commit 3ee7b5bfc74cc6794685f9c2d526e4ce7ca06be4 Author: CaiHQ Date: Wed Mar 15 01:15:57 2023 +0800 initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..77fe0bc --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.idea +node_modules +dist +package-lock.json +pnpm-lock.yaml diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..217bcf0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 The BDWare Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..6402e15 --- /dev/null +++ b/README.md @@ -0,0 +1,79 @@ +# BDContract SDK + +BDContract SDK for Node.js and browsers. + +## Install + +`npm install @bdware/bdcontract-sdk` + +```typescript +import { Client } from '@bdware/bdcontract-sdk' +import { sm2 } from 'sm-crypto' +const client = new Client( + url, + (ev) => { + console.log(JSON.stringify(ev)) + }, + (ev, ws) => { + console.log(ev.data) + }, + sm2.generateKeyPairHex(), +) +``` + +To use with plain HTML and JavaScript, include [dist/bdcontract-sdk.umd.js](dist/bdcontract-sdk.umd.js) (example from [test/index.html](test/index.html)): + +```HTML + + + +``` + +## Usage + +```javascript +// Approach 1: +const wssocket = new WsSocket(url, wsHandler) + +// Approach 2: +function print(string) { + document.write(string + '\n\n') +} + +const url = 'ws://021.node.internetapi.cn:21030/SCIDE/SCExecutor' + +const client = new bdcontract.Client( + url, + (ev) => { + console.log(JSON.stringify(ev)) + }, + (ev, ws) => { + console.log(ev.data) + }, +) +setTimeout(async () => { + const status = client.status() + console.log(status) + try { + let data = await client.executeContract( + 'AnnotationExample0608', + 'main', + 'abacd', + ) + print(JSON.stringify(data)) + } catch (data) { + print(JSON.stringify(data)) + } +}, 1000) + +// Wait for session receival +const session = await client.sessionReceived() + +// Login and wait (will wait if session not yet received) +const success = await client.login() + +async function anotherPlace() { + // In another place, wait for login to complete + const success = await client.Loggedin() +}() +``` diff --git a/lib/index.d.ts b/lib/index.d.ts new file mode 100644 index 0000000..d3169af --- /dev/null +++ b/lib/index.d.ts @@ -0,0 +1,238 @@ +import { AESKey, RSAKey } from '@daotl/cryptico'; +import { AxiosRequestConfig } from 'axios'; +import { KeyPairHex } from 'sm-crypto'; + +declare function aesEncrypt(data: string, aesKey: AESKey): string; +declare function rsaEncrypt(data: string, rsaKey: { + n: string; + e1: string; +}): string; +declare function loadRSAKey(rsaKey: string): RSAKey; +declare function encryptReq(reqContent: { + contractID: string; +}, pubKey: RSAKey): { + action: string | null; + contractID: string; + arg: string; + requester: string; +}; + +type ClientResponse = Omit & { + data?: Data; +}; +type PingResponse = ClientResponse<'pong'>; +interface SaveFileRequest { + content: string; + isAppend: boolean; + isPrivate: boolean; + path: string; +} +interface ListProjectPermissionRequest { + isPrivate: boolean; + path: string; +} +interface ListProjectPermissionResponseData { + permissions: string[]; + ypk: string; +} +interface StartContractByYpkRequest { + isPrivate: boolean; + path: string; + script: string; +} +interface ListAllUsersResponseDataListItem { + key: string; + value: string; +} +interface ListAllUsersResponseData { + kv: ListAllUsersResponseDataListItem[]; + time: ListAllUsersResponseDataListItem[]; +} +interface OnlineContractsItem { + contractID: string; + contractName: string; + isMaster: boolean; + type: string; + yjsType: string; + [key: string]: unknown; +} +interface OnlineItem { + cimanager: string; + contractVersion: number; + events: number; + ipPort: string; + masterAddress: string; + nodeName: string; + peerID: string; + pubKey: string; + contracts: OnlineContractsItem[]; +} +interface ListNodesResponse { + action: string; + offline: string[]; + online: OnlineItem[]; +} +interface DistributeContractResponse { + action: string; + progress: string; +} +interface ExecuteContractArgs extends RequestInit { + method?: 'POST' | 'GET'; + withSignature?: boolean; + withDynamicAnalysis?: boolean; +} +interface ExecuteContractResponse { + status?: boolean; + data?: Data; + executeTime?: number; + cid?: string; + isPrivate?: boolean; + [key: string]: unknown; +} +interface ConfigNodeArgs { + nodeName?: string; + dataChain?: string; + masterAddress?: string; + nodeCenter?: string; + LHSProxyAddress?: string; + [K: string]: string | undefined; +} +interface LoadNodeConfigResponseData { + doipConfig: string; + [K: string]: string; +} + +declare class HttpClient { + private baseUrl; + private sm2Key; + private fetch; + constructor(baseUrl: string, sm2Key: KeyPairHex, config?: AxiosRequestConfig); + requestWithSignature(path: string, init?: Partial, sm2Key?: KeyPairHex): Promise>; + retryRequestWithSignature(retryTimes: number, path: string, init?: Partial, sm2Key?: KeyPairHex): Promise>; + sign(data: string, privateKey?: string): string; + ping(): Promise; + startContract(code: string): Promise>; + startContractByYPK(_request: StartContractByYpkRequest): Promise>; + executeContract(contractID: string, operation: string, arg: string, { method, withDynamicAnalysis, withSignature, }?: ExecuteContractArgs): Promise>>; + killContractProcess(contractID: string, requestID?: string): Promise>; + killAllContract(): Promise>; + applyNodeRole(role: string): Promise>; + authNodeRole(isAccept: boolean, authorizedPubKey: string, managerPair?: KeyPairHex): Promise>; + distributeContract(nodeIDs: string, projectName: string, isPrivate: boolean): void; + saveFile(_request: SaveFileRequest): Promise>; + listProjectPermission(_request: ListProjectPermissionRequest): Promise>; + startContractMultiPoint(peersID: string, type: number, selectUnitNum: number, projectName: string, isPrivate: boolean, sponsorPeerID: string): Promise>; + loadNodeConfig(): Promise>; + updateConfig(key: string, val: string): Promise>; + resetNodeManager(): Promise; + lockEdit(): Promise>; + unlockEdit(): Promise>; + addNode(nodePubKey: string): Promise>; + applyRole(role: string): Promise>; + authNodeManager(isAccept: boolean, authorizedPubKey: string): Promise>; + listAllUsers(): Promise>; + listNodes(): Promise; + createTrustUnit(data: { + nodeName: string; + pubkey: string; + }[], Msg: string): Promise<{ + action: string; + status: string; + }>; + listTrustUnits(): Promise>; + listContractProcess(): Promise>; + downloadContract(projectName: string, isPrivate: boolean, timestamp: number): Promise>; + configNode(args: ConfigNodeArgs): Promise; +} + +interface WsEvent { + data: string; +} +type OnOpenHandler = (this: WebSocket, ev: Event) => void; +type WsHandler = (ev: WsEvent, ws?: WebSocket) => void; +interface SegmentData { + action: 'sendSeg'; + cid: string; + data: string; +} +declare class WsSocket { + private handlerList; + private toSend; + private isSending; + private sendList; + private toReceive; + private wssocket; + constructor(wsurl: string, onopen: OnOpenHandler, handler?: WsHandler); + status(): WebSocket['CLOSED' | 'CLOSING' | 'CONNECTING' | 'OPEN']; + sendNextSegment(): void; + receiveSeg(obj: SegmentData): void; + monitor(): void; + send(data: string): void; + addHandler(handler: WsHandler): void; +} + +interface ResponseData { + action: string; + responseID?: string; + status: true | false | string; + result?: unknown; + data: string; + [K: string]: unknown; +} +declare class WsClient { + private readonly sm2Key; + private readonly wssocket; + private readonly promiseCallbackPairs; + private readonly sessionPromise; + private sessionResolve; + private readonly loginPromise; + private loginResolve; + constructor(url: string, onopen: OnOpenHandler, handler: WsHandler, sm2Key?: KeyPairHex); + status(): WebSocket['CLOSED' | 'CLOSING' | 'CONNECTING' | 'OPEN']; + sessionReceived(): Promise; + login(): Promise; + loggedIn(): Promise; + matchCID(contractID: string): Promise; + getMetabyCID(contractID: string): Promise; + getMetabyReadme(keyword: string, page?: string, pageSize?: string): Promise; + getMetabyPubkey(pubkey: string): Promise; + segmentWord(words: string): Promise; + getMetabyOwner(owner: string, page?: string, pageSize?: string): Promise; + getDependentContract(contractName: string): Promise; + queryContractLogByDate(start: number): Promise; + queryDataByHash(hash: string): Promise; + executeContract(contractID: string, method: string, arg: unknown): Promise; + getSessionID(): Promise; + listTheContractProcess(contractID: string): Promise; + getMask(contractID: string): Promise; + setMask(contractID: string, operation: string, arg: string): Promise; + getMock(contractID: string): Promise; + setMock(contractID: string, operation: string, arg: string): Promise; + queryHashByOffset(offset: number, count: number): Promise; + loadNodeConfig(): Promise; + queryUserStat(): Promise; + listNodes(): Promise; + killContractProcess(id: string): Promise; + distributeYPK(projectName: string, nodeIDs: string): Promise; + listYPKs(): Promise; + deleteFile(file: string): Promise; + startContractByYPK(project: string): Promise; + initBDServer(host: string, username: string, password: string, name: string, clusterHost: string): Promise; + initBDCluster(host: string, username: string, password: string, name: string, sm2Key: string, agents: []): Promise; + listCompiledFiles(): Promise; + getManagerPubkey(): Promise; + getClusterName(): Promise; + setClusterName(name: string): Promise; +} + +export { ClientResponse, ConfigNodeArgs, DistributeContractResponse, ExecuteContractArgs, ExecuteContractResponse, HttpClient, ListAllUsersResponseData, ListAllUsersResponseDataListItem, ListNodesResponse, ListProjectPermissionRequest, ListProjectPermissionResponseData, LoadNodeConfigResponseData, OnOpenHandler, OnlineContractsItem, OnlineItem, PingResponse, SaveFileRequest, StartContractByYpkRequest, WsClient, WsEvent, WsHandler, WsSocket, aesEncrypt, encryptReq, loadRSAKey, rsaEncrypt }; diff --git a/lib/index.js b/lib/index.js new file mode 100644 index 0000000..fe96a4a --- /dev/null +++ b/lib/index.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@daotl/cryptico"),require("@lifeomic/axios-fetch"),require("axios"),require("sm-crypto")):"function"==typeof define&&define.amd?define(["exports","@daotl/cryptico","@lifeomic/axios-fetch","axios","sm-crypto"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).bdcontract={},e.cryptico,e.axiosFetch,e.axios,e.smCrypto)}(this,(function(e,t,s,i,r){"use strict";function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=a(i);function o(e,s){const i=s.slice(0);t.aes.ExpandKey(i);let r=t.cryptico.string2bytes(e);r=t.cryptico.pad16(r),t.aes.Encrypt(r,i);let a=t.cryptico.bytes2string(r);return a=t.cryptico.b256to64(a),a}const c=e=>Object.entries(e).map((([e,t])=>`${e}=${String(t)}`)).join("&");class h{handlerList=[];toSend="";isSending=!1;sendList=[];toReceive="";wssocket;constructor(e,t,s){console.log(`[createWS.js] createWssocket : ${e}`),s&&this.handlerList.push(s),this.monitor();const i=this,r=this.wssocket=new WebSocket(e);r.onerror=function(e){console.log(e)},r.onopen=t;const a=function(e){const t=JSON.parse(e.data);switch(t.action){case"sendNextSegment":i.sendNextSegment();break;case"sendSeg":i.receiveSeg(t);break;default:i.handlerList.forEach((t=>t(e,this)))}};r.onmessage=a;const n=function(){setTimeout((()=>{console.log("[createWS.js] try to reconnect");const s=i.wssocket=new WebSocket(e);s.onclose=n,s.onmessage=a,s.onopen=t}),1e3)};r.onclose=n}status(){return this.wssocket.readyState}sendNextSegment(){const e=this.toSend;if(e.length>1024){this.toSend=e.substr(1024);const t={isSegment:!0,data:e.substr(0,1024)};this.wssocket.send(JSON.stringify(t))}else{this.toSend="";const t={isSegment:!1,data:e};let s;this.wssocket.send(JSON.stringify(t)),this.isSending=!1,(s=this.sendList.pop())&&this.send(s)}}receiveSeg(e){if("start"===e.cid&&(this.toReceive=""),this.toReceive+=e.data,"done"===e.cid){console.log(`[receiveSeg] Received AllData:${this.toReceive}`);const e={data:this.toReceive};this.toReceive="",this.handlerList.forEach((t=>t(e,this.wssocket)))}}monitor(){if(!this.isSending){let e;(e=this.sendList.pop())&&this.send(e)}setTimeout((()=>this.monitor()),1e3)}send(e){if(this.isSending)this.sendList.push(e);else if(e.length>1024){this.isSending=!0,this.toSend=e.substr(1024);const t={isSegment:!0,data:e.substr(0,1024)};this.wssocket.send(JSON.stringify(t))}else this.wssocket.send(e)}addHandler(e){this.handlerList.push(e)}}e.HttpClient=class{baseUrl;sm2Key;fetch;constructor(e,t,i={}){this.baseUrl=e,this.sm2Key=t;const r=n.default.create({baseURL:"https://some-domain.com/api/",timeout:1e4,...i});this.fetch=s.buildAxiosFetch(r)}async requestWithSignature(e,t,s){return new Promise(((i,r)=>{const a=this.baseUrl+e,n=`${a}${e.includes("?")?"&":"?"}pubKey=${s?.publicKey??this.sm2Key.publicKey}`,o=this.sign(n.substring(n.indexOf("?")+1),s?.privateKey);this.fetch("post"===t?.method?.toLowerCase()?a:`${encodeURI(n)}&sign=${o}`,{...t,..."POST"===t?.method?{body:{...t?.body,sign:o}}:{}}).then((async e=>{const t=e;t.data=await e.text(),setTimeout((()=>{i(t)}),1)})).catch((e=>{setTimeout((()=>{r(e)}),1)}))}))}async retryRequestWithSignature(e,t,s,i){let r=new Error;for(let a=0;at));await Promise.all([...t.map((([e,t])=>this.updateConfig(e,t))),this.applyNodeRole("ContractProvider"),this.applyNodeRole("ContractUser"),this.applyNodeRole("ContractInstanceManager"),this.authNodeRole(!0,this.sm2Key.publicKey)]);const s=(await this.loadNodeConfig()).data;return!!s&&t.every((([e,t])=>s[function(e){if("dataChain"===e)return"bdledger";return e}(e)]===t))}},e.WsClient=class{sm2Key;wssocket;promiseCallbackPairs={};sessionPromise;sessionResolve;loginPromise;loginResolve;constructor(e,t,s,i=r.sm2.generateKeyPairHex()){this.sm2Key=i,this.sessionPromise=new Promise(((e,t)=>{this.sessionResolve=e})),this.loginPromise=new Promise(((e,t)=>{this.loginResolve=e}));const a=this;this.wssocket=new h(e,t,(function(e,t){const i=JSON.parse(e.data);switch(i.action){case"onSessionID":a.sessionResolve(i.session);break;case"onLogin":{const e="string"==typeof i.status&&i.status.toLowerCase().includes("failed");a.loginResolve(!e)}}const r=i.responseID;let n;r&&(n=a.promiseCallbackPairs[r])&&(i?n.resolve(i):n.reject(i)),s(e,this)}))}status(){return this.wssocket.status()}sessionReceived(){return this.sessionPromise}async login(){const e=await this.sessionPromise,t={action:"login",pubKey:this.sm2Key.publicKey,signature:r.sm2.doSignature(e,this.sm2Key.privateKey,{hash:!0,der:!0})};return this.wssocket.send(JSON.stringify(t)),this.loginPromise}loggedIn(){return this.loginPromise}matchCID(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"matchCID",contractID:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}getMetabyCID(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"getMetabyCID",contractID:e,requestID:t};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}getMetabyReadme(e,t,s){const i=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,r={action:"getMetabyReadme",page:t,pageSize:s,keyword:e,requestID:i};return this.wssocket.send(JSON.stringify(r)),new Promise(((e,t)=>{this.promiseCallbackPairs[i]={resolve:e,reject:t}}))}getMetabyPubkey(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"getMetabyPubkey",pubkey:e,requestID:t};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}segmentWord(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={words:e,action:"segmentWord",requestID:t};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}getMetabyOwner(e,t,s){const i=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,r={action:"getMetabyOwner",owner:e,page:t,pageSize:s,requestID:i};return this.wssocket.send(JSON.stringify(r)),new Promise(((e,t)=>{this.promiseCallbackPairs[i]={resolve:e,reject:t}}))}getDependentContract(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"getDependentContract",requestID:t,contractName:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}queryContractLogByDate(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"queryContractLogByDate",requestID:t,start:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}queryDataByHash(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"queryDataByHash",requestID:t,hash:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}executeContract(e,t,s){const i=this.sm2Key,a=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,n="object"==typeof s?JSON.stringify(s):s+"",o={action:"executeContract",requestID:a,contractID:e,operation:t,arg:s,...i?{pubkey:i.publicKey,signature:r.sm2.doSignature(`${e}|${t}|${n}|${i.publicKey}`,i.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(o)),new Promise(((e,t)=>{this.promiseCallbackPairs[a]={resolve:e,reject:t}}))}getSessionID(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"getSessionID",requestID:e};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}listTheContractProcess(e){const t=this.sm2Key,s=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,i={action:"listTheContractProcess",requestID:s,contractID:e,...t?{pubkey:t.publicKey,signature:r.sm2.doSignature(`${e}|${t.publicKey}`,t.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(i)),new Promise(((e,t)=>{this.promiseCallbackPairs[s]={resolve:e,reject:t}}))}getMask(e){const t=this.sm2Key,s=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,i={action:"getMask",requestID:s,contractID:e,...t?{pubkey:t.publicKey,signature:r.sm2.doSignature(`${e}|${t.publicKey}`,t.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(i)),new Promise(((e,t)=>{this.promiseCallbackPairs[s]={resolve:e,reject:t}}))}setMask(e,t,s){const i=this.sm2Key,a=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,n={action:"setMask",requestID:a,contractID:e,operation:t,arg:s,...i?{pubkey:i.publicKey,signature:r.sm2.doSignature(`${e}|${i.publicKey}`,i.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(n)),new Promise(((e,t)=>{this.promiseCallbackPairs[a]={resolve:e,reject:t}}))}getMock(e){const t=this.sm2Key,s=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,i={action:"getMock",requestID:s,contractID:e,...t?{pubkey:t.publicKey,signature:r.sm2.doSignature(`${e}|${t.publicKey}`,t.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(i)),new Promise(((e,t)=>{this.promiseCallbackPairs[s]={resolve:e,reject:t}}))}setMock(e,t,s){const i=this.sm2Key,a=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,n={action:"setMock",requestID:a,contractID:e,operation:t,arg:s,...i?{pubkey:i.publicKey,signature:r.sm2.doSignature(`${e}|${i.publicKey}`,i.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(n)),new Promise(((e,t)=>{this.promiseCallbackPairs[a]={resolve:e,reject:t}}))}queryHashByOffset(e,t){const s=this.sm2Key,i=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,r={action:"queryHashByOffset",requestID:i,offset:e,count:t,...s?{pubkey:s.publicKey}:{}};return this.wssocket.send(JSON.stringify(r)),new Promise(((e,t)=>{this.promiseCallbackPairs[i]={resolve:e,reject:t}}))}loadNodeConfig(){const e=this.sm2Key,t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"loadNodeConfig",requestID:t,...e?{pubkey:e.publicKey,signature:r.sm2.doSignature(e.publicKey,e.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}queryUserStat(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"queryUserStat",requestID:e};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}listNodes(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"listNodes",requestID:e};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}killContractProcess(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"killContractProcess",requestID:t,id:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}distributeYPK(e,t){const s=this.sm2Key,i=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,a={action:"distributeYPK",requestID:i,pubKey:s.publicKey,projectName:e,nodeIDs:t,signature:r.sm2.doSignature(`DistributeYPK|${e}|${s.publicKey}`,s.privateKey,{hash:!0,der:!0})};return this.wssocket.send(JSON.stringify(a)),new Promise(((e,t)=>{this.promiseCallbackPairs[i]={resolve:e,reject:t}}))}listYPKs(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"listYPKs",requestID:e};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}deleteFile(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"deleteFile",requestID:t,file:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}startContractByYPK(e){const t=this.sm2Key,s=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,i={action:"startContractByYPK",isPrivate:!0,requestID:s,owner:t.publicKey,path:`/${e}`,signature:r.sm2.doSignature(`Fixed|${e}|${t.publicKey}`,t.privateKey)};return this.wssocket.send(JSON.stringify(i)),new Promise(((e,t)=>{this.promiseCallbackPairs[s]={resolve:e,reject:t}}))}initBDServer(e,t,s,i,r){const a=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,n={action:"initBDServer",requestID:a,host:e,username:t,password:s,name:i,sm2Key:JSON.stringify(this.sm2Key),clusterHost:r};return this.wssocket.send(JSON.stringify(n)),new Promise(((e,t)=>{this.promiseCallbackPairs[a]={resolve:e,reject:t}}))}initBDCluster(e,t,s,i,r,a){const n=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,o={action:"initBDCluster",requestID:n,host:e,username:t,password:s,name:i,sm2Key:r,agents:a};return this.wssocket.send(JSON.stringify(o)),new Promise(((e,t)=>{this.promiseCallbackPairs[n]={resolve:e,reject:t}}))}listCompiledFiles(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"listCompiledFiles",requestID:e,isPrivate:!0};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}getManagerPubkey(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"getManagerPubkey",requestID:e};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}getClusterName(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"getClusterName",requestID:e};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}setClusterName(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"setClusterName",requestID:t,name:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}},e.WsSocket=h,e.aesEncrypt=o,e.encryptReq=function(e,s){const i={key:t.cryptico.generateAESKey()},r=JSON.stringify(i),{contractID:a}=e,n={...e,contractID:void 0};return{action:s.decrypt(r),contractID:a,arg:o(JSON.stringify(n),i.key),requester:t.cryptico.b256to64(`${s.n.toString(16)},${s.e.toString(16)},0`)}},e.loadRSAKey=function(e){const s=t.cryptico.b64to256(e).split(","),i=new t.RSAKey;return i.setPrivate(s[0],s[0],s[0]),i},e.rsaEncrypt=function(e,s){const i=new t.RSAKey;return i.setPublic(s.n,s.e1),i.encrypt(e)},Object.defineProperty(e,"__esModule",{value:!0})})); +//# sourceMappingURL=index.js.map diff --git a/lib/index.js.map b/lib/index.js.map new file mode 100644 index 0000000..fddf2f1 --- /dev/null +++ b/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../src/crypto.ts","../src/httpClient.ts","../src/wssocket.ts","../src/wsClient.ts"],"sourcesContent":["// export function aesDecrypt(data: base64) {\n// const dataAscii = cryptico.b64to256(data)\n// const encryptedBlocks = cryptico.string2bytes(dataAscii)\n// const exkey = global.aesKey.slice(0)\n// aes.ExpandKey(exkey)\n// aes.Decrypt(encryptedBlocks, exkey)\n// return cryptico.bytes2string(encryptedBlocks)\n// }\n\nimport type { AESKey } from '@daotl/cryptico'\nimport { aes, cryptico, RSAKey } from '@daotl/cryptico'\n\nexport function aesEncrypt(data: string, aesKey: AESKey): string {\n const exkey = aesKey.slice(0)\n aes.ExpandKey(exkey)\n let blocks = cryptico.string2bytes(data)\n blocks = cryptico.pad16(blocks)\n aes.Encrypt(blocks, exkey)\n let ciphertext = cryptico.bytes2string(blocks)\n ciphertext = cryptico.b256to64(ciphertext)\n return ciphertext\n}\n\nexport function rsaEncrypt(\n data: string,\n rsaKey: { n: string; e1: string },\n): string {\n const rsa = new RSAKey()\n rsa.setPublic(rsaKey.n, rsaKey.e1)\n return rsa.encrypt(data)\n}\n\nexport function loadRSAKey(rsaKey: string): RSAKey {\n const str = cryptico.b64to256(rsaKey)\n const strs = str.split(',')\n const key = new RSAKey()\n key.setPrivate(strs[0], strs[0], strs[0])\n return key\n}\n\n// function testRSA() {\n// pubKey = loadRSAKey(global.privKey)\n// reqContent = {}\n// reqContent.action = 'main'\n// reqContent.arg = '[{\"score\":20},{\"score\":20}]'\n// reqContent.contractID = 'abc'\n// eReq = encryptReq(reqContent, pubKey)\n// url =\n// 'http://localhost:8080/SCIDE/SCManager?action=executeContractEncrypted&contractRequest=' +\n// encodeURIComponent(JSON.stringify(eReq))\n// }\n\nexport function encryptReq(\n reqContent: { contractID: string },\n pubKey: RSAKey,\n): {\n action: string | null\n contractID: string\n arg: string\n requester: string\n} {\n const aes = {\n key: cryptico.generateAESKey(),\n }\n const aesObj = JSON.stringify(aes)\n const { contractID } = reqContent\n const reqContentNoId = { ...reqContent, contractID: undefined }\n const encrypedReq = {\n action: pubKey.decrypt(aesObj),\n contractID,\n arg: aesEncrypt(JSON.stringify(reqContentNoId), aes.key),\n requester: cryptico.b256to64(\n `${pubKey.n.toString(16)},${pubKey.e.toString(16)},0`,\n ),\n }\n return encrypedReq\n}\n","import { buildAxiosFetch } from '@lifeomic/axios-fetch'\nimport axios, { type AxiosRequestConfig } from 'axios'\nimport type { KeyPairHex } from 'sm-crypto'\nimport { sm2 } from 'sm-crypto'\n\nimport type {\n ClientResponse,\n ConfigNodeArgs,\n ExecuteContractArgs,\n ListAllUsersResponseData,\n ListNodesResponse,\n ListProjectPermissionRequest,\n ListProjectPermissionResponseData,\n LoadNodeConfigResponseData,\n ExecuteContractResponse,\n PingResponse,\n SaveFileRequest,\n StartContractByYpkRequest,\n} from './types'\n\nconst genUrlParamsFromObject = (obj: Record): string => {\n return Object.entries(obj)\n .map(([key, value]) => `${key}=${String(value)}`)\n .join('&')\n}\n\nexport * from './types'\n\nexport class HttpClient {\n private fetch: (input: RequestInfo, init?: RequestInit) => Promise\n\n constructor(\n private baseUrl: string,\n private sm2Key: KeyPairHex,\n config = {} as AxiosRequestConfig,\n ) {\n const axiosInstance = axios.create({\n baseURL: 'https://some-domain.com/api/',\n timeout: 10000,\n // headers: {'X-Custom-Header': 'foobar'}\n ...config,\n })\n\n this.fetch = buildAxiosFetch(\n axiosInstance /* , function (config) {\n config.timeout = 1000;\n return config;\n } */,\n )\n }\n\n async requestWithSignature(\n path: string,\n init?: Partial,\n sm2Key?: KeyPairHex,\n ): Promise> {\n return new Promise>((resolve, reject) => {\n const rawUrl = this.baseUrl + path\n const url = `${rawUrl}${path.includes('?') ? '&' : '?'}pubKey=${\n sm2Key?.publicKey ?? this.sm2Key.publicKey\n }`\n\n // console.log('privateKey:', this.sm2Key.privateKey)\n\n // console.log('publicKey:', this.sm2Key.publicKey)\n\n // console.log('to sign:', url.substring(url.indexOf('?') + 1))\n\n const sign = this.sign(\n url.substring(url.indexOf('?') + 1),\n sm2Key?.privateKey,\n )\n\n // console.log(\n // 'url:',\n // init?.method?.toLowerCase() === 'post'\n // ? rawUrl\n // : `${encodeURI(url)}&sign=${sign}`,\n // )\n\n this.fetch(\n init?.method?.toLowerCase() === 'post'\n ? rawUrl\n : `${encodeURI(url)}&sign=${sign}`,\n {\n ...init,\n ...(init?.method === 'POST'\n ? {\n body: {\n ...(init?.body as unknown as Record),\n sign,\n } as unknown as Request['body'],\n }\n : {}),\n },\n )\n .then(async (res) => {\n // console.log(res.url,'请求成功')\n const clientRes = res as unknown as ClientResponse\n clientRes.data = (await res.text()) as Data\n // Workaround for the issue causing the 2nd consecutive request to fail:\n // https://github.com/nodejs/undici/issues/1415\n setTimeout(() => {\n resolve(clientRes)\n }, 1)\n })\n .catch((err) => {\n // const clientRes = err as unknown as ClientResponse\n // clientRes.data = (await err.text()) as Data\n // console.log(err,'errerrerrerrerrerrerrerrerrerrerrerrerrerrerr')\n setTimeout(() => {\n reject(err)\n }, 1)\n })\n })\n }\n\n async retryRequestWithSignature(retryTimes: number, path: string, init?: Partial, sm2Key?: KeyPairHex ) {\n let err: Error = new Error()\n for (let i = 0; i(path, init, sm2Key)\n } catch (e) {\n if (i < retryTimes) {\n console.log('1')\n continue\n }\n err = e as Error\n }\n }\n throw err\n }\n\n sign(data: string, privateKey?: string): string {\n return sm2.doSignature(data, privateKey ?? this.sm2Key.privateKey, {\n hash: true,\n der: true,\n })\n }\n\n // ping\n // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html#id15\n ping(): Promise {\n return this.requestWithSignature('/SCManager?action=ping')\n }\n\n // 启动合约\n // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html#id60\n startContract(code: string): Promise> {\n const params = { action: 'startContract', script: code }\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject(params)}`,\n )\n }\n\n // 启动合约\n // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html#id13\n startContractByYPK(\n _request: StartContractByYpkRequest,\n ): Promise> {\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'startContractByYPK',\n ..._request,\n owner: this.sm2Key.publicKey,\n aim: 'onStartContract',\n signature: sm2.doSignature(\n `Fixed|${_request.path}|${this.sm2Key.publicKey}`,\n this.sm2Key.privateKey,\n {\n hash: true,\n der: true,\n },\n ),\n })}`,\n )\n }\n\n // 调用合约\n // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html#id69\n executeContract(\n contractID: string,\n operation: string,\n arg: string,\n {\n method = 'POST',\n withDynamicAnalysis = false,\n withSignature = false,\n } = {} as ExecuteContractArgs,\n ): Promise>> {\n let request = {}\n if (withDynamicAnalysis === undefined) {\n request = {\n action: 'executeContract',\n contractID,\n operation,\n arg,\n }\n } else {\n request = {\n action: 'executeContract',\n contractID,\n operation,\n withDynamicAnalysis,\n arg,\n }\n }\n if (withSignature) {\n request = {\n ...request,\n pubkey: this.sm2Key.publicKey,\n signature: this.sign(\n `${contractID}|${operation}|${arg ?? ''}|${this.sm2Key.publicKey}`,\n ),\n }\n }\n\n return this.retryRequestWithSignature(\n 3,\n `/SCManager${\n method === 'GET' ? `?${genUrlParamsFromObject(request)}` : ''\n }`,\n {\n method,\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n ...(method === 'POST' ? ({ body: request } as Request) : {}),\n },\n )\n }\n\n // 停止合约\n // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html#id122\n killContractProcess(\n contractID: string,\n requestID?: string,\n ): Promise> {\n const _request: Record = {\n action: 'killContractProcess',\n id: contractID,\n }\n requestID && (_request.requestID = requestID!)\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject(_request)}`,\n )\n }\n\n // 停止所有合约\n // 地址 http://39.104.205.122:18010/SCIDE\n // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html#id131\n killAllContract(): Promise> {\n return this.requestWithSignature('/SCManager?action=killAllContract')\n }\n\n // 申请角色\n // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html\n applyNodeRole(\n role: string,\n ): Promise> {\n const _request = {\n action: 'applyNodeRole',\n role,\n }\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject(_request)}`,\n )\n }\n\n // 授权角色\n // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html\n authNodeRole(\n isAccept: boolean,\n authorizedPubKey: string,\n managerPair?: KeyPairHex,\n ): Promise> {\n const _request = {\n action: 'authNodeRole',\n isAccept,\n authorizedPubKey,\n }\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject(_request)}`,\n undefined,\n managerPair,\n )\n }\n\n // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html\n // 用sse获取 问题未解决!!!\n distributeContract(\n nodeIDs: string,\n projectName: string,\n isPrivate: boolean,\n ): void {\n const signature = sm2.doSignature(\n `DistributeContract|${projectName}|${this.sm2Key.publicKey}`,\n this.sm2Key.privateKey,\n { hash: true, der: true },\n )\n\n const _request = {\n action: 'distributeContract',\n nodeIDs,\n projectName,\n isPrivate,\n signature,\n }\n\n const path = `/SCManager?${genUrlParamsFromObject(_request)}`\n const url = `${this.baseUrl + path}${\n path.includes('?') ? '&' : '?'\n }pubKey=${this.sm2Key.publicKey}`\n const sig = sm2.doSignature(\n url.substring(url.indexOf('?') + 1),\n this.sm2Key.privateKey,\n {\n hash: true,\n der: true,\n },\n )\n const source = new EventSource(\n `${this.baseUrl}${path}&pubKey=${this.sm2Key.publicKey}&sign=${sig}`,\n )\n source.addEventListener(\n 'message',\n function (_event) {\n // const data = event.data as DistributeContractResponse[]\n // console.log(data, 'dd')\n // handle message\n },\n false,\n )\n }\n\n saveFile(_request: SaveFileRequest): Promise> {\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'saveFile',\n ..._request,\n })}`,\n )\n }\n\n listProjectPermission(\n _request: ListProjectPermissionRequest,\n ): Promise> {\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'listProjectPermission',\n ..._request,\n })}`,\n )\n }\n\n startContractMultiPoint(\n peersID: string,\n type: number,\n selectUnitNum: number,\n projectName: string,\n isPrivate: boolean,\n sponsorPeerID: string,\n ): Promise> {\n const _request = {\n // peerID是节点的公钥,以逗号间隔开\n peersID,\n type,\n selectUnitNum,\n projectName,\n isPrivate,\n sponsorPeerID,\n }\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'startContractMultiPoint',\n ..._request,\n })}`,\n )\n }\n\n // 获取节点配置信息\n async loadNodeConfig(): Promise> {\n const res = await this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'loadNodeConfig',\n })}`,\n )\n return { ...res, data: (res.status === 200 && res.data ? JSON.parse( res.data).data : {}) as LoadNodeConfigResponseData}\n }\n\n // 支持的key包括:{licence,projectDir,yjsPath,dataChain,doipConfig,nodeCenter,nodeName,masterAddress,resetNodeCenterWS}\n async updateConfig(\n key: string,\n val: string,\n ): Promise> {\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'updateConfig',\n key,\n val,\n })}`,\n )\n }\n\n // 设置pubkey为node manager\n async resetNodeManager(): Promise {\n const res = await this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'resetNodeManager',\n })}`,\n )\n if (!res.data) {\n return false\n }\n const parsed = JSON.parse(res.data)\n return parsed.data === 'success'\n }\n\n // 锁定某个用户的的私有目录编辑功能\n lockEdit(): Promise> {\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'lockEdit',\n })}`,\n )\n }\n\n // 解锁某个用户的的私有目录编辑功能\n unlockEdit(): Promise> {\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'unlockEdit',\n })}`,\n )\n }\n\n addNode(nodePubKey: string): Promise> {\n return this.requestWithSignature(\n `?${genUrlParamsFromObject({\n action: 'addNode',\n nodePubKey,\n })}`,\n )\n }\n\n // 申请角色\n applyRole(role: string): Promise> {\n return this.requestWithSignature(\n `?${genUrlParamsFromObject({\n action: 'applyRole',\n role,\n })}`,\n )\n }\n\n authNodeManager(\n isAccept: boolean,\n authorizedPubKey: string,\n ): Promise> {\n return this.requestWithSignature(\n `?${genUrlParamsFromObject({\n action: 'authNodeManager',\n isAccept,\n authorizedPubKey,\n })}`,\n )\n }\n\n listAllUsers(): Promise> {\n return this.requestWithSignature(\n `?${genUrlParamsFromObject({\n action: 'listAllUsers',\n })}`,\n )\n }\n\n // 查看节点列表\n listNodes(): Promise {\n return this.requestWithSignature(\n `?${genUrlParamsFromObject({\n action: 'listNodes',\n })}`,\n ) as unknown as Promise\n }\n\n // 建立可信执行集群\n async createTrustUnit(\n data: { nodeName: string; pubkey: string }[],\n Msg: string,\n ): Promise<{ action: string; status: string }> {\n const toSign = `action=createTrustUnit&data=${JSON.stringify(\n data,\n )}&msg=${Msg}&pubKey=04303718771b9323c204e607639f14469f9a94e55b0964a408ad3b3864b0493b645d7070da0d550f0c54b934275a8e88dedc3024467b0566db5c1108b1baeaae27`\n const sig = sm2.doSignature(toSign, this.sm2Key.privateKey, {\n hash: true,\n der: true,\n })\n\n const body = {\n action: 'createTrustUnit',\n data,\n msg: Msg,\n pubKey:\n '04303718771b9323c204e607639f14469f9a94e55b0964a408ad3b3864b0493b645d7070da0d550f0c54b934275a8e88dedc3024467b0566db5c1108b1baeaae27',\n sign: sig,\n }\n return (await this.requestWithSignature('', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n })) as unknown as { action: string; status: string }\n }\n\n // 查看可信执行集群列表\n listTrustUnits(): Promise> {\n return this.requestWithSignature(\n `?${genUrlParamsFromObject({\n action: 'listTrustUnits',\n })}`,\n )\n }\n\n // listContractProcess 查询合约实例列表\n listContractProcess(): Promise> {\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'listContractProcess',\n })}`,\n )\n }\n\n // 下载合约\n downloadContract(\n projectName: string,\n isPrivate: boolean,\n timestamp: number\n ): Promise> {\n const _request = {\n action: 'downloadContract',\n projectName,\n isPrivate,\n timestamp,\n }\n return this.requestWithSignature(\n `/CMManager?${genUrlParamsFromObject(_request)}`)\n }\n\n // 配置合约引擎节点,若节点没有设置过node manager,将当前key设置为node manager\n async configNode(\n args: ConfigNodeArgs,\n ): Promise {\n if (!(await this.resetNodeManager())) {\n return false\n }\n\n const kvs: [string, string][] = Object.entries(args).filter(([_k, v]) => v) as [string, string][]\n\n await Promise.all([\n ...kvs.map(([k, v]) => this.updateConfig(k, v!)),\n this.applyNodeRole('ContractProvider'),\n this.applyNodeRole('ContractUser'),\n this.applyNodeRole('ContractInstanceManager'),\n this.authNodeRole(true, this.sm2Key.publicKey),\n ])\n\n const config = (await this.loadNodeConfig()).data\n if (!config) {\n return false\n }\n\n return kvs.every(([k, v]) => config[remapNodeConfigKey(k)] === v)\n }\n}\n\nfunction remapNodeConfigKey(k: string) {\n switch (k) {\n case 'dataChain':\n return 'bdledger'\n default:\n return k\n }\n}\n","/* eslint-disable no-console,no-cond-assign */\n\nexport interface WsEvent {\n data: string\n}\n\nexport type OnOpenHandler = (this: WebSocket, ev: Event) => void\nexport type WsHandler = (ev: WsEvent, ws?: WebSocket) => void\n\ninterface SegmentData {\n action: 'sendSeg'\n cid: string\n data: string\n}\n\nexport class WsSocket {\n private handlerList: WsHandler[] = []\n private toSend = ''\n private isSending = false\n private sendList: string[] = []\n private toReceive = ''\n private wssocket: WebSocket\n\n constructor(wsurl: string, onopen: OnOpenHandler, handler?: WsHandler) {\n console.log(`[createWS.js] createWssocket : ${wsurl}`)\n if (handler) {\n this.handlerList.push(handler)\n }\n\n // TODO: we don't need monitor at all?\n this.monitor()\n\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const that = this\n\n const wssocket = (this.wssocket = new WebSocket(wsurl))\n wssocket.onerror = function (error): void {\n console.log(error)\n }\n wssocket.onopen = onopen\n\n const onmessage = function (this: WebSocket, event: MessageEvent): void {\n const obj = JSON.parse(event.data as string) as { action: string }\n switch (obj.action) {\n case 'sendNextSegment':\n that.sendNextSegment()\n break\n case 'sendSeg':\n that.receiveSeg(obj as SegmentData)\n break\n default:\n that.handlerList.forEach((h) => h(event, this))\n }\n }\n wssocket.onmessage = onmessage\n\n const reconnect = function (): void {\n setTimeout(() => {\n console.log('[createWS.js] try to reconnect')\n const wssocket = (that.wssocket = new WebSocket(wsurl))\n wssocket.onclose = reconnect\n wssocket.onmessage = onmessage\n wssocket.onopen = onopen\n }, 1000)\n }\n wssocket.onclose = reconnect\n }\n\n status(): WebSocket['CLOSED' | 'CLOSING' | 'CONNECTING' | 'OPEN'] {\n return this.wssocket.readyState\n }\n\n sendNextSegment(): void {\n const str = this.toSend\n if (str.length > 1024) {\n this.toSend = str.substr(1024)\n const obj = {\n isSegment: true,\n data: str.substr(0, 1024),\n }\n this.wssocket.send(JSON.stringify(obj))\n } else {\n this.toSend = ''\n const obj = {\n isSegment: false,\n data: str,\n }\n this.wssocket.send(JSON.stringify(obj))\n this.isSending = false\n let data\n if ((data = this.sendList.pop())) {\n this.send(data)\n }\n }\n }\n\n receiveSeg(obj: SegmentData): void {\n if (obj.cid === 'start') {\n this.toReceive = ''\n }\n this.toReceive += obj.data\n if (obj.cid === 'done') {\n console.log(`[receiveSeg] Received AllData:${this.toReceive}`)\n const event: WsEvent = {\n data: this.toReceive,\n }\n this.toReceive = ''\n this.handlerList.forEach((h) => h(event, this.wssocket))\n }\n }\n\n monitor(): void {\n if (!this.isSending) {\n let data\n if ((data = this.sendList.pop())) {\n this.send(data)\n }\n }\n setTimeout(() => this.monitor(), 1000)\n }\n\n send(data: string): void {\n if (this.isSending) {\n this.sendList.push(data)\n return\n }\n if (data.length > 1024) {\n this.isSending = true\n this.toSend = data.substr(1024)\n const obj = {\n isSegment: true,\n data: data.substr(0, 1024),\n }\n this.wssocket.send(JSON.stringify(obj))\n } else {\n this.wssocket.send(data)\n }\n }\n\n addHandler(handler: WsHandler): void {\n this.handlerList.push(handler)\n }\n}\n","/* eslint-disable no-cond-assign */\n\nimport type { KeyPairHex } from 'sm-crypto'\nimport { sm2 } from 'sm-crypto'\n\nimport type { OnOpenHandler, WsHandler } from './wssocket'\nimport { WsSocket } from './wssocket'\n\ninterface ResponseData {\n action: string\n responseID?: string\n status: true | false | string // 'Success' | 'Exception' | 'Error' | 'failed: no session'\n result?: unknown\n data: string\n [K: string]: unknown\n}\n\n// interface ListResponseData {\n// action: string\n// data: string\n// status: true | false\n// }\n\ninterface PromiseCallbackPair {\n resolve: (value: ResponseData | PromiseLike) => void\n reject: (reason?: unknown) => void\n}\n\nexport class WsClient {\n private readonly sm2Key: KeyPairHex\n private readonly wssocket: WsSocket\n private readonly promiseCallbackPairs: Record =\n {}\n\n private readonly sessionPromise: Promise\n private sessionResolve!: (value: string | PromiseLike) => void\n private readonly loginPromise: Promise\n private loginResolve!: (value: boolean | PromiseLike) => void\n\n constructor(\n url: string,\n onopen: OnOpenHandler,\n handler: WsHandler,\n sm2Key: KeyPairHex = sm2.generateKeyPairHex(),\n ) {\n this.sm2Key = sm2Key\n this.sessionPromise = new Promise((resolve, _reject) => {\n this.sessionResolve = resolve\n })\n this.loginPromise = new Promise((resolve, _reject) => {\n this.loginResolve = resolve\n })\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const that = this\n this.wssocket = new WsSocket(url, onopen, function (\n this: WebSocket,\n event,\n _,\n ) {\n const data = JSON.parse(event.data) as ResponseData\n\n switch (data.action) {\n case 'onSessionID':\n that.sessionResolve(data.session as string)\n break\n case 'onLogin':\n {\n const failed =\n typeof data.status === 'string' &&\n data.status.toLowerCase().includes('failed')\n that.loginResolve(!failed)\n }\n break\n }\n\n const reqId = data.responseID\n let pc: PromiseCallbackPair | undefined\n if (reqId && (pc = that.promiseCallbackPairs[reqId])) {\n if (data) {\n pc.resolve(data)\n } else {\n pc.reject(data)\n }\n }\n handler(event, this)\n })\n }\n\n status(): WebSocket['CLOSED' | 'CLOSING' | 'CONNECTING' | 'OPEN'] {\n return this.wssocket.status()\n }\n\n sessionReceived(): Promise {\n return this.sessionPromise\n }\n\n async login(): Promise {\n const session = await this.sessionPromise\n const request = {\n action: 'login',\n pubKey: this.sm2Key.publicKey,\n signature: sm2.doSignature(session, this.sm2Key.privateKey, {\n hash: true,\n der: true,\n }),\n }\n this.wssocket.send(JSON.stringify(request))\n return this.loginPromise\n }\n\n loggedIn(): Promise {\n return this.loginPromise\n }\n\n matchCID(contractID: string): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'matchCID',\n contractID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getMetabyCID(contractID: string): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getMetabyCID',\n contractID,\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getMetabyReadme(\n keyword: string,\n page?: string,\n pageSize?: string,\n ): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getMetabyReadme',\n page,\n pageSize,\n keyword,\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getMetabyPubkey(pubkey: string): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getMetabyPubkey',\n pubkey,\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n segmentWord(words: string): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n words,\n action: 'segmentWord',\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getMetabyOwner(\n owner: string,\n page?: string,\n pageSize?: string,\n ): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getMetabyOwner',\n owner,\n page,\n pageSize,\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getDependentContract(contractName: string): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getDependentContract',\n requestID,\n contractName,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n queryContractLogByDate(start: number): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'queryContractLogByDate',\n requestID,\n start,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n queryDataByHash(hash: string): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'queryDataByHash',\n requestID,\n hash,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n executeContract(\n contractID: string,\n method: string,\n arg: unknown,\n ): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const argStr = (typeof arg) == 'object' ? JSON.stringify(arg):arg+\"\";\n const request = {\n action: 'executeContract',\n requestID,\n contractID,\n operation: method,\n arg: arg,\n ...(sm2Key\n ? {\n pubkey: sm2Key.publicKey,\n signature: sm2.doSignature(\n `${contractID}|${method}|${argStr}|${sm2Key.publicKey}`,\n sm2Key.privateKey,\n { hash: true, der: true },\n ),\n }\n : {}),\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getSessionID(): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getSessionID',\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n listTheContractProcess(contractID: string): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'listTheContractProcess',\n requestID,\n contractID,\n ...(sm2Key\n ? {\n pubkey: sm2Key.publicKey,\n signature: sm2.doSignature(\n `${contractID}|${sm2Key.publicKey}`,\n sm2Key.privateKey,\n { hash: true, der: true },\n ),\n }\n : {}),\n }\n this.wssocket.send(JSON.stringify(request))\n\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getMask(\n contractID: string,\n // operation: string,\n ): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getMask',\n requestID,\n contractID,\n // operation,\n ...(sm2Key\n ? {\n pubkey: sm2Key.publicKey,\n signature: sm2.doSignature(\n `${contractID}|${sm2Key.publicKey}`,\n sm2Key.privateKey,\n { hash: true, der: true },\n ),\n }\n : {}),\n }\n\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n setMask(\n contractID: string,\n operation: string,\n arg: string,\n ): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'setMask',\n requestID,\n contractID,\n operation,\n arg,\n ...(sm2Key\n ? {\n pubkey: sm2Key.publicKey,\n signature: sm2.doSignature(\n `${contractID}|${sm2Key.publicKey}`,\n sm2Key.privateKey,\n { hash: true, der: true },\n ),\n }\n : {}),\n }\n\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getMock(\n contractID: string,\n // operation: string,\n ): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getMock',\n requestID,\n contractID,\n // operation,\n ...(sm2Key\n ? {\n pubkey: sm2Key.publicKey,\n signature: sm2.doSignature(\n `${contractID}|${sm2Key.publicKey}`,\n sm2Key.privateKey,\n { hash: true, der: true },\n ),\n }\n : {}),\n }\n\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n setMock(\n contractID: string,\n operation: string,\n arg: string,\n ): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'setMock',\n requestID,\n contractID,\n operation,\n arg,\n ...(sm2Key\n ? {\n pubkey: sm2Key.publicKey,\n signature: sm2.doSignature(\n `${contractID}|${sm2Key.publicKey}`,\n sm2Key.privateKey,\n { hash: true, der: true },\n ),\n }\n : {}),\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n queryHashByOffset(offset: number, count: number): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'queryHashByOffset',\n requestID,\n offset,\n count,\n ...(sm2Key\n ? {\n pubkey: sm2Key.publicKey,\n /* signature: sm2.doSignature(\n id + '|' + sm2Key.publicKey,\n sm2Key.privateKey,\n { hash: true, der: true },\n ), */\n }\n : {}),\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n loadNodeConfig(): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'loadNodeConfig',\n requestID,\n\n ...(sm2Key\n ? {\n pubkey: sm2Key.publicKey,\n signature: sm2.doSignature(sm2Key.publicKey, sm2Key.privateKey, {\n hash: true,\n der: true,\n }),\n }\n : {}),\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n queryUserStat(): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'queryUserStat',\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n listNodes(): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'listNodes',\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n killContractProcess(id: string): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'killContractProcess',\n requestID,\n id,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n distributeYPK(projectName: string, nodeIDs: string): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'distributeYPK',\n requestID,\n pubKey: sm2Key.publicKey,\n projectName,\n nodeIDs,\n signature: sm2.doSignature(\n `DistributeYPK|${projectName}|${sm2Key.publicKey}`,\n sm2Key.privateKey,\n { hash: true, der: true },\n ),\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n listYPKs(): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'listYPKs',\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n deleteFile(file: string): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'deleteFile',\n requestID,\n file,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n startContractByYPK(project: string): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'startContractByYPK',\n isPrivate: true,\n requestID,\n owner: sm2Key.publicKey,\n path: `/${project}`,\n signature: sm2.doSignature(\n `Fixed|${project}|${sm2Key.publicKey}`,\n sm2Key.privateKey,\n ),\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n initBDServer(\n host: string,\n username: string,\n password: string,\n name: string,\n clusterHost: string,\n ): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'initBDServer',\n requestID,\n host,\n username,\n password,\n name,\n sm2Key: JSON.stringify(this.sm2Key),\n clusterHost,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n initBDCluster(\n host: string,\n username: string,\n password: string,\n name: string,\n sm2Key: string,\n agents: [],\n ): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'initBDCluster',\n requestID,\n host,\n username,\n password,\n name,\n sm2Key,\n agents,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n listCompiledFiles(): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'listCompiledFiles',\n requestID,\n isPrivate: true,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getManagerPubkey(): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getManagerPubkey',\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getClusterName(): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getClusterName',\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n setClusterName(name: string): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'setClusterName',\n requestID,\n name,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n}\n"],"names":["aesEncrypt","data","aesKey","exkey","slice","aes","ExpandKey","blocks","cryptico","string2bytes","pad16","Encrypt","ciphertext","bytes2string","b256to64","genUrlParamsFromObject","obj","Object","entries","map","key","value","String","join","WsSocket","handlerList","toSend","isSending","sendList","toReceive","wssocket","constructor","wsurl","onopen","handler","console","log","this","push","monitor","that","WebSocket","onerror","error","onmessage","event","JSON","parse","action","sendNextSegment","receiveSeg","forEach","h","reconnect","setTimeout","onclose","status","readyState","str","length","substr","isSegment","send","stringify","pop","cid","addHandler","baseUrl","sm2Key","fetch","config","axiosInstance","axios","create","baseURL","timeout","buildAxiosFetch","async","path","init","Promise","resolve","reject","rawUrl","url","includes","publicKey","sign","substring","indexOf","privateKey","method","toLowerCase","encodeURI","body","then","res","clientRes","text","catch","err","retryTimes","Error","i","requestWithSignature","e","sm2","doSignature","hash","der","ping","startContract","code","params","script","startContractByYPK","_request","owner","aim","signature","executeContract","contractID","operation","arg","withDynamicAnalysis","withSignature","request","undefined","pubkey","retryRequestWithSignature","killContractProcess","requestID","id","killAllContract","applyNodeRole","role","authNodeRole","isAccept","authorizedPubKey","managerPair","distributeContract","nodeIDs","projectName","isPrivate","sig","EventSource","addEventListener","_event","saveFile","listProjectPermission","startContractMultiPoint","peersID","type","selectUnitNum","sponsorPeerID","val","lockEdit","unlockEdit","addNode","nodePubKey","applyRole","authNodeManager","listAllUsers","listNodes","Msg","toSign","msg","pubKey","headers","listTrustUnits","listContractProcess","downloadContract","timestamp","args","resetNodeManager","kvs","filter","_k","v","all","k","updateConfig","loadNodeConfig","every","remapNodeConfigKey","promiseCallbackPairs","sessionPromise","sessionResolve","loginPromise","loginResolve","generateKeyPairHex","_reject","_","session","failed","reqId","responseID","pc","sessionReceived","loggedIn","matchCID","Date","getTime","Math","floor","random","getMetabyCID","getMetabyReadme","keyword","page","pageSize","getMetabyPubkey","segmentWord","words","getMetabyOwner","getDependentContract","contractName","queryContractLogByDate","start","queryDataByHash","argStr","getSessionID","listTheContractProcess","getMask","setMask","getMock","setMock","queryHashByOffset","offset","count","queryUserStat","distributeYPK","listYPKs","deleteFile","file","project","initBDServer","host","username","password","name","clusterHost","initBDCluster","agents","listCompiledFiles","getManagerPubkey","getClusterName","setClusterName","reqContent","generateAESKey","aesObj","reqContentNoId","decrypt","requester","n","toString","rsaKey","strs","b64to256","split","RSAKey","setPrivate","rsa","setPublic","e1","encrypt"],"mappings":"whBAYgB,SAAAA,EAAWC,EAAcC,GACvC,MAAMC,EAAQD,EAAOE,MAAM,GAC3BC,MAAIC,UAAUH,GACd,IAAII,EAASC,EAAAA,SAASC,aAAaR,GACnCM,EAASC,EAAQA,SAACE,MAAMH,GACxBF,EAAAA,IAAIM,QAAQJ,EAAQJ,GACpB,IAAIS,EAAaJ,EAAAA,SAASK,aAAaN,GAEvC,OADAK,EAAaJ,EAAQA,SAACM,SAASF,GACxBA,CACT,CCDA,MAAMG,EAA0BC,GACvBC,OAAOC,QAAQF,GACnBG,KAAI,EAAEC,EAAKC,KAAW,GAAGD,KAAOE,OAAOD,OACvCE,KAAK,WCRGC,EACHC,YAA2B,GAC3BC,OAAS,GACTC,WAAY,EACZC,SAAqB,GACrBC,UAAY,GACZC,SAERC,YAAYC,EAAeC,EAAuBC,GAChDC,QAAQC,IAAI,kCAAkCJ,KAC1CE,GACFG,KAAKZ,YAAYa,KAAKJ,GAIxBG,KAAKE,UAGL,MAAMC,EAAOH,KAEPP,EAAYO,KAAKP,SAAW,IAAIW,UAAUT,GAChDF,EAASY,QAAU,SAAUC,GAC3BR,QAAQC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GAE7D,4CH/qBa,SACdsK,EACAjF,GAOA,MAAMlK,EAAM,CACVe,IAAKZ,EAAQA,SAACiP,kBAEVC,EAAS5M,KAAKiB,UAAU1D,IACxBoH,WAAEA,GAAe+H,EACjBG,EAAiB,IAAKH,EAAY/H,gBAAYM,GASpD,MARoB,CAClB/E,OAAQuH,EAAOqF,QAAQF,GACvBjI,aACAE,IAAK3H,EAAW8C,KAAKiB,UAAU4L,GAAiBtP,EAAIe,KACpDyO,UAAWrP,EAAQA,SAACM,SAClB,GAAGyJ,EAAOuF,EAAEC,SAAS,OAAOxF,EAAO9D,EAAEsJ,SAAS,SAIpD,eA5CM,SAAqBC,GACzB,MACMC,EADMzP,EAAAA,SAAS0P,SAASF,GACbG,MAAM,KACjB/O,EAAM,IAAIgP,EAAAA,OAEhB,OADAhP,EAAIiP,WAAWJ,EAAK,GAAIA,EAAK,GAAIA,EAAK,IAC/B7O,CACT,eAfgB,SACdnB,EACA+P,GAEA,MAAMM,EAAM,IAAIF,EAAAA,OAEhB,OADAE,EAAIC,UAAUP,EAAOF,EAAGE,EAAOQ,IACxBF,EAAIG,QAAQxQ,EACrB"} \ No newline at end of file diff --git a/lib/index.mjs b/lib/index.mjs new file mode 100644 index 0000000..96bc5b6 --- /dev/null +++ b/lib/index.mjs @@ -0,0 +1,2 @@ +import{aes as e,cryptico as t,RSAKey as s}from"@daotl/cryptico";import{buildAxiosFetch as i}from"@lifeomic/axios-fetch";import r from"axios";import{sm2 as a}from"sm-crypto";function n(s,i){const r=i.slice(0);e.ExpandKey(r);let a=t.string2bytes(s);a=t.pad16(a),e.Encrypt(a,r);let n=t.bytes2string(a);return n=t.b256to64(n),n}function o(e,t){const i=new s;return i.setPublic(t.n,t.e1),i.encrypt(e)}function c(e){const i=t.b64to256(e).split(","),r=new s;return r.setPrivate(i[0],i[0],i[0]),r}function h(e,s){const i={key:t.generateAESKey()},r=JSON.stringify(i),{contractID:a}=e,o={...e,contractID:void 0};return{action:s.decrypt(r),contractID:a,arg:n(JSON.stringify(o),i.key),requester:t.b256to64(`${s.n.toString(16)},${s.e.toString(16)},0`)}}const u=e=>Object.entries(e).map((([e,t])=>`${e}=${String(t)}`)).join("&");class l{baseUrl;sm2Key;fetch;constructor(e,t,s={}){this.baseUrl=e,this.sm2Key=t;const a=r.create({baseURL:"https://some-domain.com/api/",timeout:1e4,...s});this.fetch=i(a)}async requestWithSignature(e,t,s){return new Promise(((i,r)=>{const a=this.baseUrl+e,n=`${a}${e.includes("?")?"&":"?"}pubKey=${s?.publicKey??this.sm2Key.publicKey}`,o=this.sign(n.substring(n.indexOf("?")+1),s?.privateKey);this.fetch("post"===t?.method?.toLowerCase()?a:`${encodeURI(n)}&sign=${o}`,{...t,..."POST"===t?.method?{body:{...t?.body,sign:o}}:{}}).then((async e=>{const t=e;t.data=await e.text(),setTimeout((()=>{i(t)}),1)})).catch((e=>{setTimeout((()=>{r(e)}),1)}))}))}async retryRequestWithSignature(e,t,s,i){let r=new Error;for(let a=0;at));await Promise.all([...t.map((([e,t])=>this.updateConfig(e,t))),this.applyNodeRole("ContractProvider"),this.applyNodeRole("ContractUser"),this.applyNodeRole("ContractInstanceManager"),this.authNodeRole(!0,this.sm2Key.publicKey)]);const s=(await this.loadNodeConfig()).data;return!!s&&t.every((([e,t])=>s[function(e){if("dataChain"===e)return"bdledger";return e}(e)]===t))}}class d{handlerList=[];toSend="";isSending=!1;sendList=[];toReceive="";wssocket;constructor(e,t,s){console.log(`[createWS.js] createWssocket : ${e}`),s&&this.handlerList.push(s),this.monitor();const i=this,r=this.wssocket=new WebSocket(e);r.onerror=function(e){console.log(e)},r.onopen=t;const a=function(e){const t=JSON.parse(e.data);switch(t.action){case"sendNextSegment":i.sendNextSegment();break;case"sendSeg":i.receiveSeg(t);break;default:i.handlerList.forEach((t=>t(e,this)))}};r.onmessage=a;const n=function(){setTimeout((()=>{console.log("[createWS.js] try to reconnect");const s=i.wssocket=new WebSocket(e);s.onclose=n,s.onmessage=a,s.onopen=t}),1e3)};r.onclose=n}status(){return this.wssocket.readyState}sendNextSegment(){const e=this.toSend;if(e.length>1024){this.toSend=e.substr(1024);const t={isSegment:!0,data:e.substr(0,1024)};this.wssocket.send(JSON.stringify(t))}else{this.toSend="";const t={isSegment:!1,data:e};let s;this.wssocket.send(JSON.stringify(t)),this.isSending=!1,(s=this.sendList.pop())&&this.send(s)}}receiveSeg(e){if("start"===e.cid&&(this.toReceive=""),this.toReceive+=e.data,"done"===e.cid){console.log(`[receiveSeg] Received AllData:${this.toReceive}`);const e={data:this.toReceive};this.toReceive="",this.handlerList.forEach((t=>t(e,this.wssocket)))}}monitor(){if(!this.isSending){let e;(e=this.sendList.pop())&&this.send(e)}setTimeout((()=>this.monitor()),1e3)}send(e){if(this.isSending)this.sendList.push(e);else if(e.length>1024){this.isSending=!0,this.toSend=e.substr(1024);const t={isSegment:!0,data:e.substr(0,1024)};this.wssocket.send(JSON.stringify(t))}else this.wssocket.send(e)}addHandler(e){this.handlerList.push(e)}}class g{sm2Key;wssocket;promiseCallbackPairs={};sessionPromise;sessionResolve;loginPromise;loginResolve;constructor(e,t,s,i=a.generateKeyPairHex()){this.sm2Key=i,this.sessionPromise=new Promise(((e,t)=>{this.sessionResolve=e})),this.loginPromise=new Promise(((e,t)=>{this.loginResolve=e}));const r=this;this.wssocket=new d(e,t,(function(e,t){const i=JSON.parse(e.data);switch(i.action){case"onSessionID":r.sessionResolve(i.session);break;case"onLogin":{const e="string"==typeof i.status&&i.status.toLowerCase().includes("failed");r.loginResolve(!e)}}const a=i.responseID;let n;a&&(n=r.promiseCallbackPairs[a])&&(i?n.resolve(i):n.reject(i)),s(e,this)}))}status(){return this.wssocket.status()}sessionReceived(){return this.sessionPromise}async login(){const e=await this.sessionPromise,t={action:"login",pubKey:this.sm2Key.publicKey,signature:a.doSignature(e,this.sm2Key.privateKey,{hash:!0,der:!0})};return this.wssocket.send(JSON.stringify(t)),this.loginPromise}loggedIn(){return this.loginPromise}matchCID(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"matchCID",contractID:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}getMetabyCID(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"getMetabyCID",contractID:e,requestID:t};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}getMetabyReadme(e,t,s){const i=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,r={action:"getMetabyReadme",page:t,pageSize:s,keyword:e,requestID:i};return this.wssocket.send(JSON.stringify(r)),new Promise(((e,t)=>{this.promiseCallbackPairs[i]={resolve:e,reject:t}}))}getMetabyPubkey(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"getMetabyPubkey",pubkey:e,requestID:t};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}segmentWord(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={words:e,action:"segmentWord",requestID:t};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}getMetabyOwner(e,t,s){const i=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,r={action:"getMetabyOwner",owner:e,page:t,pageSize:s,requestID:i};return this.wssocket.send(JSON.stringify(r)),new Promise(((e,t)=>{this.promiseCallbackPairs[i]={resolve:e,reject:t}}))}getDependentContract(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"getDependentContract",requestID:t,contractName:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}queryContractLogByDate(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"queryContractLogByDate",requestID:t,start:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}queryDataByHash(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"queryDataByHash",requestID:t,hash:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}executeContract(e,t,s){const i=this.sm2Key,r=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,n="object"==typeof s?JSON.stringify(s):s+"",o={action:"executeContract",requestID:r,contractID:e,operation:t,arg:s,...i?{pubkey:i.publicKey,signature:a.doSignature(`${e}|${t}|${n}|${i.publicKey}`,i.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(o)),new Promise(((e,t)=>{this.promiseCallbackPairs[r]={resolve:e,reject:t}}))}getSessionID(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"getSessionID",requestID:e};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}listTheContractProcess(e){const t=this.sm2Key,s=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,i={action:"listTheContractProcess",requestID:s,contractID:e,...t?{pubkey:t.publicKey,signature:a.doSignature(`${e}|${t.publicKey}`,t.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(i)),new Promise(((e,t)=>{this.promiseCallbackPairs[s]={resolve:e,reject:t}}))}getMask(e){const t=this.sm2Key,s=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,i={action:"getMask",requestID:s,contractID:e,...t?{pubkey:t.publicKey,signature:a.doSignature(`${e}|${t.publicKey}`,t.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(i)),new Promise(((e,t)=>{this.promiseCallbackPairs[s]={resolve:e,reject:t}}))}setMask(e,t,s){const i=this.sm2Key,r=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,n={action:"setMask",requestID:r,contractID:e,operation:t,arg:s,...i?{pubkey:i.publicKey,signature:a.doSignature(`${e}|${i.publicKey}`,i.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(n)),new Promise(((e,t)=>{this.promiseCallbackPairs[r]={resolve:e,reject:t}}))}getMock(e){const t=this.sm2Key,s=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,i={action:"getMock",requestID:s,contractID:e,...t?{pubkey:t.publicKey,signature:a.doSignature(`${e}|${t.publicKey}`,t.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(i)),new Promise(((e,t)=>{this.promiseCallbackPairs[s]={resolve:e,reject:t}}))}setMock(e,t,s){const i=this.sm2Key,r=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,n={action:"setMock",requestID:r,contractID:e,operation:t,arg:s,...i?{pubkey:i.publicKey,signature:a.doSignature(`${e}|${i.publicKey}`,i.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(n)),new Promise(((e,t)=>{this.promiseCallbackPairs[r]={resolve:e,reject:t}}))}queryHashByOffset(e,t){const s=this.sm2Key,i=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,r={action:"queryHashByOffset",requestID:i,offset:e,count:t,...s?{pubkey:s.publicKey}:{}};return this.wssocket.send(JSON.stringify(r)),new Promise(((e,t)=>{this.promiseCallbackPairs[i]={resolve:e,reject:t}}))}loadNodeConfig(){const e=this.sm2Key,t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"loadNodeConfig",requestID:t,...e?{pubkey:e.publicKey,signature:a.doSignature(e.publicKey,e.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}queryUserStat(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"queryUserStat",requestID:e};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}listNodes(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"listNodes",requestID:e};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}killContractProcess(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"killContractProcess",requestID:t,id:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}distributeYPK(e,t){const s=this.sm2Key,i=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,r={action:"distributeYPK",requestID:i,pubKey:s.publicKey,projectName:e,nodeIDs:t,signature:a.doSignature(`DistributeYPK|${e}|${s.publicKey}`,s.privateKey,{hash:!0,der:!0})};return this.wssocket.send(JSON.stringify(r)),new Promise(((e,t)=>{this.promiseCallbackPairs[i]={resolve:e,reject:t}}))}listYPKs(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"listYPKs",requestID:e};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}deleteFile(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"deleteFile",requestID:t,file:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}startContractByYPK(e){const t=this.sm2Key,s=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,i={action:"startContractByYPK",isPrivate:!0,requestID:s,owner:t.publicKey,path:`/${e}`,signature:a.doSignature(`Fixed|${e}|${t.publicKey}`,t.privateKey)};return this.wssocket.send(JSON.stringify(i)),new Promise(((e,t)=>{this.promiseCallbackPairs[s]={resolve:e,reject:t}}))}initBDServer(e,t,s,i,r){const a=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,n={action:"initBDServer",requestID:a,host:e,username:t,password:s,name:i,sm2Key:JSON.stringify(this.sm2Key),clusterHost:r};return this.wssocket.send(JSON.stringify(n)),new Promise(((e,t)=>{this.promiseCallbackPairs[a]={resolve:e,reject:t}}))}initBDCluster(e,t,s,i,r,a){const n=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,o={action:"initBDCluster",requestID:n,host:e,username:t,password:s,name:i,sm2Key:r,agents:a};return this.wssocket.send(JSON.stringify(o)),new Promise(((e,t)=>{this.promiseCallbackPairs[n]={resolve:e,reject:t}}))}listCompiledFiles(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"listCompiledFiles",requestID:e,isPrivate:!0};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}getManagerPubkey(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"getManagerPubkey",requestID:e};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}getClusterName(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"getClusterName",requestID:e};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}setClusterName(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"setClusterName",requestID:t,name:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}}export{l as HttpClient,g as WsClient,d as WsSocket,n as aesEncrypt,h as encryptReq,c as loadRSAKey,o as rsaEncrypt}; +//# sourceMappingURL=index.mjs.map diff --git a/lib/index.mjs.map b/lib/index.mjs.map new file mode 100644 index 0000000..a9e2415 --- /dev/null +++ b/lib/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sources":["../src/crypto.ts","../src/httpClient.ts","../src/wssocket.ts","../src/wsClient.ts"],"sourcesContent":["// export function aesDecrypt(data: base64) {\n// const dataAscii = cryptico.b64to256(data)\n// const encryptedBlocks = cryptico.string2bytes(dataAscii)\n// const exkey = global.aesKey.slice(0)\n// aes.ExpandKey(exkey)\n// aes.Decrypt(encryptedBlocks, exkey)\n// return cryptico.bytes2string(encryptedBlocks)\n// }\n\nimport type { AESKey } from '@daotl/cryptico'\nimport { aes, cryptico, RSAKey } from '@daotl/cryptico'\n\nexport function aesEncrypt(data: string, aesKey: AESKey): string {\n const exkey = aesKey.slice(0)\n aes.ExpandKey(exkey)\n let blocks = cryptico.string2bytes(data)\n blocks = cryptico.pad16(blocks)\n aes.Encrypt(blocks, exkey)\n let ciphertext = cryptico.bytes2string(blocks)\n ciphertext = cryptico.b256to64(ciphertext)\n return ciphertext\n}\n\nexport function rsaEncrypt(\n data: string,\n rsaKey: { n: string; e1: string },\n): string {\n const rsa = new RSAKey()\n rsa.setPublic(rsaKey.n, rsaKey.e1)\n return rsa.encrypt(data)\n}\n\nexport function loadRSAKey(rsaKey: string): RSAKey {\n const str = cryptico.b64to256(rsaKey)\n const strs = str.split(',')\n const key = new RSAKey()\n key.setPrivate(strs[0], strs[0], strs[0])\n return key\n}\n\n// function testRSA() {\n// pubKey = loadRSAKey(global.privKey)\n// reqContent = {}\n// reqContent.action = 'main'\n// reqContent.arg = '[{\"score\":20},{\"score\":20}]'\n// reqContent.contractID = 'abc'\n// eReq = encryptReq(reqContent, pubKey)\n// url =\n// 'http://localhost:8080/SCIDE/SCManager?action=executeContractEncrypted&contractRequest=' +\n// encodeURIComponent(JSON.stringify(eReq))\n// }\n\nexport function encryptReq(\n reqContent: { contractID: string },\n pubKey: RSAKey,\n): {\n action: string | null\n contractID: string\n arg: string\n requester: string\n} {\n const aes = {\n key: cryptico.generateAESKey(),\n }\n const aesObj = JSON.stringify(aes)\n const { contractID } = reqContent\n const reqContentNoId = { ...reqContent, contractID: undefined }\n const encrypedReq = {\n action: pubKey.decrypt(aesObj),\n contractID,\n arg: aesEncrypt(JSON.stringify(reqContentNoId), aes.key),\n requester: cryptico.b256to64(\n `${pubKey.n.toString(16)},${pubKey.e.toString(16)},0`,\n ),\n }\n return encrypedReq\n}\n","import { buildAxiosFetch } from '@lifeomic/axios-fetch'\nimport axios, { type AxiosRequestConfig } from 'axios'\nimport type { KeyPairHex } from 'sm-crypto'\nimport { sm2 } from 'sm-crypto'\n\nimport type {\n ClientResponse,\n ConfigNodeArgs,\n ExecuteContractArgs,\n ListAllUsersResponseData,\n ListNodesResponse,\n ListProjectPermissionRequest,\n ListProjectPermissionResponseData,\n LoadNodeConfigResponseData,\n ExecuteContractResponse,\n PingResponse,\n SaveFileRequest,\n StartContractByYpkRequest,\n} from './types'\n\nconst genUrlParamsFromObject = (obj: Record): string => {\n return Object.entries(obj)\n .map(([key, value]) => `${key}=${String(value)}`)\n .join('&')\n}\n\nexport * from './types'\n\nexport class HttpClient {\n private fetch: (input: RequestInfo, init?: RequestInit) => Promise\n\n constructor(\n private baseUrl: string,\n private sm2Key: KeyPairHex,\n config = {} as AxiosRequestConfig,\n ) {\n const axiosInstance = axios.create({\n baseURL: 'https://some-domain.com/api/',\n timeout: 10000,\n // headers: {'X-Custom-Header': 'foobar'}\n ...config,\n })\n\n this.fetch = buildAxiosFetch(\n axiosInstance /* , function (config) {\n config.timeout = 1000;\n return config;\n } */,\n )\n }\n\n async requestWithSignature(\n path: string,\n init?: Partial,\n sm2Key?: KeyPairHex,\n ): Promise> {\n return new Promise>((resolve, reject) => {\n const rawUrl = this.baseUrl + path\n const url = `${rawUrl}${path.includes('?') ? '&' : '?'}pubKey=${\n sm2Key?.publicKey ?? this.sm2Key.publicKey\n }`\n\n // console.log('privateKey:', this.sm2Key.privateKey)\n\n // console.log('publicKey:', this.sm2Key.publicKey)\n\n // console.log('to sign:', url.substring(url.indexOf('?') + 1))\n\n const sign = this.sign(\n url.substring(url.indexOf('?') + 1),\n sm2Key?.privateKey,\n )\n\n // console.log(\n // 'url:',\n // init?.method?.toLowerCase() === 'post'\n // ? rawUrl\n // : `${encodeURI(url)}&sign=${sign}`,\n // )\n\n this.fetch(\n init?.method?.toLowerCase() === 'post'\n ? rawUrl\n : `${encodeURI(url)}&sign=${sign}`,\n {\n ...init,\n ...(init?.method === 'POST'\n ? {\n body: {\n ...(init?.body as unknown as Record),\n sign,\n } as unknown as Request['body'],\n }\n : {}),\n },\n )\n .then(async (res) => {\n // console.log(res.url,'请求成功')\n const clientRes = res as unknown as ClientResponse\n clientRes.data = (await res.text()) as Data\n // Workaround for the issue causing the 2nd consecutive request to fail:\n // https://github.com/nodejs/undici/issues/1415\n setTimeout(() => {\n resolve(clientRes)\n }, 1)\n })\n .catch((err) => {\n // const clientRes = err as unknown as ClientResponse\n // clientRes.data = (await err.text()) as Data\n // console.log(err,'errerrerrerrerrerrerrerrerrerrerrerrerrerrerr')\n setTimeout(() => {\n reject(err)\n }, 1)\n })\n })\n }\n\n async retryRequestWithSignature(retryTimes: number, path: string, init?: Partial, sm2Key?: KeyPairHex ) {\n let err: Error = new Error()\n for (let i = 0; i(path, init, sm2Key)\n } catch (e) {\n if (i < retryTimes) {\n console.log('1')\n continue\n }\n err = e as Error\n }\n }\n throw err\n }\n\n sign(data: string, privateKey?: string): string {\n return sm2.doSignature(data, privateKey ?? this.sm2Key.privateKey, {\n hash: true,\n der: true,\n })\n }\n\n // ping\n // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html#id15\n ping(): Promise {\n return this.requestWithSignature('/SCManager?action=ping')\n }\n\n // 启动合约\n // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html#id60\n startContract(code: string): Promise> {\n const params = { action: 'startContract', script: code }\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject(params)}`,\n )\n }\n\n // 启动合约\n // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html#id13\n startContractByYPK(\n _request: StartContractByYpkRequest,\n ): Promise> {\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'startContractByYPK',\n ..._request,\n owner: this.sm2Key.publicKey,\n aim: 'onStartContract',\n signature: sm2.doSignature(\n `Fixed|${_request.path}|${this.sm2Key.publicKey}`,\n this.sm2Key.privateKey,\n {\n hash: true,\n der: true,\n },\n ),\n })}`,\n )\n }\n\n // 调用合约\n // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html#id69\n executeContract(\n contractID: string,\n operation: string,\n arg: string,\n {\n method = 'POST',\n withDynamicAnalysis = false,\n withSignature = false,\n } = {} as ExecuteContractArgs,\n ): Promise>> {\n let request = {}\n if (withDynamicAnalysis === undefined) {\n request = {\n action: 'executeContract',\n contractID,\n operation,\n arg,\n }\n } else {\n request = {\n action: 'executeContract',\n contractID,\n operation,\n withDynamicAnalysis,\n arg,\n }\n }\n if (withSignature) {\n request = {\n ...request,\n pubkey: this.sm2Key.publicKey,\n signature: this.sign(\n `${contractID}|${operation}|${arg ?? ''}|${this.sm2Key.publicKey}`,\n ),\n }\n }\n\n return this.retryRequestWithSignature(\n 3,\n `/SCManager${\n method === 'GET' ? `?${genUrlParamsFromObject(request)}` : ''\n }`,\n {\n method,\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n ...(method === 'POST' ? ({ body: request } as Request) : {}),\n },\n )\n }\n\n // 停止合约\n // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html#id122\n killContractProcess(\n contractID: string,\n requestID?: string,\n ): Promise> {\n const _request: Record = {\n action: 'killContractProcess',\n id: contractID,\n }\n requestID && (_request.requestID = requestID!)\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject(_request)}`,\n )\n }\n\n // 停止所有合约\n // 地址 http://39.104.205.122:18010/SCIDE\n // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html#id131\n killAllContract(): Promise> {\n return this.requestWithSignature('/SCManager?action=killAllContract')\n }\n\n // 申请角色\n // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html\n applyNodeRole(\n role: string,\n ): Promise> {\n const _request = {\n action: 'applyNodeRole',\n role,\n }\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject(_request)}`,\n )\n }\n\n // 授权角色\n // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html\n authNodeRole(\n isAccept: boolean,\n authorizedPubKey: string,\n managerPair?: KeyPairHex,\n ): Promise> {\n const _request = {\n action: 'authNodeRole',\n isAccept,\n authorizedPubKey,\n }\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject(_request)}`,\n undefined,\n managerPair,\n )\n }\n\n // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html\n // 用sse获取 问题未解决!!!\n distributeContract(\n nodeIDs: string,\n projectName: string,\n isPrivate: boolean,\n ): void {\n const signature = sm2.doSignature(\n `DistributeContract|${projectName}|${this.sm2Key.publicKey}`,\n this.sm2Key.privateKey,\n { hash: true, der: true },\n )\n\n const _request = {\n action: 'distributeContract',\n nodeIDs,\n projectName,\n isPrivate,\n signature,\n }\n\n const path = `/SCManager?${genUrlParamsFromObject(_request)}`\n const url = `${this.baseUrl + path}${\n path.includes('?') ? '&' : '?'\n }pubKey=${this.sm2Key.publicKey}`\n const sig = sm2.doSignature(\n url.substring(url.indexOf('?') + 1),\n this.sm2Key.privateKey,\n {\n hash: true,\n der: true,\n },\n )\n const source = new EventSource(\n `${this.baseUrl}${path}&pubKey=${this.sm2Key.publicKey}&sign=${sig}`,\n )\n source.addEventListener(\n 'message',\n function (_event) {\n // const data = event.data as DistributeContractResponse[]\n // console.log(data, 'dd')\n // handle message\n },\n false,\n )\n }\n\n saveFile(_request: SaveFileRequest): Promise> {\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'saveFile',\n ..._request,\n })}`,\n )\n }\n\n listProjectPermission(\n _request: ListProjectPermissionRequest,\n ): Promise> {\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'listProjectPermission',\n ..._request,\n })}`,\n )\n }\n\n startContractMultiPoint(\n peersID: string,\n type: number,\n selectUnitNum: number,\n projectName: string,\n isPrivate: boolean,\n sponsorPeerID: string,\n ): Promise> {\n const _request = {\n // peerID是节点的公钥,以逗号间隔开\n peersID,\n type,\n selectUnitNum,\n projectName,\n isPrivate,\n sponsorPeerID,\n }\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'startContractMultiPoint',\n ..._request,\n })}`,\n )\n }\n\n // 获取节点配置信息\n async loadNodeConfig(): Promise> {\n const res = await this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'loadNodeConfig',\n })}`,\n )\n return { ...res, data: (res.status === 200 && res.data ? JSON.parse( res.data).data : {}) as LoadNodeConfigResponseData}\n }\n\n // 支持的key包括:{licence,projectDir,yjsPath,dataChain,doipConfig,nodeCenter,nodeName,masterAddress,resetNodeCenterWS}\n async updateConfig(\n key: string,\n val: string,\n ): Promise> {\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'updateConfig',\n key,\n val,\n })}`,\n )\n }\n\n // 设置pubkey为node manager\n async resetNodeManager(): Promise {\n const res = await this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'resetNodeManager',\n })}`,\n )\n if (!res.data) {\n return false\n }\n const parsed = JSON.parse(res.data)\n return parsed.data === 'success'\n }\n\n // 锁定某个用户的的私有目录编辑功能\n lockEdit(): Promise> {\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'lockEdit',\n })}`,\n )\n }\n\n // 解锁某个用户的的私有目录编辑功能\n unlockEdit(): Promise> {\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'unlockEdit',\n })}`,\n )\n }\n\n addNode(nodePubKey: string): Promise> {\n return this.requestWithSignature(\n `?${genUrlParamsFromObject({\n action: 'addNode',\n nodePubKey,\n })}`,\n )\n }\n\n // 申请角色\n applyRole(role: string): Promise> {\n return this.requestWithSignature(\n `?${genUrlParamsFromObject({\n action: 'applyRole',\n role,\n })}`,\n )\n }\n\n authNodeManager(\n isAccept: boolean,\n authorizedPubKey: string,\n ): Promise> {\n return this.requestWithSignature(\n `?${genUrlParamsFromObject({\n action: 'authNodeManager',\n isAccept,\n authorizedPubKey,\n })}`,\n )\n }\n\n listAllUsers(): Promise> {\n return this.requestWithSignature(\n `?${genUrlParamsFromObject({\n action: 'listAllUsers',\n })}`,\n )\n }\n\n // 查看节点列表\n listNodes(): Promise {\n return this.requestWithSignature(\n `?${genUrlParamsFromObject({\n action: 'listNodes',\n })}`,\n ) as unknown as Promise\n }\n\n // 建立可信执行集群\n async createTrustUnit(\n data: { nodeName: string; pubkey: string }[],\n Msg: string,\n ): Promise<{ action: string; status: string }> {\n const toSign = `action=createTrustUnit&data=${JSON.stringify(\n data,\n )}&msg=${Msg}&pubKey=04303718771b9323c204e607639f14469f9a94e55b0964a408ad3b3864b0493b645d7070da0d550f0c54b934275a8e88dedc3024467b0566db5c1108b1baeaae27`\n const sig = sm2.doSignature(toSign, this.sm2Key.privateKey, {\n hash: true,\n der: true,\n })\n\n const body = {\n action: 'createTrustUnit',\n data,\n msg: Msg,\n pubKey:\n '04303718771b9323c204e607639f14469f9a94e55b0964a408ad3b3864b0493b645d7070da0d550f0c54b934275a8e88dedc3024467b0566db5c1108b1baeaae27',\n sign: sig,\n }\n return (await this.requestWithSignature('', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n })) as unknown as { action: string; status: string }\n }\n\n // 查看可信执行集群列表\n listTrustUnits(): Promise> {\n return this.requestWithSignature(\n `?${genUrlParamsFromObject({\n action: 'listTrustUnits',\n })}`,\n )\n }\n\n // listContractProcess 查询合约实例列表\n listContractProcess(): Promise> {\n return this.requestWithSignature(\n `/SCManager?${genUrlParamsFromObject({\n action: 'listContractProcess',\n })}`,\n )\n }\n\n // 下载合约\n downloadContract(\n projectName: string,\n isPrivate: boolean,\n timestamp: number\n ): Promise> {\n const _request = {\n action: 'downloadContract',\n projectName,\n isPrivate,\n timestamp,\n }\n return this.requestWithSignature(\n `/CMManager?${genUrlParamsFromObject(_request)}`)\n }\n\n // 配置合约引擎节点,若节点没有设置过node manager,将当前key设置为node manager\n async configNode(\n args: ConfigNodeArgs,\n ): Promise {\n if (!(await this.resetNodeManager())) {\n return false\n }\n\n const kvs: [string, string][] = Object.entries(args).filter(([_k, v]) => v) as [string, string][]\n\n await Promise.all([\n ...kvs.map(([k, v]) => this.updateConfig(k, v!)),\n this.applyNodeRole('ContractProvider'),\n this.applyNodeRole('ContractUser'),\n this.applyNodeRole('ContractInstanceManager'),\n this.authNodeRole(true, this.sm2Key.publicKey),\n ])\n\n const config = (await this.loadNodeConfig()).data\n if (!config) {\n return false\n }\n\n return kvs.every(([k, v]) => config[remapNodeConfigKey(k)] === v)\n }\n}\n\nfunction remapNodeConfigKey(k: string) {\n switch (k) {\n case 'dataChain':\n return 'bdledger'\n default:\n return k\n }\n}\n","/* eslint-disable no-console,no-cond-assign */\n\nexport interface WsEvent {\n data: string\n}\n\nexport type OnOpenHandler = (this: WebSocket, ev: Event) => void\nexport type WsHandler = (ev: WsEvent, ws?: WebSocket) => void\n\ninterface SegmentData {\n action: 'sendSeg'\n cid: string\n data: string\n}\n\nexport class WsSocket {\n private handlerList: WsHandler[] = []\n private toSend = ''\n private isSending = false\n private sendList: string[] = []\n private toReceive = ''\n private wssocket: WebSocket\n\n constructor(wsurl: string, onopen: OnOpenHandler, handler?: WsHandler) {\n console.log(`[createWS.js] createWssocket : ${wsurl}`)\n if (handler) {\n this.handlerList.push(handler)\n }\n\n // TODO: we don't need monitor at all?\n this.monitor()\n\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const that = this\n\n const wssocket = (this.wssocket = new WebSocket(wsurl))\n wssocket.onerror = function (error): void {\n console.log(error)\n }\n wssocket.onopen = onopen\n\n const onmessage = function (this: WebSocket, event: MessageEvent): void {\n const obj = JSON.parse(event.data as string) as { action: string }\n switch (obj.action) {\n case 'sendNextSegment':\n that.sendNextSegment()\n break\n case 'sendSeg':\n that.receiveSeg(obj as SegmentData)\n break\n default:\n that.handlerList.forEach((h) => h(event, this))\n }\n }\n wssocket.onmessage = onmessage\n\n const reconnect = function (): void {\n setTimeout(() => {\n console.log('[createWS.js] try to reconnect')\n const wssocket = (that.wssocket = new WebSocket(wsurl))\n wssocket.onclose = reconnect\n wssocket.onmessage = onmessage\n wssocket.onopen = onopen\n }, 1000)\n }\n wssocket.onclose = reconnect\n }\n\n status(): WebSocket['CLOSED' | 'CLOSING' | 'CONNECTING' | 'OPEN'] {\n return this.wssocket.readyState\n }\n\n sendNextSegment(): void {\n const str = this.toSend\n if (str.length > 1024) {\n this.toSend = str.substr(1024)\n const obj = {\n isSegment: true,\n data: str.substr(0, 1024),\n }\n this.wssocket.send(JSON.stringify(obj))\n } else {\n this.toSend = ''\n const obj = {\n isSegment: false,\n data: str,\n }\n this.wssocket.send(JSON.stringify(obj))\n this.isSending = false\n let data\n if ((data = this.sendList.pop())) {\n this.send(data)\n }\n }\n }\n\n receiveSeg(obj: SegmentData): void {\n if (obj.cid === 'start') {\n this.toReceive = ''\n }\n this.toReceive += obj.data\n if (obj.cid === 'done') {\n console.log(`[receiveSeg] Received AllData:${this.toReceive}`)\n const event: WsEvent = {\n data: this.toReceive,\n }\n this.toReceive = ''\n this.handlerList.forEach((h) => h(event, this.wssocket))\n }\n }\n\n monitor(): void {\n if (!this.isSending) {\n let data\n if ((data = this.sendList.pop())) {\n this.send(data)\n }\n }\n setTimeout(() => this.monitor(), 1000)\n }\n\n send(data: string): void {\n if (this.isSending) {\n this.sendList.push(data)\n return\n }\n if (data.length > 1024) {\n this.isSending = true\n this.toSend = data.substr(1024)\n const obj = {\n isSegment: true,\n data: data.substr(0, 1024),\n }\n this.wssocket.send(JSON.stringify(obj))\n } else {\n this.wssocket.send(data)\n }\n }\n\n addHandler(handler: WsHandler): void {\n this.handlerList.push(handler)\n }\n}\n","/* eslint-disable no-cond-assign */\n\nimport type { KeyPairHex } from 'sm-crypto'\nimport { sm2 } from 'sm-crypto'\n\nimport type { OnOpenHandler, WsHandler } from './wssocket'\nimport { WsSocket } from './wssocket'\n\ninterface ResponseData {\n action: string\n responseID?: string\n status: true | false | string // 'Success' | 'Exception' | 'Error' | 'failed: no session'\n result?: unknown\n data: string\n [K: string]: unknown\n}\n\n// interface ListResponseData {\n// action: string\n// data: string\n// status: true | false\n// }\n\ninterface PromiseCallbackPair {\n resolve: (value: ResponseData | PromiseLike) => void\n reject: (reason?: unknown) => void\n}\n\nexport class WsClient {\n private readonly sm2Key: KeyPairHex\n private readonly wssocket: WsSocket\n private readonly promiseCallbackPairs: Record =\n {}\n\n private readonly sessionPromise: Promise\n private sessionResolve!: (value: string | PromiseLike) => void\n private readonly loginPromise: Promise\n private loginResolve!: (value: boolean | PromiseLike) => void\n\n constructor(\n url: string,\n onopen: OnOpenHandler,\n handler: WsHandler,\n sm2Key: KeyPairHex = sm2.generateKeyPairHex(),\n ) {\n this.sm2Key = sm2Key\n this.sessionPromise = new Promise((resolve, _reject) => {\n this.sessionResolve = resolve\n })\n this.loginPromise = new Promise((resolve, _reject) => {\n this.loginResolve = resolve\n })\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const that = this\n this.wssocket = new WsSocket(url, onopen, function (\n this: WebSocket,\n event,\n _,\n ) {\n const data = JSON.parse(event.data) as ResponseData\n\n switch (data.action) {\n case 'onSessionID':\n that.sessionResolve(data.session as string)\n break\n case 'onLogin':\n {\n const failed =\n typeof data.status === 'string' &&\n data.status.toLowerCase().includes('failed')\n that.loginResolve(!failed)\n }\n break\n }\n\n const reqId = data.responseID\n let pc: PromiseCallbackPair | undefined\n if (reqId && (pc = that.promiseCallbackPairs[reqId])) {\n if (data) {\n pc.resolve(data)\n } else {\n pc.reject(data)\n }\n }\n handler(event, this)\n })\n }\n\n status(): WebSocket['CLOSED' | 'CLOSING' | 'CONNECTING' | 'OPEN'] {\n return this.wssocket.status()\n }\n\n sessionReceived(): Promise {\n return this.sessionPromise\n }\n\n async login(): Promise {\n const session = await this.sessionPromise\n const request = {\n action: 'login',\n pubKey: this.sm2Key.publicKey,\n signature: sm2.doSignature(session, this.sm2Key.privateKey, {\n hash: true,\n der: true,\n }),\n }\n this.wssocket.send(JSON.stringify(request))\n return this.loginPromise\n }\n\n loggedIn(): Promise {\n return this.loginPromise\n }\n\n matchCID(contractID: string): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'matchCID',\n contractID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getMetabyCID(contractID: string): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getMetabyCID',\n contractID,\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getMetabyReadme(\n keyword: string,\n page?: string,\n pageSize?: string,\n ): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getMetabyReadme',\n page,\n pageSize,\n keyword,\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getMetabyPubkey(pubkey: string): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getMetabyPubkey',\n pubkey,\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n segmentWord(words: string): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n words,\n action: 'segmentWord',\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getMetabyOwner(\n owner: string,\n page?: string,\n pageSize?: string,\n ): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getMetabyOwner',\n owner,\n page,\n pageSize,\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getDependentContract(contractName: string): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getDependentContract',\n requestID,\n contractName,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n queryContractLogByDate(start: number): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'queryContractLogByDate',\n requestID,\n start,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n queryDataByHash(hash: string): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'queryDataByHash',\n requestID,\n hash,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n executeContract(\n contractID: string,\n method: string,\n arg: unknown,\n ): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const argStr = (typeof arg) == 'object' ? JSON.stringify(arg):arg+\"\";\n const request = {\n action: 'executeContract',\n requestID,\n contractID,\n operation: method,\n arg: arg,\n ...(sm2Key\n ? {\n pubkey: sm2Key.publicKey,\n signature: sm2.doSignature(\n `${contractID}|${method}|${argStr}|${sm2Key.publicKey}`,\n sm2Key.privateKey,\n { hash: true, der: true },\n ),\n }\n : {}),\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getSessionID(): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getSessionID',\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n listTheContractProcess(contractID: string): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'listTheContractProcess',\n requestID,\n contractID,\n ...(sm2Key\n ? {\n pubkey: sm2Key.publicKey,\n signature: sm2.doSignature(\n `${contractID}|${sm2Key.publicKey}`,\n sm2Key.privateKey,\n { hash: true, der: true },\n ),\n }\n : {}),\n }\n this.wssocket.send(JSON.stringify(request))\n\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getMask(\n contractID: string,\n // operation: string,\n ): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getMask',\n requestID,\n contractID,\n // operation,\n ...(sm2Key\n ? {\n pubkey: sm2Key.publicKey,\n signature: sm2.doSignature(\n `${contractID}|${sm2Key.publicKey}`,\n sm2Key.privateKey,\n { hash: true, der: true },\n ),\n }\n : {}),\n }\n\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n setMask(\n contractID: string,\n operation: string,\n arg: string,\n ): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'setMask',\n requestID,\n contractID,\n operation,\n arg,\n ...(sm2Key\n ? {\n pubkey: sm2Key.publicKey,\n signature: sm2.doSignature(\n `${contractID}|${sm2Key.publicKey}`,\n sm2Key.privateKey,\n { hash: true, der: true },\n ),\n }\n : {}),\n }\n\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getMock(\n contractID: string,\n // operation: string,\n ): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getMock',\n requestID,\n contractID,\n // operation,\n ...(sm2Key\n ? {\n pubkey: sm2Key.publicKey,\n signature: sm2.doSignature(\n `${contractID}|${sm2Key.publicKey}`,\n sm2Key.privateKey,\n { hash: true, der: true },\n ),\n }\n : {}),\n }\n\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n setMock(\n contractID: string,\n operation: string,\n arg: string,\n ): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'setMock',\n requestID,\n contractID,\n operation,\n arg,\n ...(sm2Key\n ? {\n pubkey: sm2Key.publicKey,\n signature: sm2.doSignature(\n `${contractID}|${sm2Key.publicKey}`,\n sm2Key.privateKey,\n { hash: true, der: true },\n ),\n }\n : {}),\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n queryHashByOffset(offset: number, count: number): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'queryHashByOffset',\n requestID,\n offset,\n count,\n ...(sm2Key\n ? {\n pubkey: sm2Key.publicKey,\n /* signature: sm2.doSignature(\n id + '|' + sm2Key.publicKey,\n sm2Key.privateKey,\n { hash: true, der: true },\n ), */\n }\n : {}),\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n loadNodeConfig(): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'loadNodeConfig',\n requestID,\n\n ...(sm2Key\n ? {\n pubkey: sm2Key.publicKey,\n signature: sm2.doSignature(sm2Key.publicKey, sm2Key.privateKey, {\n hash: true,\n der: true,\n }),\n }\n : {}),\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n queryUserStat(): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'queryUserStat',\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n listNodes(): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'listNodes',\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n killContractProcess(id: string): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'killContractProcess',\n requestID,\n id,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n distributeYPK(projectName: string, nodeIDs: string): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'distributeYPK',\n requestID,\n pubKey: sm2Key.publicKey,\n projectName,\n nodeIDs,\n signature: sm2.doSignature(\n `DistributeYPK|${projectName}|${sm2Key.publicKey}`,\n sm2Key.privateKey,\n { hash: true, der: true },\n ),\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n listYPKs(): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'listYPKs',\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n deleteFile(file: string): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'deleteFile',\n requestID,\n file,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n startContractByYPK(project: string): Promise {\n const sm2Key = this.sm2Key\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'startContractByYPK',\n isPrivate: true,\n requestID,\n owner: sm2Key.publicKey,\n path: `/${project}`,\n signature: sm2.doSignature(\n `Fixed|${project}|${sm2Key.publicKey}`,\n sm2Key.privateKey,\n ),\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n initBDServer(\n host: string,\n username: string,\n password: string,\n name: string,\n clusterHost: string,\n ): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'initBDServer',\n requestID,\n host,\n username,\n password,\n name,\n sm2Key: JSON.stringify(this.sm2Key),\n clusterHost,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n initBDCluster(\n host: string,\n username: string,\n password: string,\n name: string,\n sm2Key: string,\n agents: [],\n ): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'initBDCluster',\n requestID,\n host,\n username,\n password,\n name,\n sm2Key,\n agents,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n listCompiledFiles(): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'listCompiledFiles',\n requestID,\n isPrivate: true,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getManagerPubkey(): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getManagerPubkey',\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n getClusterName(): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'getClusterName',\n requestID,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n\n setClusterName(name: string): Promise {\n const requestID = `${new Date().getTime()}_${Math.floor(\n Math.random() * 10000,\n )}`\n const request = {\n action: 'setClusterName',\n requestID,\n name,\n }\n this.wssocket.send(JSON.stringify(request))\n return new Promise((resolve, reject) => {\n this.promiseCallbackPairs[requestID] = { resolve, reject }\n })\n }\n}\n"],"names":["aesEncrypt","data","aesKey","exkey","slice","aes","ExpandKey","blocks","cryptico","string2bytes","pad16","Encrypt","ciphertext","bytes2string","b256to64","rsaEncrypt","rsaKey","rsa","RSAKey","setPublic","n","e1","encrypt","loadRSAKey","strs","b64to256","split","key","setPrivate","encryptReq","reqContent","pubKey","generateAESKey","aesObj","JSON","stringify","contractID","reqContentNoId","undefined","action","decrypt","arg","requester","toString","e","genUrlParamsFromObject","obj","Object","entries","map","value","String","join","HttpClient","baseUrl","sm2Key","fetch","constructor","config","this","axiosInstance","axios","create","baseURL","timeout","buildAxiosFetch","async","path","init","Promise","resolve","reject","rawUrl","url","includes","publicKey","sign","substring","indexOf","privateKey","method","toLowerCase","encodeURI","body","then","res","clientRes","text","setTimeout","catch","err","retryTimes","Error","i","requestWithSignature","console","log","sm2","doSignature","hash","der","ping","startContract","code","params","script","startContractByYPK","_request","owner","aim","signature","executeContract","operation","withDynamicAnalysis","withSignature","request","pubkey","retryRequestWithSignature","killContractProcess","requestID","id","killAllContract","applyNodeRole","role","authNodeRole","isAccept","authorizedPubKey","managerPair","distributeContract","nodeIDs","projectName","isPrivate","sig","EventSource","addEventListener","_event","saveFile","listProjectPermission","startContractMultiPoint","peersID","type","selectUnitNum","sponsorPeerID","status","parse","val","lockEdit","unlockEdit","addNode","nodePubKey","applyRole","authNodeManager","listAllUsers","listNodes","Msg","toSign","msg","headers","listTrustUnits","listContractProcess","downloadContract","timestamp","args","resetNodeManager","kvs","filter","_k","v","all","k","updateConfig","loadNodeConfig","every","remapNodeConfigKey","WsSocket","handlerList","toSend","isSending","sendList","toReceive","wssocket","wsurl","onopen","handler","push","monitor","that","WebSocket","onerror","error","onmessage","event","sendNextSegment","receiveSeg","forEach","h","reconnect","onclose","readyState","str","length","substr","isSegment","send","pop","cid","addHandler","WsClient","promiseCallbackPairs","sessionPromise","sessionResolve","loginPromise","loginResolve","generateKeyPairHex","_reject","_","session","failed","reqId","responseID","pc","sessionReceived","loggedIn","matchCID","Date","getTime","Math","floor","random","getMetabyCID","getMetabyReadme","keyword","page","pageSize","getMetabyPubkey","segmentWord","words","getMetabyOwner","getDependentContract","contractName","queryContractLogByDate","start","queryDataByHash","argStr","getSessionID","listTheContractProcess","getMask","setMask","getMock","setMock","queryHashByOffset","offset","count","queryUserStat","distributeYPK","listYPKs","deleteFile","file","project","initBDServer","host","username","password","name","clusterHost","initBDCluster","agents","listCompiledFiles","getManagerP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A5M,KAAKyH,SAASuB,KAAKzK,KAAKC,UAAUgF,IAC3B,IAAI9C,SAAQ,CAACC,EAASC,KAC3BZ,KAAKqJ,qBAAqBzF,GAAa,CAAEjD,UAASC,SAAQ,GAE7D"} \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..327a0b6 --- /dev/null +++ b/package.json @@ -0,0 +1,51 @@ +{ + "name": "@bdware/bdcontract-sdk", + "version": "0.3.0-alpha.14", + "description": "BDContract SDK for Node.js and browsers", + "license": "MIT", + "keywords": [ + "BDWare", + "BDContract", + "SDK", + "WebSocket", + "TypeScript", + "Node.js", + "node", + "nodejs", + "browser" + ], + "main": "lib/index.js", + "module": "lib/index.mjs", + "iife": "dist/bdcontract-sdk.iife.js", + "types": "lib/index.d.ts", + "files": [ + "lib" + ], + "scripts": { + "build": "shx rm -rf lib dist && rollup -c rollup.config.js", + "lint": "eslint .", + "lint:fix": "eslint . --fix", + "pub": "npm run lint && npm publish --access public" + }, + "prettier": "@daotl/prettier-config", + "dependencies": { + "@daotl/cryptico": "^2.0.3", + "@lifeomic/axios-fetch": "^3.0.0", + "axios": "^0.27.2", + "sm-crypto": "^0.3.11" + }, + "devDependencies": { + "@daotl/eslint-config": "^0.3.31", + "@types/node": "^18.7.15", + "@types/sm-crypto": "^0.3.0", + "eslint": "^8.23.0", + "prettier": "^2.7.1", + "rollup": "^2.79.0", + "rollup-plugin-dts": "^4.2.2", + "rollup-plugin-terser": "^7.0.2", + "rollup-plugin-typescript2": "^0.33.0", + "shx": "^0.3.4", + "sucrase": "^3.25.0", + "typescript": "^4.8.2" + } +} diff --git a/rollup.config.js b/rollup.config.js new file mode 100644 index 0000000..1921fa1 --- /dev/null +++ b/rollup.config.js @@ -0,0 +1,2 @@ +require('sucrase/register') +module.exports = require('./rollup.config.ts') diff --git a/rollup.config.ts b/rollup.config.ts new file mode 100644 index 0000000..f696874 --- /dev/null +++ b/rollup.config.ts @@ -0,0 +1,41 @@ +import type { RollupOptions } from 'rollup' +import dts from 'rollup-plugin-dts' +import { terser } from 'rollup-plugin-terser' +import typescript from 'rollup-plugin-typescript2' + +const pkg = require('./package.json') + +const name = 'bdcontract' + +export default [ + { + input: 'src/index.ts', + output: [ + { + file: `${pkg.main}`, + format: 'umd', + name, + sourcemap: true, + }, + { file: `${pkg.module}`, format: 'es', sourcemap: true }, + { + file: `${pkg.iife}`, + format: 'iife', + name, + sourcemap: true, + }, + ], + plugins: [ + typescript({ + tsconfig: 'tsconfig.build.json', + useTsconfigDeclarationDir: true, + }), + terser(), + ], + }, + { + input: 'types/index.d.ts', + output: [{ file: 'lib/index.d.ts' }], + plugins: [dts()], + }, +] as RollupOptions diff --git a/src/crypto.ts b/src/crypto.ts new file mode 100644 index 0000000..caba990 --- /dev/null +++ b/src/crypto.ts @@ -0,0 +1,77 @@ +// export function aesDecrypt(data: base64) { +// const dataAscii = cryptico.b64to256(data) +// const encryptedBlocks = cryptico.string2bytes(dataAscii) +// const exkey = global.aesKey.slice(0) +// aes.ExpandKey(exkey) +// aes.Decrypt(encryptedBlocks, exkey) +// return cryptico.bytes2string(encryptedBlocks) +// } + +import type { AESKey } from '@daotl/cryptico' +import { aes, cryptico, RSAKey } from '@daotl/cryptico' + +export function aesEncrypt(data: string, aesKey: AESKey): string { + const exkey = aesKey.slice(0) + aes.ExpandKey(exkey) + let blocks = cryptico.string2bytes(data) + blocks = cryptico.pad16(blocks) + aes.Encrypt(blocks, exkey) + let ciphertext = cryptico.bytes2string(blocks) + ciphertext = cryptico.b256to64(ciphertext) + return ciphertext +} + +export function rsaEncrypt( + data: string, + rsaKey: { n: string; e1: string }, +): string { + const rsa = new RSAKey() + rsa.setPublic(rsaKey.n, rsaKey.e1) + return rsa.encrypt(data) +} + +export function loadRSAKey(rsaKey: string): RSAKey { + const str = cryptico.b64to256(rsaKey) + const strs = str.split(',') + const key = new RSAKey() + key.setPrivate(strs[0], strs[0], strs[0]) + return key +} + +// function testRSA() { +// pubKey = loadRSAKey(global.privKey) +// reqContent = {} +// reqContent.action = 'main' +// reqContent.arg = '[{"score":20},{"score":20}]' +// reqContent.contractID = 'abc' +// eReq = encryptReq(reqContent, pubKey) +// url = +// 'http://localhost:8080/SCIDE/SCManager?action=executeContractEncrypted&contractRequest=' + +// encodeURIComponent(JSON.stringify(eReq)) +// } + +export function encryptReq( + reqContent: { contractID: string }, + pubKey: RSAKey, +): { + action: string | null + contractID: string + arg: string + requester: string +} { + const aes = { + key: cryptico.generateAESKey(), + } + const aesObj = JSON.stringify(aes) + const { contractID } = reqContent + const reqContentNoId = { ...reqContent, contractID: undefined } + const encrypedReq = { + action: pubKey.decrypt(aesObj), + contractID, + arg: aesEncrypt(JSON.stringify(reqContentNoId), aes.key), + requester: cryptico.b256to64( + `${pubKey.n.toString(16)},${pubKey.e.toString(16)},0`, + ), + } + return encrypedReq +} diff --git a/src/httpClient.ts b/src/httpClient.ts new file mode 100644 index 0000000..5107ca6 --- /dev/null +++ b/src/httpClient.ts @@ -0,0 +1,582 @@ +import { buildAxiosFetch } from '@lifeomic/axios-fetch' +import axios, { type AxiosRequestConfig } from 'axios' +import type { KeyPairHex } from 'sm-crypto' +import { sm2 } from 'sm-crypto' + +import type { + ClientResponse, + ConfigNodeArgs, + ExecuteContractArgs, + ListAllUsersResponseData, + ListNodesResponse, + ListProjectPermissionRequest, + ListProjectPermissionResponseData, + LoadNodeConfigResponseData, + ExecuteContractResponse, + PingResponse, + SaveFileRequest, + StartContractByYpkRequest, +} from './types' + +const genUrlParamsFromObject = (obj: Record): string => { + return Object.entries(obj) + .map(([key, value]) => `${key}=${String(value)}`) + .join('&') +} + +export * from './types' + +export class HttpClient { + private fetch: (input: RequestInfo, init?: RequestInit) => Promise + + constructor( + private baseUrl: string, + private sm2Key: KeyPairHex, + config = {} as AxiosRequestConfig, + ) { + const axiosInstance = axios.create({ + baseURL: 'https://some-domain.com/api/', + timeout: 10000, + // headers: {'X-Custom-Header': 'foobar'} + ...config, + }) + + this.fetch = buildAxiosFetch( + axiosInstance /* , function (config) { + config.timeout = 1000; + return config; + } */, + ) + } + + async requestWithSignature( + path: string, + init?: Partial, + sm2Key?: KeyPairHex, + ): Promise> { + return new Promise>((resolve, reject) => { + const rawUrl = this.baseUrl + path + const url = `${rawUrl}${path.includes('?') ? '&' : '?'}pubKey=${ + sm2Key?.publicKey ?? this.sm2Key.publicKey + }` + + // console.log('privateKey:', this.sm2Key.privateKey) + + // console.log('publicKey:', this.sm2Key.publicKey) + + // console.log('to sign:', url.substring(url.indexOf('?') + 1)) + + const sign = this.sign( + url.substring(url.indexOf('?') + 1), + sm2Key?.privateKey, + ) + + // console.log( + // 'url:', + // init?.method?.toLowerCase() === 'post' + // ? rawUrl + // : `${encodeURI(url)}&sign=${sign}`, + // ) + + this.fetch( + init?.method?.toLowerCase() === 'post' + ? rawUrl + : `${encodeURI(url)}&sign=${sign}`, + { + ...init, + ...(init?.method === 'POST' + ? { + body: { + ...(init?.body as unknown as Record), + sign, + } as unknown as Request['body'], + } + : {}), + }, + ) + .then(async (res) => { + // console.log(res.url,'请求成功') + const clientRes = res as unknown as ClientResponse + clientRes.data = (await res.text()) as Data + // Workaround for the issue causing the 2nd consecutive request to fail: + // https://github.com/nodejs/undici/issues/1415 + setTimeout(() => { + resolve(clientRes) + }, 1) + }) + .catch((err) => { + // const clientRes = err as unknown as ClientResponse + // clientRes.data = (await err.text()) as Data + // console.log(err,'errerrerrerrerrerrerrerrerrerrerrerrerrerrerr') + setTimeout(() => { + reject(err) + }, 1) + }) + }) + } + + async retryRequestWithSignature(retryTimes: number, path: string, init?: Partial, sm2Key?: KeyPairHex ) { + let err: Error = new Error() + for (let i = 0; i(path, init, sm2Key) + } catch (e) { + if (i < retryTimes) { + console.log('1') + continue + } + err = e as Error + } + } + throw err + } + + sign(data: string, privateKey?: string): string { + return sm2.doSignature(data, privateKey ?? this.sm2Key.privateKey, { + hash: true, + der: true, + }) + } + + // ping + // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html#id15 + ping(): Promise { + return this.requestWithSignature('/SCManager?action=ping') + } + + // 启动合约 + // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html#id60 + startContract(code: string): Promise> { + const params = { action: 'startContract', script: code } + return this.requestWithSignature( + `/SCManager?${genUrlParamsFromObject(params)}`, + ) + } + + // 启动合约 + // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html#id13 + startContractByYPK( + _request: StartContractByYpkRequest, + ): Promise> { + return this.requestWithSignature( + `/SCManager?${genUrlParamsFromObject({ + action: 'startContractByYPK', + ..._request, + owner: this.sm2Key.publicKey, + aim: 'onStartContract', + signature: sm2.doSignature( + `Fixed|${_request.path}|${this.sm2Key.publicKey}`, + this.sm2Key.privateKey, + { + hash: true, + der: true, + }, + ), + })}`, + ) + } + + // 调用合约 + // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html#id69 + executeContract( + contractID: string, + operation: string, + arg: string, + { + method = 'POST', + withDynamicAnalysis = false, + withSignature = false, + } = {} as ExecuteContractArgs, + ): Promise>> { + let request = {} + if (withDynamicAnalysis === undefined) { + request = { + action: 'executeContract', + contractID, + operation, + arg, + } + } else { + request = { + action: 'executeContract', + contractID, + operation, + withDynamicAnalysis, + arg, + } + } + if (withSignature) { + request = { + ...request, + pubkey: this.sm2Key.publicKey, + signature: this.sign( + `${contractID}|${operation}|${arg ?? ''}|${this.sm2Key.publicKey}`, + ), + } + } + + return this.retryRequestWithSignature( + 3, + `/SCManager${ + method === 'GET' ? `?${genUrlParamsFromObject(request)}` : '' + }`, + { + method, + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + ...(method === 'POST' ? ({ body: request } as Request) : {}), + }, + ) + } + + // 停止合约 + // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html#id122 + killContractProcess( + contractID: string, + requestID?: string, + ): Promise> { + const _request: Record = { + action: 'killContractProcess', + id: contractID, + } + requestID && (_request.requestID = requestID!) + return this.requestWithSignature( + `/SCManager?${genUrlParamsFromObject(_request)}`, + ) + } + + // 停止所有合约 + // 地址 http://39.104.205.122:18010/SCIDE + // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html#id131 + killAllContract(): Promise> { + return this.requestWithSignature('/SCManager?action=killAllContract') + } + + // 申请角色 + // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html + applyNodeRole( + role: string, + ): Promise> { + const _request = { + action: 'applyNodeRole', + role, + } + return this.requestWithSignature( + `/SCManager?${genUrlParamsFromObject(_request)}`, + ) + } + + // 授权角色 + // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html + authNodeRole( + isAccept: boolean, + authorizedPubKey: string, + managerPair?: KeyPairHex, + ): Promise> { + const _request = { + action: 'authNodeRole', + isAccept, + authorizedPubKey, + } + return this.requestWithSignature( + `/SCManager?${genUrlParamsFromObject(_request)}`, + undefined, + managerPair, + ) + } + + // https://public.internetapi.cn/docs/bdcontract/doc/ContractAPI.html + // 用sse获取 问题未解决!!! + distributeContract( + nodeIDs: string, + projectName: string, + isPrivate: boolean, + ): void { + const signature = sm2.doSignature( + `DistributeContract|${projectName}|${this.sm2Key.publicKey}`, + this.sm2Key.privateKey, + { hash: true, der: true }, + ) + + const _request = { + action: 'distributeContract', + nodeIDs, + projectName, + isPrivate, + signature, + } + + const path = `/SCManager?${genUrlParamsFromObject(_request)}` + const url = `${this.baseUrl + path}${ + path.includes('?') ? '&' : '?' + }pubKey=${this.sm2Key.publicKey}` + const sig = sm2.doSignature( + url.substring(url.indexOf('?') + 1), + this.sm2Key.privateKey, + { + hash: true, + der: true, + }, + ) + const source = new EventSource( + `${this.baseUrl}${path}&pubKey=${this.sm2Key.publicKey}&sign=${sig}`, + ) + source.addEventListener( + 'message', + function (_event) { + // const data = event.data as DistributeContractResponse[] + // console.log(data, 'dd') + // handle message + }, + false, + ) + } + + saveFile(_request: SaveFileRequest): Promise> { + return this.requestWithSignature( + `/SCManager?${genUrlParamsFromObject({ + action: 'saveFile', + ..._request, + })}`, + ) + } + + listProjectPermission( + _request: ListProjectPermissionRequest, + ): Promise> { + return this.requestWithSignature( + `/SCManager?${genUrlParamsFromObject({ + action: 'listProjectPermission', + ..._request, + })}`, + ) + } + + startContractMultiPoint( + peersID: string, + type: number, + selectUnitNum: number, + projectName: string, + isPrivate: boolean, + sponsorPeerID: string, + ): Promise> { + const _request = { + // peerID是节点的公钥,以逗号间隔开 + peersID, + type, + selectUnitNum, + projectName, + isPrivate, + sponsorPeerID, + } + return this.requestWithSignature( + `/SCManager?${genUrlParamsFromObject({ + action: 'startContractMultiPoint', + ..._request, + })}`, + ) + } + + // 获取节点配置信息 + async loadNodeConfig(): Promise> { + const res = await this.requestWithSignature( + `/SCManager?${genUrlParamsFromObject({ + action: 'loadNodeConfig', + })}`, + ) + return { ...res, data: (res.status === 200 && res.data ? JSON.parse( res.data).data : {}) as LoadNodeConfigResponseData} + } + + // 支持的key包括:{licence,projectDir,yjsPath,dataChain,doipConfig,nodeCenter,nodeName,masterAddress,resetNodeCenterWS} + async updateConfig( + key: string, + val: string, + ): Promise> { + return this.requestWithSignature( + `/SCManager?${genUrlParamsFromObject({ + action: 'updateConfig', + key, + val, + })}`, + ) + } + + // 设置pubkey为node manager + async resetNodeManager(): Promise { + const res = await this.requestWithSignature( + `/SCManager?${genUrlParamsFromObject({ + action: 'resetNodeManager', + })}`, + ) + if (!res.data) { + return false + } + const parsed = JSON.parse(res.data) + return parsed.data === 'success' + } + + // 锁定某个用户的的私有目录编辑功能 + lockEdit(): Promise> { + return this.requestWithSignature( + `/SCManager?${genUrlParamsFromObject({ + action: 'lockEdit', + })}`, + ) + } + + // 解锁某个用户的的私有目录编辑功能 + unlockEdit(): Promise> { + return this.requestWithSignature( + `/SCManager?${genUrlParamsFromObject({ + action: 'unlockEdit', + })}`, + ) + } + + addNode(nodePubKey: string): Promise> { + return this.requestWithSignature( + `?${genUrlParamsFromObject({ + action: 'addNode', + nodePubKey, + })}`, + ) + } + + // 申请角色 + applyRole(role: string): Promise> { + return this.requestWithSignature( + `?${genUrlParamsFromObject({ + action: 'applyRole', + role, + })}`, + ) + } + + authNodeManager( + isAccept: boolean, + authorizedPubKey: string, + ): Promise> { + return this.requestWithSignature( + `?${genUrlParamsFromObject({ + action: 'authNodeManager', + isAccept, + authorizedPubKey, + })}`, + ) + } + + listAllUsers(): Promise> { + return this.requestWithSignature( + `?${genUrlParamsFromObject({ + action: 'listAllUsers', + })}`, + ) + } + + // 查看节点列表 + listNodes(): Promise { + return this.requestWithSignature( + `?${genUrlParamsFromObject({ + action: 'listNodes', + })}`, + ) as unknown as Promise + } + + // 建立可信执行集群 + async createTrustUnit( + data: { nodeName: string; pubkey: string }[], + Msg: string, + ): Promise<{ action: string; status: string }> { + const toSign = `action=createTrustUnit&data=${JSON.stringify( + data, + )}&msg=${Msg}&pubKey=04303718771b9323c204e607639f14469f9a94e55b0964a408ad3b3864b0493b645d7070da0d550f0c54b934275a8e88dedc3024467b0566db5c1108b1baeaae27` + const sig = sm2.doSignature(toSign, this.sm2Key.privateKey, { + hash: true, + der: true, + }) + + const body = { + action: 'createTrustUnit', + data, + msg: Msg, + pubKey: + '04303718771b9323c204e607639f14469f9a94e55b0964a408ad3b3864b0493b645d7070da0d550f0c54b934275a8e88dedc3024467b0566db5c1108b1baeaae27', + sign: sig, + } + return (await this.requestWithSignature('', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(body), + })) as unknown as { action: string; status: string } + } + + // 查看可信执行集群列表 + listTrustUnits(): Promise> { + return this.requestWithSignature( + `?${genUrlParamsFromObject({ + action: 'listTrustUnits', + })}`, + ) + } + + // listContractProcess 查询合约实例列表 + listContractProcess(): Promise> { + return this.requestWithSignature( + `/SCManager?${genUrlParamsFromObject({ + action: 'listContractProcess', + })}`, + ) + } + + // 下载合约 + downloadContract( + projectName: string, + isPrivate: boolean, + timestamp: number + ): Promise> { + const _request = { + action: 'downloadContract', + projectName, + isPrivate, + timestamp, + } + return this.requestWithSignature( + `/CMManager?${genUrlParamsFromObject(_request)}`) + } + + // 配置合约引擎节点,若节点没有设置过node manager,将当前key设置为node manager + async configNode( + args: ConfigNodeArgs, + ): Promise { + if (!(await this.resetNodeManager())) { + return false + } + + const kvs: [string, string][] = Object.entries(args).filter(([_k, v]) => v) as [string, string][] + + await Promise.all([ + ...kvs.map(([k, v]) => this.updateConfig(k, v!)), + this.applyNodeRole('ContractProvider'), + this.applyNodeRole('ContractUser'), + this.applyNodeRole('ContractInstanceManager'), + this.authNodeRole(true, this.sm2Key.publicKey), + ]) + + const config = (await this.loadNodeConfig()).data + if (!config) { + return false + } + + return kvs.every(([k, v]) => config[remapNodeConfigKey(k)] === v) + } +} + +function remapNodeConfigKey(k: string) { + switch (k) { + case 'dataChain': + return 'bdledger' + default: + return k + } +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..ca7bba1 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,4 @@ +export * from './crypto' +export * from './httpClient' +export * from './wsClient' +export * from './wssocket' diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..d383d6b --- /dev/null +++ b/src/types.ts @@ -0,0 +1,101 @@ +export type ClientResponse = Omit & { + data?: Data +} + +export type PingResponse = ClientResponse<'pong'> + +export interface SaveFileRequest { + content: string + isAppend: boolean + isPrivate: boolean + path: string +} + +export interface ListProjectPermissionRequest { + isPrivate: boolean + path: string +} + +export interface ListProjectPermissionResponseData { + permissions: string[] + ypk: string +} + +export interface StartContractByYpkRequest { + isPrivate: boolean + path: string + script: string + // signature: string +} + +export interface ListAllUsersResponseDataListItem { + key: string + value: string +} +export interface ListAllUsersResponseData { + kv: ListAllUsersResponseDataListItem[] + time: ListAllUsersResponseDataListItem[] +} +export interface OnlineContractsItem { + contractID: string + contractName: string + isMaster: boolean + type: string + yjsType: string + [key: string]: unknown +} +export interface OnlineItem { + cimanager: string + contractVersion: number + events: number + ipPort: string + masterAddress: string + nodeName: string + peerID: string + pubKey: string + contracts: OnlineContractsItem[] +} + +export interface ListNodesResponse { + action: string + offline: string[] + online: OnlineItem[] +} + +export interface DistributeContractResponse { + action: string + progress: string +} + +export interface ExecuteContractArgs extends RequestInit { + method?: 'POST' | 'GET' + // 是否使用签名 + withSignature?: boolean + withDynamicAnalysis?: boolean +} + +export interface ExecuteContractResponse { + // ok: boolean + status?: boolean + // statusText: string + data?: Data + executeTime?: number + cid?: string + isPrivate?: boolean + [key: string]: unknown +} + +export interface ConfigNodeArgs { + nodeName?: string + dataChain?: string + masterAddress?: string + nodeCenter?: string + // 配置中心节点时使用 + LHSProxyAddress?: string + [K: string]: string | undefined +} + +export interface LoadNodeConfigResponseData { + doipConfig: string + [K: string]: string +} diff --git a/src/wsClient.ts b/src/wsClient.ts new file mode 100644 index 0000000..8002368 --- /dev/null +++ b/src/wsClient.ts @@ -0,0 +1,741 @@ +/* eslint-disable no-cond-assign */ + +import type { KeyPairHex } from 'sm-crypto' +import { sm2 } from 'sm-crypto' + +import type { OnOpenHandler, WsHandler } from './wssocket' +import { WsSocket } from './wssocket' + +interface ResponseData { + action: string + responseID?: string + status: true | false | string // 'Success' | 'Exception' | 'Error' | 'failed: no session' + result?: unknown + data: string + [K: string]: unknown +} + +// interface ListResponseData { +// action: string +// data: string +// status: true | false +// } + +interface PromiseCallbackPair { + resolve: (value: ResponseData | PromiseLike) => void + reject: (reason?: unknown) => void +} + +export class WsClient { + private readonly sm2Key: KeyPairHex + private readonly wssocket: WsSocket + private readonly promiseCallbackPairs: Record = + {} + + private readonly sessionPromise: Promise + private sessionResolve!: (value: string | PromiseLike) => void + private readonly loginPromise: Promise + private loginResolve!: (value: boolean | PromiseLike) => void + + constructor( + url: string, + onopen: OnOpenHandler, + handler: WsHandler, + sm2Key: KeyPairHex = sm2.generateKeyPairHex(), + ) { + this.sm2Key = sm2Key + this.sessionPromise = new Promise((resolve, _reject) => { + this.sessionResolve = resolve + }) + this.loginPromise = new Promise((resolve, _reject) => { + this.loginResolve = resolve + }) + // eslint-disable-next-line @typescript-eslint/no-this-alias + const that = this + this.wssocket = new WsSocket(url, onopen, function ( + this: WebSocket, + event, + _, + ) { + const data = JSON.parse(event.data) as ResponseData + + switch (data.action) { + case 'onSessionID': + that.sessionResolve(data.session as string) + break + case 'onLogin': + { + const failed = + typeof data.status === 'string' && + data.status.toLowerCase().includes('failed') + that.loginResolve(!failed) + } + break + } + + const reqId = data.responseID + let pc: PromiseCallbackPair | undefined + if (reqId && (pc = that.promiseCallbackPairs[reqId])) { + if (data) { + pc.resolve(data) + } else { + pc.reject(data) + } + } + handler(event, this) + }) + } + + status(): WebSocket['CLOSED' | 'CLOSING' | 'CONNECTING' | 'OPEN'] { + return this.wssocket.status() + } + + sessionReceived(): Promise { + return this.sessionPromise + } + + async login(): Promise { + const session = await this.sessionPromise + const request = { + action: 'login', + pubKey: this.sm2Key.publicKey, + signature: sm2.doSignature(session, this.sm2Key.privateKey, { + hash: true, + der: true, + }), + } + this.wssocket.send(JSON.stringify(request)) + return this.loginPromise + } + + loggedIn(): Promise { + return this.loginPromise + } + + matchCID(contractID: string): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'matchCID', + contractID, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + getMetabyCID(contractID: string): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'getMetabyCID', + contractID, + requestID, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + getMetabyReadme( + keyword: string, + page?: string, + pageSize?: string, + ): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'getMetabyReadme', + page, + pageSize, + keyword, + requestID, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + getMetabyPubkey(pubkey: string): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'getMetabyPubkey', + pubkey, + requestID, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + segmentWord(words: string): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + words, + action: 'segmentWord', + requestID, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + getMetabyOwner( + owner: string, + page?: string, + pageSize?: string, + ): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'getMetabyOwner', + owner, + page, + pageSize, + requestID, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + getDependentContract(contractName: string): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'getDependentContract', + requestID, + contractName, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + queryContractLogByDate(start: number): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'queryContractLogByDate', + requestID, + start, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + queryDataByHash(hash: string): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'queryDataByHash', + requestID, + hash, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + executeContract( + contractID: string, + method: string, + arg: unknown, + ): Promise { + const sm2Key = this.sm2Key + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const argStr = (typeof arg) == 'object' ? JSON.stringify(arg):arg+""; + const request = { + action: 'executeContract', + requestID, + contractID, + operation: method, + arg: arg, + ...(sm2Key + ? { + pubkey: sm2Key.publicKey, + signature: sm2.doSignature( + `${contractID}|${method}|${argStr}|${sm2Key.publicKey}`, + sm2Key.privateKey, + { hash: true, der: true }, + ), + } + : {}), + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + getSessionID(): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'getSessionID', + requestID, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + listTheContractProcess(contractID: string): Promise { + const sm2Key = this.sm2Key + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'listTheContractProcess', + requestID, + contractID, + ...(sm2Key + ? { + pubkey: sm2Key.publicKey, + signature: sm2.doSignature( + `${contractID}|${sm2Key.publicKey}`, + sm2Key.privateKey, + { hash: true, der: true }, + ), + } + : {}), + } + this.wssocket.send(JSON.stringify(request)) + + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + getMask( + contractID: string, + // operation: string, + ): Promise { + const sm2Key = this.sm2Key + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'getMask', + requestID, + contractID, + // operation, + ...(sm2Key + ? { + pubkey: sm2Key.publicKey, + signature: sm2.doSignature( + `${contractID}|${sm2Key.publicKey}`, + sm2Key.privateKey, + { hash: true, der: true }, + ), + } + : {}), + } + + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + setMask( + contractID: string, + operation: string, + arg: string, + ): Promise { + const sm2Key = this.sm2Key + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'setMask', + requestID, + contractID, + operation, + arg, + ...(sm2Key + ? { + pubkey: sm2Key.publicKey, + signature: sm2.doSignature( + `${contractID}|${sm2Key.publicKey}`, + sm2Key.privateKey, + { hash: true, der: true }, + ), + } + : {}), + } + + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + getMock( + contractID: string, + // operation: string, + ): Promise { + const sm2Key = this.sm2Key + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'getMock', + requestID, + contractID, + // operation, + ...(sm2Key + ? { + pubkey: sm2Key.publicKey, + signature: sm2.doSignature( + `${contractID}|${sm2Key.publicKey}`, + sm2Key.privateKey, + { hash: true, der: true }, + ), + } + : {}), + } + + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + setMock( + contractID: string, + operation: string, + arg: string, + ): Promise { + const sm2Key = this.sm2Key + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'setMock', + requestID, + contractID, + operation, + arg, + ...(sm2Key + ? { + pubkey: sm2Key.publicKey, + signature: sm2.doSignature( + `${contractID}|${sm2Key.publicKey}`, + sm2Key.privateKey, + { hash: true, der: true }, + ), + } + : {}), + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + queryHashByOffset(offset: number, count: number): Promise { + const sm2Key = this.sm2Key + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'queryHashByOffset', + requestID, + offset, + count, + ...(sm2Key + ? { + pubkey: sm2Key.publicKey, + /* signature: sm2.doSignature( + id + '|' + sm2Key.publicKey, + sm2Key.privateKey, + { hash: true, der: true }, + ), */ + } + : {}), + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + loadNodeConfig(): Promise { + const sm2Key = this.sm2Key + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'loadNodeConfig', + requestID, + + ...(sm2Key + ? { + pubkey: sm2Key.publicKey, + signature: sm2.doSignature(sm2Key.publicKey, sm2Key.privateKey, { + hash: true, + der: true, + }), + } + : {}), + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + queryUserStat(): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'queryUserStat', + requestID, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + listNodes(): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'listNodes', + requestID, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + killContractProcess(id: string): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'killContractProcess', + requestID, + id, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + distributeYPK(projectName: string, nodeIDs: string): Promise { + const sm2Key = this.sm2Key + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'distributeYPK', + requestID, + pubKey: sm2Key.publicKey, + projectName, + nodeIDs, + signature: sm2.doSignature( + `DistributeYPK|${projectName}|${sm2Key.publicKey}`, + sm2Key.privateKey, + { hash: true, der: true }, + ), + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + listYPKs(): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'listYPKs', + requestID, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + deleteFile(file: string): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'deleteFile', + requestID, + file, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + startContractByYPK(project: string): Promise { + const sm2Key = this.sm2Key + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'startContractByYPK', + isPrivate: true, + requestID, + owner: sm2Key.publicKey, + path: `/${project}`, + signature: sm2.doSignature( + `Fixed|${project}|${sm2Key.publicKey}`, + sm2Key.privateKey, + ), + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + initBDServer( + host: string, + username: string, + password: string, + name: string, + clusterHost: string, + ): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'initBDServer', + requestID, + host, + username, + password, + name, + sm2Key: JSON.stringify(this.sm2Key), + clusterHost, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + initBDCluster( + host: string, + username: string, + password: string, + name: string, + sm2Key: string, + agents: [], + ): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'initBDCluster', + requestID, + host, + username, + password, + name, + sm2Key, + agents, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + listCompiledFiles(): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'listCompiledFiles', + requestID, + isPrivate: true, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + getManagerPubkey(): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'getManagerPubkey', + requestID, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + getClusterName(): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'getClusterName', + requestID, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } + + setClusterName(name: string): Promise { + const requestID = `${new Date().getTime()}_${Math.floor( + Math.random() * 10000, + )}` + const request = { + action: 'setClusterName', + requestID, + name, + } + this.wssocket.send(JSON.stringify(request)) + return new Promise((resolve, reject) => { + this.promiseCallbackPairs[requestID] = { resolve, reject } + }) + } +} diff --git a/src/wssocket.ts b/src/wssocket.ts new file mode 100644 index 0000000..6dc1b56 --- /dev/null +++ b/src/wssocket.ts @@ -0,0 +1,143 @@ +/* eslint-disable no-console,no-cond-assign */ + +export interface WsEvent { + data: string +} + +export type OnOpenHandler = (this: WebSocket, ev: Event) => void +export type WsHandler = (ev: WsEvent, ws?: WebSocket) => void + +interface SegmentData { + action: 'sendSeg' + cid: string + data: string +} + +export class WsSocket { + private handlerList: WsHandler[] = [] + private toSend = '' + private isSending = false + private sendList: string[] = [] + private toReceive = '' + private wssocket: WebSocket + + constructor(wsurl: string, onopen: OnOpenHandler, handler?: WsHandler) { + console.log(`[createWS.js] createWssocket : ${wsurl}`) + if (handler) { + this.handlerList.push(handler) + } + + // TODO: we don't need monitor at all? + this.monitor() + + // eslint-disable-next-line @typescript-eslint/no-this-alias + const that = this + + const wssocket = (this.wssocket = new WebSocket(wsurl)) + wssocket.onerror = function (error): void { + console.log(error) + } + wssocket.onopen = onopen + + const onmessage = function (this: WebSocket, event: MessageEvent): void { + const obj = JSON.parse(event.data as string) as { action: string } + switch (obj.action) { + case 'sendNextSegment': + that.sendNextSegment() + break + case 'sendSeg': + that.receiveSeg(obj as SegmentData) + break + default: + that.handlerList.forEach((h) => h(event, this)) + } + } + wssocket.onmessage = onmessage + + const reconnect = function (): void { + setTimeout(() => { + console.log('[createWS.js] try to reconnect') + const wssocket = (that.wssocket = new WebSocket(wsurl)) + wssocket.onclose = reconnect + wssocket.onmessage = onmessage + wssocket.onopen = onopen + }, 1000) + } + wssocket.onclose = reconnect + } + + status(): WebSocket['CLOSED' | 'CLOSING' | 'CONNECTING' | 'OPEN'] { + return this.wssocket.readyState + } + + sendNextSegment(): void { + const str = this.toSend + if (str.length > 1024) { + this.toSend = str.substr(1024) + const obj = { + isSegment: true, + data: str.substr(0, 1024), + } + this.wssocket.send(JSON.stringify(obj)) + } else { + this.toSend = '' + const obj = { + isSegment: false, + data: str, + } + this.wssocket.send(JSON.stringify(obj)) + this.isSending = false + let data + if ((data = this.sendList.pop())) { + this.send(data) + } + } + } + + receiveSeg(obj: SegmentData): void { + if (obj.cid === 'start') { + this.toReceive = '' + } + this.toReceive += obj.data + if (obj.cid === 'done') { + console.log(`[receiveSeg] Received AllData:${this.toReceive}`) + const event: WsEvent = { + data: this.toReceive, + } + this.toReceive = '' + this.handlerList.forEach((h) => h(event, this.wssocket)) + } + } + + monitor(): void { + if (!this.isSending) { + let data + if ((data = this.sendList.pop())) { + this.send(data) + } + } + setTimeout(() => this.monitor(), 1000) + } + + send(data: string): void { + if (this.isSending) { + this.sendList.push(data) + return + } + if (data.length > 1024) { + this.isSending = true + this.toSend = data.substr(1024) + const obj = { + isSegment: true, + data: data.substr(0, 1024), + } + this.wssocket.send(JSON.stringify(obj)) + } else { + this.wssocket.send(data) + } + } + + addHandler(handler: WsHandler): void { + this.handlerList.push(handler) + } +} diff --git a/test-node/http.html b/test-node/http.html new file mode 100644 index 0000000..bc8cc51 --- /dev/null +++ b/test-node/http.html @@ -0,0 +1,91 @@ + + + + + + + + + + + Vite App + + + diff --git a/test-node/index.js b/test-node/index.js new file mode 100644 index 0000000..2ced9e6 --- /dev/null +++ b/test-node/index.js @@ -0,0 +1,103 @@ +const bdcontract = require('@bdcontract/sdk') +// const sm2 = require('sm-crypto') +// import { sm2 } from 'sm-crypto' +async function main() { + // const url = 'http://localhost:21030/SCIDE' + const url = 'http://39.104.201.40:18010/SCIDE' + // const url = 'http://39.104.201.40:18010/NodeCenter' + // const url = 'http://021.node.internetapi.cn:18060/NodeCenter' + // const url = 'http://localhost/8080/api/sse' + // eslint-disable-next-line no-undef + const sm2Key = { + publicKey: + '04303718771b9323c204e607639f14469f9a94e55b0964a408ad3b3864b0493b645d7070da0d550f0c54b934275a8e88dedc3024467b0566db5c1108b1baeaae27', + privateKey: + 'd675782acf011dbc01a73c7967ccff9564486f7c3a9f5d5de151caffaa18936', + } + + // const keyPair = sm2.generateKeyPairHex() + + // const url1 = 'http://023.node.internetapi.cn:18010/SCIDE/SCManager' + // const url1 = 'http://023.node.internetapi.cn:18010/SCIDE/SCManager?action=applyNodeRole&role=ContractProvider&pubKey=04303718771b9323c204e607639f14469f9a94e55b0964a408ad3b3864b0493b645d7070da0d550f0c54b934275a8e88dedc3024467b0566db5c1108b1baeaae27&sign=3046022100d186df39542f44deb08ca9a6a33ea4c0eef4222c3d0a9821e836a231daa615fa022100d89b202b3bb44c8caf98b3c415c62359eab2607c391ad04ba39034a550a78db3' + // const res1 = await fetch(url1) + // console.log(res1) + // const res2 = await fetch(url1) + // console.log(res2) + + // eslint-disable-next-line no-undef + const client = new bdcontract.HttpClient(url, sm2Key, { timeout: 20000 }) + + try { + // const result = await client.executeContract( + // 'ControlProxy', + // 'setName', + // { name: 'df' }, + // 'POST', + // true, + // ) + // const result = await client.updateConfig('dataChain', 'ddsjkdsf') + // const result = await client.resetNodeManager() + // const result = await client.applyNodeRole('ContractProvider') + // const result = await client.loadNodeConfig() + // const result = await client.configContract({ + // nodeName: 'test', + // bdledgerAddr: 'bdledger:2401', + // masterAddr: 'localhost:21030', + // contractCenterAddr: 'localhost:21040', + // // 配置中心节点时使用 + // LHSProxyAddress: 'http://localhost:21041', + // }) + // console.log(result, 'res1') + + const result = await client.executeContract( + 'ControlProxy', + 'getDoList', + 1, + true, + ) + console.log(result, 'res1') + } catch (e) { + console.log('error: ', e.message) + } + + // const res2 = await client.applyNodeRole('ContractInstanceManager') + // console.log(res2.data, 'res2') + // const res2 = await client.authNodeManager( + // true, + // '0430276215ff414e0047a532d4dea32048ad4ec60a729ce8e4248c98889d244c3b27b9549e5cb664ce324e2acac4a81590321f4196ca159cb577e06a3eb553ce6a', + // ) + // // const res3 = await client.applyRole('NodeManager') + // console.log(res2, 'res2res2res2res2res2res2res2res2res2res2res2') + // const res3 = await client.applyNodeRole( + // '0430276215ff414e0047a532d4dea32048ad4ec60a729ce8e4248c98889d244c3b27b9549e5cb664ce324e2acac4a81590321f4196ca159cb577e06a3eb553ce6a', + // 'ContractInstanceManager', + // ) + // console.log(res3, 'res33333333333333333333333333333333') + // // console.log(res1.data, 'data') + // const res1 = await client.authNodeRole( + // true, + // '0430276215ff414e0047a532d4dea32048ad4ec60a729ce8e4248c98889d244c3b27b9549e5cb664ce324e2acac4a81590321f4196ca159cb577e06a3eb553ce6a', + // ) + // console.log(res1, 'res11111111111111111111111111111111') + // console.log(res1.data, 'data') + + // const res1 = await client.applyRole('ContractProvider') + // console.log(res1, 'res') + // console.log(res1.data, 'data') + + // let i = 0 + // for (i = 0; i < 3000000000; i++) { + // a = i + 1 + // if (a > 100000000000000) { + // console.log('b') + // } + // } + + // setTimeout(async ()=> { + // const client2 = new bdcontract.HttpClient(url, sm2Key) + // const res2 = await client.applyNodeRole('ContractInstanceManager') + // console.log(res2) + // }, 1) +} + +void main().then(console.log) diff --git a/test-node/package.json b/test-node/package.json new file mode 100644 index 0000000..ea6fd04 --- /dev/null +++ b/test-node/package.json @@ -0,0 +1,9 @@ +{ + "dependencies": { + "@bdcontract/sdk": "link:..", + "@formily/core": "^2.2.5", + "@formily/element-plus": "1.0.0-beta.6", + "@formily/vue": "^2.2.5", + "@vue/composition-api": "^1.7.1" + } +} diff --git a/test-node/tsconfig.json b/test-node/tsconfig.json new file mode 100644 index 0000000..6424e69 --- /dev/null +++ b/test-node/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "allowJs": true, + "target": "esnext", + "module": "esnext", + "lib": ["esnext", "dom", "dom.iterable"], + "moduleResolution": "Node", + "types": ["node"], + "strict": true, + "sourceMap": true, + "resolveJsonModule": true, + "esModuleInterop": true, + "noEmit": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true + } +} diff --git a/test/cryptico.iife.js b/test/cryptico.iife.js new file mode 100644 index 0000000..6359ed2 --- /dev/null +++ b/test/cryptico.iife.js @@ -0,0 +1,2 @@ +var cryptico=function(t,s){"use strict";function e(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var i=e(s);!function(){const t={};try{if(process)return process.env=Object.assign({},process.env),void Object.assign(process.env,t)}catch(t){}globalThis.process={env:t}}();const r={Sbox:[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],ShiftRowTab:[0,5,10,15,4,9,14,3,8,13,2,7,12,1,6,11],Sbox_Inv:new Array(256),ShiftRowTab_Inv:new Array(16),xtime:new Array(256),Init(){for(let t=0;t<256;t++)this.Sbox_Inv[this.Sbox[t]]=t;for(let t=0;t<16;t++)this.ShiftRowTab_Inv[this.ShiftRowTab[t]]=t;for(let t=0;t<128;t++)this.xtime[t]=t<<1,this.xtime[128+t]=t<<1^27},Done(){this.Sbox_Inv.length=0,this.Sbox_Inv.length=256,this.ShiftRowTab_Inv.length=0,this.ShiftRowTab_Inv.length=16,this.xtime.length=0,this.xtime.length=256},ExpandKey(t){const s=t.length;let e,i=1;switch(s){case 16:e=176;break;case 24:e=208;break;case 32:e=240;break;default:throw"my.ExpandKey: Only key lengths of 16, 24 or 32 bytes allowed!"}for(let n=s;n=256&&(i^=283)):s>24&&n%s==16&&(e=[r.Sbox[e[0]],r.Sbox[e[1]],r.Sbox[e[2]],r.Sbox[e[3]]]);for(let i=0;i<4;i++)t[n+i]=t[n+i-s]^e[i]}},Encrypt(t,s){const e=s.length;let i;for(r.AddRoundKey(t,s.slice(0,16)),i=16;i=16;i-=16)r.AddRoundKey(t,s.slice(i,i+16)),r.MixColumns_Inv(t),r.ShiftRows(t,r.ShiftRowTab_Inv),r.SubBytes(t,r.Sbox_Inv);r.AddRoundKey(t,s.slice(0,16))},SubBytes(t,s){for(let e=0;e<16;e++)t[e]=s[t[e]]},AddRoundKey(t,s){for(let e=0;e<16;e++)t[e]^=s[e]},ShiftRows(t,s){const e=(new Array).concat(t);for(let i=0;i<16;i++)t[i]=e[s[i]]},MixColumns(t){for(let s=0;s<16;s+=4){const e=t[s+0],i=t[s+1],n=t[s+2],o=t[s+3],h=e^i^n^o;t[s+0]^=h^r.xtime[e^i],t[s+1]^=h^r.xtime[i^n],t[s+2]^=h^r.xtime[n^o],t[s+3]^=h^r.xtime[o^e]}},MixColumns_Inv(t){for(let s=0;s<16;s+=4){const e=t[s+0],i=t[s+1],n=t[s+2],o=t[s+3],h=e^i^n^o,c=r.xtime[h],u=r.xtime[r.xtime[c^e^n]]^h,f=r.xtime[r.xtime[c^i^o]]^h;t[s+0]^=u^r.xtime[e^i],t[s+1]^=f^r.xtime[i^n],t[s+2]^=u^r.xtime[n^o],t[s+3]^=f^r.xtime[o^e]}}},n=[],o=256,h=Math.pow(2,52),c=2*h,u=Math.pow(o,6),f={seedrandom(t,s=!1){const e=[];t=m(a(s?[t,n]:arguments.length?t:[(new Date).getTime(),n],3),e);const i=new l(e);return m(i.S,n),f.random=function(){let t=i.g(6),s=u,e=0;for(;t=c;)t/=2,s/=2,e>>>=1;return(t+e)/s},t},random:function(){return Math.random()}};class l{i=0;j=0;S=[];c=[];constructor(t){let s,e,i=t.length,r=0,n=0;for(i||(t=[i++]);rr+=String.fromCharCode(t))),r}function d(t){return 255&t}m(Math.random(),n);class p{nextBytes(t){for(let s=0;s>8&255,T[S++]^=t>>16&255,T[S++]^=t>>24&255,S>=256&&(S-=256)}if(!T){let t;for(T=[],S=0;S<256;)t=Math.floor(65536*Math.random()),T[S++]=t>>>8,T[S++]=255&t;S=0,w()}function y(){if(!b){for(w(),b=new g,b.init(T),S=0;St&s,A=(t,s)=>t|s,x=(t,s)=>t^s,B=(t,s)=>t&~s;class R{static DB=30;static DM=(1<<30)-1;static DV=1<<30;static FV=Math.pow(2,52);static F1=22;static F2=8;static ZERO=new R(0);static ONE=new R(1);s=0;t=0;constructor(t,s,e){t&&("number"==typeof t?s?this.fromNumber(t,s,e):this.fromInt(t):this.fromString(t,s||256))}am(t,s,e,i,r,n){const o=32767&s,h=s>>15;for(;--n>=0;){let s=32767&this[t];const n=this[t++]>>15,c=h*s+n*o;s=o*s+((32767&c)<<15)+e[i]+(1073741823&r),r=(s>>>30)+(c>>>15)+h*n+(r>>>30),e[i++]=1073741823&s}return r}copyTo(t){for(let s=this.t-1;s>=0;--s)t[s]=this[s];t.t=this.t,t.s=this.s}fromInt(t){this.t=1,this.s=t<0?-1:0,t>0?this[0]=t:t<-1?this[0]=t+R.DV:this.t=0}fromString(t,s){let e;if(16===s)e=4;else if(8===s)e=3;else if(256===s)e=8;else if(2===s)e=1;else if(32===s)e=5;else{if(4!==s)return void this.fromRadix(t,s);e=2}this.t=0,this.s=0;let i=t.length,r=!1,n=0;for(;--i>=0;){const s=8===e?t[i]:I(t,i);s<0?"-"===t.charAt(i)&&(r=!0):(r=!1,0===n?this[this.t++]=s:n+e>R.DB?(this[this.t-1]|=(s&(1<>R.DB-n):this[this.t-1]|=s<=R.DB&&(n-=R.DB))}8===e&&0!=(128&t[0])&&(this.s=-1,n>0&&(this[this.t-1]|=(1<0&&this[this.t-1]===t;)--this.t}toString(t=16){if(this.s<0)return"-"+this.negate().toString(t);let s;if(16===t)s=4;else if(8===t)s=3;else if(2===t)s=1;else if(32===t)s=5;else if(64===t)s=6;else{if(4!==t)return this.toRadix(t);s=2}const e=(1<0)for(h>h)>0&&(r=!0,n=O(i));o>=0;)h>(h+=R.DB-s)):(i=this[o]>>(h-=s)&e,h<=0&&(h+=R.DB,--o)),i>0&&(r=!0),r&&(n+=O(i));return r?n:"0"}negate(){const t=new R;return R.ZERO.subTo(this,t),t}abs(){return this.s<0?this.negate():this}compareTo(t){let s=this.s-t.s;if(0!==s)return s;let e=this.t;if(s=e-t.t,0!==s)return s;for(;--e>=0;)if(0!=(s=this[e]-t[e]))return s;return 0}bitLength(){return this.t<=0?0:R.DB*(this.t-1)+q(this[this.t-1]^this.s&R.DM)}dlShiftTo(t,s){let e;for(e=this.t-1;e>=0;--e)s[e+t]=this[e];for(e=t-1;e>=0;--e)s[e]=0;s.t=this.t+t,s.s=this.s}drShiftTo(t,s){for(let e=t;e=0;--o)s[o+n+1]=this[o]>>i|h,h=(this[o]&r)<=0;--o)s[o]=0;s[n]=h,s.t=this.t+n+1,s.s=this.s,s.clamp()}rShiftTo(t,s){s.s=this.s;const e=Math.floor(t/R.DB);if(e>=this.t)return void(s.t=0);const i=t%R.DB,r=R.DB-i,n=(1<>i;for(let t=e+1;t>i;i>0&&(s[this.t-e-1]|=(this.s&n)<>=R.DB;if(t.t>=R.DB;r+=this.s}else{for(r+=this.s;i>=R.DB;r-=t.s}s.s=r<0?-1:0,r<-1?s[i++]=R.DV+r:r>0&&(s[i++]=r),s.t=i,s.clamp()}multiplyTo(t,s){const e=this.abs(),i=t.abs();let r=e.t;for(s.t=r+i.t;--r>=0;)s[r]=0;for(r=0;r=0;)t[e]=0;for(e=0;e=R.DV&&(t[e+s.t]-=R.DV,t[e+s.t+1]=1)}t.t>0&&(t[t.t-1]+=s.am(e,s[e],t,2*e,0,1)),t.s=0,t.clamp()}divRemTo(t,s,e){const i=t.abs();if(i.t<=0)return;const r=this.abs();if(r.t0?(i.lShiftTo(c,n),r.lShiftTo(c,e)):(i.copyTo(n),r.copyTo(e));const u=n.t,f=n[u-1];if(0===f)return;const l=f*(1<1?n[u-2]>>R.F2:0),a=R.FV/l,m=(1<=0&&(e[e.t++]=1,e.subTo(p,e)),R.ONE.dlShiftTo(u,p),p.subTo(n,n);n.t=0;){let t=e[--g]===f?R.DM:Math.floor(e[g]*a+(e[g-1]+d)*m);if((e[g]+=n.am(0,t,e,b,0,u))0&&e.rShiftTo(c,e),o<0&&R.ZERO.subTo(e,e)}mod(t){const s=new R;return this.abs().divRemTo(t,void 0,s),this.s<0&&s.compareTo(R.ZERO)>0&&t.subTo(s,s),s}invDigit(){if(this.t<1)return 0;const t=this[0];if(0==(1&t))return 0;let s=3&t;return s=s*(2-(15&t)*s)&15,s=s*(2-(255&t)*s)&255,s=s*(2-((65535&t)*s&65535))&65535,s=s*(2-t*s%R.DV)%R.DV,s>0?R.DV-s:-s}isEven(){return 0===(this.t>0?1&this[0]:this.s)}exp(t,s){if(t>4294967295||t<1)return R.ONE;const e=s.convert(this);let i=new R,r=new R,n=q(t)-1;for(e.copyTo(i);--n>=0;)if(s.sqrTo(i,r),(t&1<0)s.mulTo(r,e,i);else{const t=i;i=r,r=t}return s.revert(i)}modPowInt(t,s){let e;return e=t<256||s.isEven()?new P(s):new N(s),this.exp(t,e)}clone(){const t=new R;return this.copyTo(t),t}intValue(){if(this.s<0){if(1===this.t)return this[0]-R.DV;if(0===this.t)return-1}else{if(1===this.t)return this[0];if(0===this.t)return 0}return(this[1]&(1<<32-R.DB)-1)<>24}shortValue(){return 0===this.t?this.s:this[0]<<16>>16}chunkSize(t){return Math.floor(Math.LN2*R.DB/Math.log(t))}signum(){return this.s<0?-1:this.t<=0||1===this.t&&this[0]<=0?0:1}toRadix(t){if(t||(t=10),0===this.signum()||t<2||t>36)return"0";const s=this.chunkSize(t),e=Math.pow(t,s),i=new R(e),r=new R,n=new R;let o="";for(this.divRemTo(i,r,n);r.signum()>0;)o=(e+n.intValue()).toString(t).substr(1)+o,r.divRemTo(i,r,n);return n.intValue().toString(t)+o}fromRadix(t,s){this.fromInt(0),s||(s=10);const e=this.chunkSize(s),i=Math.pow(s,e);let r=!1,n=0,o=0;for(let h=0;h=e&&(this.dMultiply(i),this.dAddOffset(o,0),n=0,o=0))}n>0&&(this.dMultiply(Math.pow(s,n)),this.dAddOffset(o,0)),r&&R.ZERO.subTo(this,this)}fromNumber(t,s,e){if("number"==typeof s)if(t<2)this.fromInt(1);else for(this.fromNumber(t,e),this.testBit(t-1)||this.bitwiseTo(R.ONE.shiftLeft(t-1),A,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(s);)this.dAddOffset(2,0),this.bitLength()>t&&this.subTo(R.ONE.shiftLeft(t-1),this);else{const e=[],i=7&t;e.length=1+(t>>3),s.nextBytes(e),i>0?e[0]&=(1<0)for(i>i)!=(this.s&R.DM)>>i&&(t[r++]=e|this.s<=0;)i<8?(e=(this[s]&(1<>(i+=R.DB-8)):(e=this[s]>>(i-=8)&255,i<=0&&(i+=R.DB,--s)),0!=(128&e)&&(e|=-256),0===r&&(128&this.s)!=(128&e)&&++r,(r>0||e!==this.s)&&(t[r++]=e);return t}equals(t){return 0===this.compareTo(t)}min(t){return this.compareTo(t)<0?this:t}max(t){return this.compareTo(t)>0?this:t}bitwiseTo(t,s,e){const i=Math.min(t.t,this.t);let r;for(let r=0;r=this.t?0!==this.s:0!=(this[s]&1<>=R.DB;if(t.t>=R.DB;r+=this.s}else{for(r+=this.s;i>=R.DB;r+=t.s}s.s=r<0?-1:0,r>0?s[i++]=r:r<-1&&(s[i++]=R.DV+r),s.t=i,s.clamp()}add(t){const s=new R;return this.addTo(t,s),s}subtract(t){const s=new R;return this.subTo(t,s),s}multiply(t){const s=new R;return this.multiplyTo(t,s),s}square(){const t=new R;return this.squareTo(t),t}divide(t){const s=new R;return this.divRemTo(t,s,void 0),s}remainder(t){const s=new R;return this.divRemTo(t,void 0,s),s}divideAndRemainder(t){const s=new R,e=new R;return this.divRemTo(t,s,e),[s,e]}dMultiply(t){this[this.t]=this.am(0,t-1,this,0,0,this.t),++this.t,this.clamp()}dAddOffset(t,s){if(0!==t){for(;this.t<=s;)this[this.t++]=0;for(this[s]+=t;this[s]>=R.DV;)this[s]-=R.DV,++s>=this.t&&(this[this.t++]=0),++this[s]}}pow(t){return this.exp(t,new V)}multiplyLowerTo(t,s,e){let i,r=Math.min(this.t+t.t,s);for(e.s=0,e.t=r;r>0;)e[--r]=0;for(i=e.t-this.t;r=0;)e[i]=0;for(i=Math.max(s-this.t,0);i1){const t=new R;for(i.sqrTo(o[1],t);u<=c;)o[u]=new R,i.mulTo(t,o[u-2],o[u]),u+=2}let f,l,a=t.t-1,m=!0,d=new R;for(r=q(t[a])-1;a>=0;){for(r>=h?f=t[a]>>r-h&c:(f=(t[a]&(1<0&&(f|=t[a-1]>>R.DB+r-h)),u=e;0==(1&f);)f>>=1,--u;if((r-=u)<0&&(r+=R.DB,--a),m)o[f].copyTo(n),m=!1;else{for(;u>1;)i.sqrTo(n,d),i.sqrTo(d,n),u-=2;u>0?i.sqrTo(n,d):(l=n,n=d,d=l),i.mulTo(d,o[f],n)}for(;a>=0&&0==(t[a]&1<0&&(s.rShiftTo(r,s),e.rShiftTo(r,e));s.signum()>0;)(i=s.getLowestSetBit())>0&&s.rShiftTo(i,s),(i=e.getLowestSetBit())>0&&e.rShiftTo(i,e),s.compareTo(e)>=0?(s.subTo(e,s),s.rShiftTo(1,s)):(e.subTo(s,e),e.rShiftTo(1,e));return r>0&&e.lShiftTo(r,e),e}modInt(t){if(t<=0)return 0;const s=R.DV%t;let e=this.s<0?t-1:0;if(this.t>0)if(0===s)e=this[0]%t;else for(let i=this.t-1;i>=0;--i)e=(s*e+this[i])%t;return e}modInverse(t){const s=t.isEven();if(this.isEven()&&s||0===t.signum())return R.ZERO;const e=t.clone(),i=this.clone(),r=new R(1),n=new R(0),o=new R(0),h=new R(1);for(;0!==e.signum();){for(;e.isEven();)e.rShiftTo(1,e),s?(r.isEven()&&n.isEven()||(r.addTo(this,r),n.subTo(t,n)),r.rShiftTo(1,r)):n.isEven()||n.subTo(t,n),n.rShiftTo(1,n);for(;i.isEven();)i.rShiftTo(1,i),s?(o.isEven()&&h.isEven()||(o.addTo(this,o),h.subTo(t,h)),o.rShiftTo(1,o)):h.isEven()||h.subTo(t,h),h.rShiftTo(1,h);e.compareTo(i)>=0?(e.subTo(i,e),s&&r.subTo(o,r),n.subTo(h,n)):(i.subTo(e,i),s&&o.subTo(r,o),h.subTo(n,h))}return 0!==i.compareTo(R.ONE)?R.ZERO:h.compareTo(t)>=0?h.subtract(t):h.signum()<0?(h.addTo(t,h),h.signum()<0?h.add(t):h):h}static lowprimes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997];static lplim=(1<<26)/R.lowprimes[R.lowprimes.length-1];isProbablePrime(t){const s=this.abs();let e;if(1===s.t&&s[0]<=R.lowprimes[R.lowprimes.length-1]){for(e=0;e>1)>R.lowprimes.length&&(t=R.lowprimes.length);const r=new R;for(let n=0;n>>16)&&(t=s,e+=16),0!=(s=t>>8)&&(t=s,e+=8),0!=(s=t>>4)&&(t=s,e+=4),0!=(s=t>>2)&&(t=s,e+=2),0!=(s=t>>1)&&(e+=1),e}class P{m;constructor(t){this.m=t}convert(t){return t.s<0||t.compareTo(this.m)>=0?t.mod(this.m):t}revert(t){return t}reduce(t){t.divRemTo(this.m,void 0,t)}mulTo(t,s,e){t.multiplyTo(s,e),this.reduce(e)}sqrTo(t,s){t.squareTo(s),this.reduce(s)}}class N{m;mp;mpl;mph;um;mt2;constructor(t){this.m=t,this.mp=t.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(s,s),s}revert(t){const s=new R;return t.copyTo(s),this.reduce(s),s}reduce(t){for(;t.t<=this.mt2;)t[t.t++]=0;for(let s=0;s>15)*this.mpl&this.um)<<15)&R.DM;for(e=s+this.m.t,t[e]+=this.m.am(0,i,t,s,0,this.m.t);t[e]>=R.DV;)t[e]-=R.DV,t[++e]++}t.clamp(),t.drShiftTo(this.m.t,t),t.compareTo(this.m)>=0&&t.subTo(this.m,t)}sqrTo(t,s){t.squareTo(s),this.reduce(s)}mulTo(t,s,e){t.multiplyTo(s,e),this.reduce(e)}}function K(t){if(0===t)return-1;let s=0;return 0==(65535&t)&&(t>>=16,s+=16),0==(255&t)&&(t>>=8,s+=8),0==(15&t)&&(t>>=4,s+=4),0==(3&t)&&(t>>=2,s+=2),0==(1&t)&&++s,s}function k(t){let s=0;for(;0!==t;)t&=t-1,++s;return s}class V{convert=L;revert=L;reduce=()=>{};mulTo(t,s,e){t.multiplyTo(s,e)}sqrTo(t,s){t.squareTo(s)}}function L(t){return t}class _{r2;q3;mu;m;constructor(t){this.r2=new R,this.q3=new R,R.ONE.dlShiftTo(2*t.t,this.r2),this.mu=this.r2.divide(t),this.m=t}convert(t){if(t.s<0||t.t>2*this.m.t)return t.mod(this.m);if(t.compareTo(this.m)<0)return t;{const s=new R;return t.copyTo(s),this.reduce(s),s}}revert(t){return t}reduce(t){for(t.drShiftTo(this.m.t-1,this.r2),t.t>this.m.t+1&&(t.t=this.m.t+1,t.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);t.compareTo(this.r2)<0;)t.dAddOffset(1,this.m.t+1);for(t.subTo(this.r2,t);t.compareTo(this.m)>=0;)t.subTo(this.m,t)}sqrTo(t,s){t.squareTo(s),this.reduce(s)}mulTo(t,s,e){t.multiplyTo(s,e),this.reduce(e)}}function j(t){t=t.replace(/\r\n/g,"\n");let s="";for(let e=0;e127&&i<2048?(s+=String.fromCharCode(i>>6|192),s+=String.fromCharCode(63&i|128)):(s+=String.fromCharCode(i>>12|224),s+=String.fromCharCode(i>>6&63|128),s+=String.fromCharCode(63&i|128))}return s}const F=process.env.NODEJS?function(t){return i.default.createHash("sha256").update(t,"utf8").digest("hex")}:function(t){function s(t,s){const e=(65535&t)+(65535&s);return(t>>16)+(s>>16)+(e>>16)<<16|65535&e}function e(t,s){return t>>>s|t<<32-s}function i(t,s){return t>>>s}function r(t,s,e){return t&s^~t&e}function n(t,s,e){return t&s^t&e^s&e}function o(t){return e(t,2)^e(t,13)^e(t,22)}function h(t){return e(t,6)^e(t,11)^e(t,25)}function c(t){return e(t,7)^e(t,18)^i(t,3)}return function(t){const s="0123456789abcdef";let e="";for(let i=0;i<4*t.length;i++)e+=s.charAt(t[i>>2]>>8*(3-i%4)+4&15)+s.charAt(t[i>>2]>>8*(3-i%4)&15);return e}(function(t,u){const f=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],l=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],a=new Array(64);let m,d,p,g,b,S,T,w,y,v;t[u>>5]|=128<<24-u%32,t[15+(u+64>>9<<4)]=u;for(let u=0;u>5]|=(255&t.charCodeAt(e/8))<<24-e%32;return s}(t=j(t)),8*t.length))},Z=process.env.NODEJS?function(t){return i.default.createHash("sha1").update(t,"utf8").digest("hex")}:function(t){function s(t,s){return t<>>32-s}function e(t){let s,e="";for(let i=7;i>=0;i--)s=t>>>4*i&15,e+=s.toString(16);return e}let i,r,n;const o=new Array(80);let h,c,u,f,l,a,m=1732584193,d=4023233417,p=2562383102,g=271733878,b=3285377520;const S=(t=j(t)).length,T=[];for(r=0;r>>29),T.push(S<<3&4294967295),i=0;i>>32-s}function e(t,s){const e=2147483648&t,i=2147483648&s,r=1073741824&t,n=1073741824&s,o=(1073741823&t)+(1073741823&s);return r&n?2147483648^o^e^i:r|n?1073741824&o?3221225472^o^e^i:1073741824^o^e^i:o^e^i}function i(t,i,r,n,o,h,c){return t=e(t,e(e(function(t,s,e){return t&s|~t&e}(i,r,n),o),c)),e(s(t,h),i)}function r(t,i,r,n,o,h,c){return t=e(t,e(e(function(t,s,e){return t&e|s&~e}(i,r,n),o),c)),e(s(t,h),i)}function n(t,i,r,n,o,h,c){return t=e(t,e(e(function(t,s,e){return t^s^e}(i,r,n),o),c)),e(s(t,h),i)}function o(t,i,r,n,o,h,c){return t=e(t,e(e(function(t,s,e){return s^(t|~e)}(i,r,n),o),c)),e(s(t,h),i)}function h(t){let s,e,i="",r="";for(e=0;e<=3;e++)s=t>>>8*e&255,r="0"+s.toString(16),i+=r.substr(r.length-2,2);return i}let c,u,f,l,a,m,d,p,g;const b=function(t){let s;const e=t.length,i=e+8,r=16*((i-i%64)/64+1),n=Array(r-1);let o=0,h=0;for(;h>>29,n}(t=j(t));for(m=1732584193,d=4023233417,p=2562383102,g=271733878,c=0;c=0&&s>0;){const r=t.charCodeAt(i--);r<128?e[--s]=r:r>127&&r<2048?(e[--s]=63&r|128,e[--s]=r>>6|192):(e[--s]=63&r|128,e[--s]=r>>6&63|128,e[--s]=r>>12|224)}e[--s]=0;const r=new v,n=[];for(;s>2;){for(n[0]=0;0===n[0];)r.nextBytes(n);e[--s]=n[0]}return e[--s]=2,e[--s]=0,new R(e)}class z{n=new R;e=0;d=new R;p=new R;q=new R;dmp1=new R;dmq1=new R;coeff=new R;setPublic(t,s){if(!t||!s)throw"Invalid RSA public key";this.n=J(t,16),this.e=parseInt(s,16)}doPublic(t){return t.modPowInt(this.e,this.n)}encrypt(t){const s=U(t,this.n.bitLength()+7>>3),e=this.doPublic(s).toString(16);return 0==(1&e.length)?e:"0"+e}setPrivate(t,s,e){if(!(!t&&!s&&t.length>0&&s.length>0))throw"Invalid RSA private key";this.n=J(t,16),this.e=parseInt(s,16),this.d=J(e,16)}setPrivateEx(t,s,e,i,r,n,o,h){if(!(!t&&!s&&t.length>0&&s.length>0))throw new Error("Invalid RSA private key");this.n=J(t,16),this.e=parseInt(s,16),this.d=J(e,16),this.p=J(i,16),this.q=J(r,16),this.dmp1=J(n,16),this.dmq1=J(o,16),this.coeff=J(h,16)}generate(t,s){const e=new p,i=t>>1;this.e=parseInt(s,16);const r=new R(s,16);for(;;){for(;this.p=new R(t-i,1,e),0!==this.p.subtract(R.ONE).gcd(r).compareTo(R.ONE)||!this.p.isProbablePrime(10););for(;this.q=new R(i,1,e),0!==this.q.subtract(R.ONE).gcd(r).compareTo(R.ONE)||!this.q.isProbablePrime(10););if(this.p.compareTo(this.q)<=0){const t=this.p;this.p=this.q,this.q=t}const s=this.p.subtract(R.ONE),n=this.q.subtract(R.ONE),o=s.multiply(n);if(0===o.gcd(r).compareTo(R.ONE)){this.n=this.p.multiply(this.q),this.d=r.modInverse(o),this.dmp1=this.d.mod(s),this.dmq1=this.d.mod(n),this.coeff=this.q.modInverse(this.p);break}}}doPrivate(t){if(!this.p||!this.q)return t.modPow(this.d,this.n);let s=t.mod(this.p).modPow(this.dmp1,this.p);const e=t.mod(this.q).modPow(this.dmq1,this.q);for(;s.compareTo(e)<0;)s=s.add(this.p);return s.subtract(e).multiply(this.coeff).mod(this.p).multiply(this.q).add(e)}decrypt(t){const s=J(t,16),e=this.doPrivate(s);return e instanceof R?X(e,this.n.bitLength()+7>>3):null}signString=Y;signStringWithSHA1=$;signStringWithSHA256=tt;verifyHexSignatureForMessage=it;verifyString=rt;toJSON(){return JSON.stringify({coeff:this.coeff.toString(16),d:this.d.toString(16),dmp1:this.dmp1.toString(16),dmq1:this.dmq1.toString(16),e:this.e.toString(16),n:this.n.toString(16),p:this.p.toString(16),q:this.q.toString(16)})}static parse(t){const s="string"==typeof t?JSON.parse(t):t;if(!s)return null;const e=new z;return e.setPrivateEx(s.n,s.e,s.d,s.p,s.q,s.dmp1,s.dmq1,s.coeff),e}}function X(t,s){const e=t.toByteArray();let i=0;for(;i=e.length)return null;let r="";for(;++i191&&t<224?(r+=String.fromCharCode((31&t)<<6|63&e[i+1]),++i):(r+=String.fromCharCode((15&t)<<12|(63&e[i+1])<<6|63&e[i+2]),i+=2)}return r}const W={sha1:"3021300906052b0e03021a05000414",sha256:"3031300d060960864801650304020105000420"},G={sha1:Z,sha256:F};function Q(t,s,e){const i=s/4,r=(0,G[e])(t),n="0001",o="00"+W[e]+r;let h="";const c=i-n.length-o.length;for(let t=0;t>2&63),i=(3&s)<<4):1===n?(r+=nt.charAt(i|s>>4&15),i=(15&s)<<2):2===n&&(r+=nt.charAt(i|s>>6&3),r+=nt.charAt(63&s)),n+=1,3===n&&(n=0);return n>0&&(r+=nt.charAt(i),r+="="),1===n&&(r+="="),r}static b64to256(t){let s,e,i="",r=0,n=0;const o=t.length;for(e=0;e=0&&(r&&(i+=String.fromCharCode(n|s>>6-r&255)),r=r+2&7,n=s<>6)+nt.charAt(63&e);for(s+1===t.length?(e=parseInt(t.substring(s,s+1),16),i+=nt.charAt(e<<2)):s+2===t.length&&(e=parseInt(t.substring(s,s+2),16),i+=nt.charAt(e>>2)+nt.charAt((3&e)<<4));(3&i.length)>0;)i+="=";return i}static b64to16(t){let s,e="",i=0,r=0;for(s=0;s>2),r=3&n,i=1):1===i?(e+=O(r<<2|n>>4),r=15&n,i=2):2===i?(e+=O(r),e+=O(n>>2),r=3&n,i=3):(e+=O(r<<2|n>>4),e+=O(15&n),i=0))}return 1===i&&(e+=O(r<<2)),e}static string2bytes(t){const s=[];for(let e=0;e1?this._confirm(n):{status:"success",plaintext:n[0],signature:"unsigned"}}static sign(t,s){return this.b16to64(s.signString(t,"sha256"))}static verify(t){const s=this._confirm(t);return"success"===s.status&&"verified"===s.signature}static _confirm(t){if(3===t.length){const s=this.publicKeyFromString(t[1]),e=this.b64to16(t[2]);return s.verifyString(t[0],e)?{status:"success",plaintext:t[0],signature:"verified",publicKeyString:this.publicKeyString(s)}:{status:"success",plaintext:t[0],signature:"forged",publicKeyString:this.publicKeyString(s)}}return{status:"failure"}}},t.int2char=O,t.linebrk=function(t,s){let e="",i=0;for(;i+s{\n // eslint-disable-next-line prettier/prettier\n Sbox: [\n 99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118,\n 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114,\n 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49,\n 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9,\n 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209,\n 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170,\n 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143,\n 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236,\n 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34,\n 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6,\n 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213,\n 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166,\n 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3,\n 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217,\n 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230,\n 66, 104, 65, 153, 45, 15, 176, 84, 187, 22,\n ] as ByteArray,\n\n ShiftRowTab: [\n 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11,\n ] as ByteArray,\n\n Sbox_Inv: new Array(256),\n ShiftRowTab_Inv: new Array(16),\n xtime: new Array(256),\n\n Init() {\n for (let i = 0; i < 256; i++) this.Sbox_Inv[this.Sbox[i]] = i\n\n for (let i = 0; i < 16; i++) this.ShiftRowTab_Inv[this.ShiftRowTab[i]] = i\n\n for (let i = 0; i < 128; i++) {\n this.xtime[i] = i << 1\n this.xtime[128 + i] = (i << 1) ^ 0x1b\n }\n },\n\n Done() {\n this.Sbox_Inv.length = 0\n this.Sbox_Inv.length = 256\n this.ShiftRowTab_Inv.length = 0\n this.ShiftRowTab_Inv.length = 16\n this.xtime.length = 0\n this.xtime.length = 256\n },\n\n ExpandKey(key: AESKey) {\n const kl = key.length\n let ks,\n Rcon = 1\n switch (kl) {\n case 16:\n ks = 16 * (10 + 1)\n break\n case 24:\n ks = 16 * (12 + 1)\n break\n case 32:\n ks = 16 * (14 + 1)\n break\n default:\n throw 'my.ExpandKey: Only key lengths of 16, 24 or 32 bytes allowed!'\n }\n for (let i = kl; i < ks; i += 4) {\n let temp = key.slice(i - 4, i)\n if (i % kl === 0) {\n temp = [\n aes.Sbox[temp[1]] ^ Rcon,\n aes.Sbox[temp[2]],\n aes.Sbox[temp[3]],\n aes.Sbox[temp[0]],\n ]\n if ((Rcon <<= 1) >= 256) Rcon ^= 0x11b\n } else if (kl > 24 && i % kl === 16)\n temp = [\n aes.Sbox[temp[0]],\n aes.Sbox[temp[1]],\n aes.Sbox[temp[2]],\n aes.Sbox[temp[3]],\n ]\n for (let j = 0; j < 4; j++) key[i + j] = key[i + j - kl] ^ temp[j]\n }\n },\n\n Encrypt(block: ByteArray, key: AESKey) {\n const l = key.length\n aes.AddRoundKey(block, key.slice(0, 16))\n let i\n for (i = 16; i < l - 16; i += 16) {\n aes.SubBytes(block, aes.Sbox)\n aes.ShiftRows(block, aes.ShiftRowTab)\n aes.MixColumns(block)\n aes.AddRoundKey(block, key.slice(i, i + 16))\n }\n aes.SubBytes(block, aes.Sbox)\n aes.ShiftRows(block, aes.ShiftRowTab)\n aes.AddRoundKey(block, key.slice(i, l))\n },\n\n Decrypt(block: ByteArray, key: AESKey) {\n const l = key.length\n aes.AddRoundKey(block, key.slice(l - 16, l))\n aes.ShiftRows(block, aes.ShiftRowTab_Inv)\n aes.SubBytes(block, aes.Sbox_Inv)\n for (let i = l - 32; i >= 16; i -= 16) {\n aes.AddRoundKey(block, key.slice(i, i + 16))\n aes.MixColumns_Inv(block)\n aes.ShiftRows(block, aes.ShiftRowTab_Inv)\n aes.SubBytes(block, aes.Sbox_Inv)\n }\n aes.AddRoundKey(block, key.slice(0, 16))\n },\n\n SubBytes(state: ByteArray, sbox: ByteArray) {\n for (let i = 0; i < 16; i++) state[i] = sbox[state[i]]\n },\n\n AddRoundKey(state: ByteArray, rkey: ByteArray) {\n for (let i = 0; i < 16; i++) state[i] ^= rkey[i]\n },\n\n ShiftRows(state: ByteArray, shifttab: number[]) {\n const h = new Array().concat(state)\n for (let i = 0; i < 16; i++) state[i] = h[shifttab[i]]\n },\n\n MixColumns(state: ByteArray) {\n for (let i = 0; i < 16; i += 4) {\n const s0 = state[i + 0],\n s1 = state[i + 1]\n const s2 = state[i + 2],\n s3 = state[i + 3]\n const h = s0 ^ s1 ^ s2 ^ s3\n state[i + 0] ^= h ^ aes.xtime[s0 ^ s1]\n state[i + 1] ^= h ^ aes.xtime[s1 ^ s2]\n state[i + 2] ^= h ^ aes.xtime[s2 ^ s3]\n state[i + 3] ^= h ^ aes.xtime[s3 ^ s0]\n }\n },\n\n MixColumns_Inv(state: ByteArray) {\n for (let i = 0; i < 16; i += 4) {\n const s0 = state[i + 0],\n s1 = state[i + 1]\n const s2 = state[i + 2],\n s3 = state[i + 3]\n const h = s0 ^ s1 ^ s2 ^ s3\n const xh = aes.xtime[h]\n const h1 = aes.xtime[aes.xtime[xh ^ s0 ^ s2]] ^ h\n const h2 = aes.xtime[aes.xtime[xh ^ s1 ^ s3]] ^ h\n state[i + 0] ^= h1 ^ aes.xtime[s0 ^ s1]\n state[i + 1] ^= h2 ^ aes.xtime[s1 ^ s2]\n state[i + 2] ^= h1 ^ aes.xtime[s2 ^ s3]\n state[i + 3] ^= h2 ^ aes.xtime[s3 ^ s0]\n }\n },\n}\n","// seedrandom.js version 2.0.\n// Author: David Bau 4/2/2011\n//\n// Defines a method math.seedrandom() that, when called, substitutes\n// an explicitly seeded RC4-based algorithm for math.random(). Also\n// supports automatic seeding from local or network sources of entropy.\n//\n// Usage:\n//\n// \n//\n// Math.seedrandom('yipee'); Sets math.random to a function that is\n// initialized using the given explicit seed.\n//\n// Math.seedrandom(); Sets math.random to a function that is\n// seeded using the current time, dom state,\n// and other accumulated local entropy.\n// The generated seed string is returned.\n//\n// Math.seedrandom('yowza', true);\n// Seeds using the given explicit seed mixed\n// together with accumulated entropy.\n//\n// \n// Seeds using physical random bits downloaded\n// from random.org.\n//\n// Seeds using urandom bits from call.jsonlib.com,\n// which is faster than random.org.\n//\n// Examples:\n//\n// math.seedrandom(\"hello\"); // Use \"hello\" as the seed.\n// document.write(math.random()); // Always 0.5463663768140734\n// document.write(math.random()); // Always 0.43973793770592234\n// let rng1 = math.random; // Remember the current prng.\n//\n// let autoseed = math.seedrandom(); // New prng with an automatic seed.\n// document.write(math.random()); // Pretty much unpredictable.\n//\n// math.random = rng1; // Continue \"hello\" prng sequence.\n// document.write(math.random()); // Always 0.554769432473455\n//\n// Math.seedrandom(autoseed); // Restart at the previous seed.\n// document.write(math.random()); // Repeat the 'unpredictable' value.\n//\n// Notes:\n//\n// Each time seedrandom('arg') is called, entropy from the passed seed\n// is accumulated in a pool to help generate future seeds for the\n// zero-argument form of Math.seedrandom, so entropy can be injected over\n// time by calling seedrandom with explicit data repeatedly.\n//\n// On speed - This javascript implementation of math.random() is about\n// 3-10x slower than the built-in Math.random() because it is not native\n// code, but this is typically fast enough anyway. Seeding is more expensive,\n// especially if you use auto-seeding. Some details (timings on Chrome 4):\n//\n// Our math.random() - avg less than 0.002 milliseconds per call\n// seedrandom('explicit') - avg less than 0.5 milliseconds per call\n// seedrandom('explicit', true) - avg less than 2 milliseconds per call\n// seedrandom() - avg about 38 milliseconds per call\n//\n// LICENSE (BSD):\n//\n// Copyright 2010 David Bau, all rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n//\n// 3. Neither the name of this module nor the names of its contributors may\n// be used to endorse or promote products derived from this software\n// without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n\nimport { ByteArray } from './type'\n\nconst pool: number[] = [] // pool: entropy pool starts empty\nconst width = 256 // width: each RC4 output is 0 <= x < 256\nconst chunks = 6 // chunks: at least six RC4 outputs for each double\n//\n// The following constants are related to IEEE 754 limits.\n//\nconst significance = Math.pow(2, 52) // significance: there are 52 significant digits in a double\nconst overflow = significance * 2\nconst startdenom = Math.pow(width, chunks)\n\nexport const math = {\n //\n // seedrandom()\n // This is the seedrandom function described above.\n //\n seedrandom(seed: string, use_entropy = false): string {\n const key: number[] = []\n\n // Flatten the seed string or build one from local entropy if needed.\n seed = mixkey(\n flatten(\n use_entropy\n ? [seed, pool]\n : arguments.length\n ? seed\n : [new Date().getTime(), pool],\n 3,\n ),\n key,\n )\n\n // Use the seed to initialize an ARC4 generator.\n const arc4 = new ARC4(key)\n\n // Mix the randomness into accumulated entropy.\n mixkey(arc4.S, pool)\n\n // Override math.random\n // This function returns a random double in [0, 1) that contains\n // randomness in every bit of the mantissa of the IEEE 754 value.\n math.random = function (): number {\n // Closure to return a random double:\n let n = arc4.g(chunks) // Start with a numerator n < 2 ^ 48\n let d = startdenom // and denominator d = 2 ^ 48.\n let x = 0 // and no 'extra last byte'.\n while (n < significance) {\n // Fill up all significant digits by\n n = (n + x) * width // shifting numerator and\n d *= width // denominator and generating a\n x = arc4.g(1) // new least-significant-byte.\n }\n while (n >= overflow) {\n // To avoid rounding up, before adding\n n /= 2 // last byte, shift everything\n d /= 2 // right using integer math until\n x >>>= 1 // we have exactly the desired bits.\n }\n return (n + x) / d // Form the number within [0, 1).\n }\n\n // Return the seed that was used\n return seed\n },\n\n random: function (): number {\n return Math.random()\n },\n}\n\n//\n// ARC4\n//\n// An ARC4 implementation. The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4. Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\n/** @constructor */\nclass ARC4 {\n i = 0\n j = 0\n S: number[] = []\n c: number[] = []\n\n constructor(key: number[]) {\n let t,\n u,\n keylen = key.length\n let i = 0,\n j = 0\n\n // The empty key [] is treated as [0].\n if (!keylen) {\n key = [keylen++]\n }\n\n // Set up S using the standard key scheduling algorithm.\n while (i < width) {\n this.S[i] = i++\n }\n for (i = 0; i < width; i++) {\n t = this.S[i]\n j = lowbits(j + t + key[i % keylen])\n u = this.S[j]\n this.S[i] = u\n this.S[j] = t\n }\n\n // For robust unpredictability discard an initial batch of values.\n // See http://www.rsa.com/rsalabs/node.asp?id=2009\n this.g(width)\n }\n\n // The \"g\" method returns the next (count) outputs as one number.\n g(count: number): number {\n const s = this.S\n let i = lowbits(this.i + 1)\n let t = s[i]\n let j = lowbits(this.j + t)\n let u = s[j]\n s[i] = u\n s[j] = t\n let r = s[lowbits(t + u)]\n while (--count) {\n i = lowbits(i + 1)\n t = s[i]\n j = lowbits(j + t)\n u = s[j]\n s[i] = u\n s[j] = t\n r = r * width + s[lowbits(t + u)]\n }\n this.i = i\n this.j = j\n return r\n }\n}\n\ntype NestedStrArray = (string | NestedStrArray)[]\n\n//\n// flatten()\n// Converts an object tree to nested arrays of strings.\n//\n/** @param {Object=} result\n * @param {string=} prop\n * @param {string=} typ */\nfunction flatten(obj: unknown, depth: number): NestedStrArray | string {\n const result: NestedStrArray = []\n const typ = typeof obj\n if (depth && typ === 'object') {\n for (const prop in obj as Record) {\n if (prop.indexOf('S') < 5) {\n // Avoid FF3 bug (local/sessionStorage)\n try {\n result.push(\n flatten((obj as Record)[prop], depth - 1),\n )\n } catch (e) {\n console.error(e)\n }\n }\n }\n }\n return result.length ? result : obj + (typ !== 'string' ? '\\0' : '')\n}\n\n//\n// mixkey()\n// Mixes a string seed into a key that is an array of integers, and\n// returns a shortened string seed that is equivalent to the result key.\n//\n/** @param {number=} smear\n * @param {number=} j */\nfunction mixkey(seed: unknown, key: number[]): string {\n const seedStr = seed + '' // Ensure the seed is a string\n let smear = 0\n for (let i = 0; i < seedStr.length; i++) {\n key[lowbits(i)] = lowbits(\n (smear ^= key[lowbits(i)] * 19) + seedStr.charCodeAt(i),\n )\n }\n let mixed = ''\n key.forEach((v) => (mixed += String.fromCharCode(v)))\n return mixed\n}\n\n//\n// lowbits()\n// A quick \"n mod width\" for width a power of 2.\n//\nfunction lowbits(n: number): number {\n return n & (width - 1)\n}\n\n//\n// When seedrandom.js is loaded, we immediately mix a few bits\n// from the built-in RNG into the entropy pool. Because we do\n// not want to intefere with determinstic PRNG state later,\n// seedrandom will not call math.random on its own again after\n// initialization.\n//\nmixkey(Math.random(), pool)\n\n// This is not really a random number generator object, and two SeededRandom\n// objects will conflict with one another, but it's good enough for generating\n// the rsa key.\nexport class SeededRandom {\n nextBytes(ba: number[]): void {\n for (let i = 0; i < ba.length; i++) {\n ba[i] = Math.floor(math.random() * 256)\n }\n }\n}\n\n// prng4.js - uses Arcfour as a PRNG\nclass Arcfour {\n i = 0\n j = 0\n S: number[] = []\n\n // Initialize arcfour context from key, an array of ints, each from [0..255]\n init(key: number[]): void {\n let i, j, t\n for (i = 0; i < 256; ++i) this.S[i] = i\n j = 0\n for (i = 0; i < 256; ++i) {\n j = (j + this.S[i] + key[i % key.length]) & 255\n t = this.S[i]\n this.S[i] = this.S[j]\n this.S[j] = t\n }\n this.i = 0\n this.j = 0\n }\n\n next(): number {\n this.i = (this.i + 1) & 255\n this.j = (this.j + this.S[this.i]) & 255\n const t = this.S[this.i]\n this.S[this.i] = this.S[this.j]\n this.S[this.j] = t\n return this.S[(t + this.S[this.i]) & 255]\n }\n}\n\n// Plug in your RNG constructor here\nfunction prng_newstate(): Arcfour {\n return new Arcfour()\n}\n\n// Pool size must be a multiple of 4 and greater than 32.\n// An array of bytes the size of the pool will be passed to init()\nconst rng_psize = 256\n\n// Random number generator - requires a PRNG backend, e.g. prng4.js\n\n// For best results, put code like\n// \n// in your main HTML document.\n\nlet rng_state: Arcfour\nlet rng_pool: number[] = []\nlet rng_pptr: number\n\n// Mix in a 32-bit integer into the pool\nfunction rng_seed_int(x: number): void {\n rng_pool[rng_pptr++] ^= x & 255\n rng_pool[rng_pptr++] ^= (x >> 8) & 255\n rng_pool[rng_pptr++] ^= (x >> 16) & 255\n rng_pool[rng_pptr++] ^= (x >> 24) & 255\n if (rng_pptr >= rng_psize) rng_pptr -= rng_psize\n}\n\n// Mix in the current time (w/milliseconds) into the pool\nfunction rng_seed_time(): void {\n rng_seed_int(new Date().getTime())\n}\n\n// Initialize the pool with junk if needed.\nif (!rng_pool) {\n rng_pool = []\n rng_pptr = 0\n let t\n while (rng_pptr < rng_psize) {\n // extract some randomness from Math.random()\n t = Math.floor(65536 * Math.random())\n rng_pool[rng_pptr++] = t >>> 8\n rng_pool[rng_pptr++] = t & 255\n }\n rng_pptr = 0\n rng_seed_time()\n //rng_seed_int(window.screenX);\n //rng_seed_int(window.screenY);\n}\n\nfunction rng_get_byte(): number {\n if (!rng_state) {\n rng_seed_time()\n rng_state = prng_newstate()\n rng_state.init(rng_pool)\n for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)\n rng_pool[rng_pptr] = 0\n rng_pptr = 0\n //rng_pool = null;\n }\n // TODO: allow reseeding after first request\n return rng_state.next()\n}\n\nexport class SecureRandom {\n nextBytes(ba: ByteArray): void {\n let i\n for (i = 0; i < ba.length; ++i) ba[i] = rng_get_byte()\n }\n}\n","// Copyright (c) 2005 Tom Wu\n// All Rights Reserved.\n// See \"LICENSE\" for details.\n// Basic JavaScript BN library - subset useful for RSA encryption.\n\n// (public) Constructor\n\nimport { math, SeededRandom } from './random'\nimport { ByteArray } from './type'\n\nexport type Op = (x: number, y: number) => number\nexport const op_and: Op = (x, y) => x & y\nexport const op_or: Op = (x, y) => x | y\nexport const op_xor: Op = (x, y) => x ^ y\nexport const op_andnot: Op = (x, y) => x & ~y\n\nconst dbits = 30\nconst BI_FP = 52\n\nexport class BigInteger {\n static DB = dbits\n static DM = (1 << dbits) - 1\n static DV = 1 << dbits\n static FV = Math.pow(2, BI_FP)\n static F1 = BI_FP - dbits\n static F2 = 2 * dbits - BI_FP\n // \"constants\"\n static ZERO = new BigInteger(0)\n static ONE = new BigInteger(1)\n\n // FIXME: ;\n s = 0\n t = 0;\n [k: number]: number\n\n constructor(\n a?: number | string | number[],\n b?: number | SeededRandom,\n c?: number | SeededRandom,\n ) {\n if (a) {\n if ('number' === typeof a) {\n if (b) {\n this.fromNumber(a, b, c as number)\n } else {\n // return bigint initialized to value\n this.fromInt(a)\n }\n } else {\n this.fromString(a, (b as number) || 256)\n }\n }\n }\n\n // am avoids a big mult-and-extract completely.\n // Max digit bits should be <= 30 because we do bitwise ops\n // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)\n am(\n i: number,\n x: number,\n w: BigInteger,\n j: number,\n c: number,\n n: number,\n ): number {\n const xl = x & 0x7fff,\n xh = x >> 15\n while (--n >= 0) {\n let l = this[i] & 0x7fff\n const h = this[i++] >> 15\n const m = xh * l + h * xl\n l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff)\n c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30)\n w[j++] = l & 0x3fffffff\n }\n return c\n }\n\n // copy this to r\n copyTo(r: BigInteger): void {\n for (let i = this.t - 1; i >= 0; --i) r[i] = this[i]\n r.t = this.t\n r.s = this.s\n }\n\n // set from integer value x, -DV <= x < DV\n fromInt(x: number): void {\n this.t = 1\n this.s = x < 0 ? -1 : 0\n if (x > 0) this[0] = x\n else if (x < -1) this[0] = x + BigInteger.DV\n else this.t = 0\n }\n\n // set from string and radix\n fromString(s: string | number[], b: number): void {\n let k\n if (b === 16) k = 4\n else if (b === 8) k = 3\n else if (b === 256) k = 8\n // byte array\n else if (b === 2) k = 1\n else if (b === 32) k = 5\n else if (b === 4) k = 2\n else {\n this.fromRadix(s as string, b)\n return\n }\n this.t = 0\n this.s = 0\n let i = s.length,\n mi = false,\n sh = 0\n while (--i >= 0) {\n const x = k === 8 ? (s[i] as number & 0xff) : intAt(s as string, i)\n if (x < 0) {\n if ((s as string).charAt(i) === '-') mi = true\n continue\n }\n mi = false\n if (sh === 0) this[this.t++] = x\n else if (sh + k > BigInteger.DB) {\n this[this.t - 1] |= (x & ((1 << (BigInteger.DB - sh)) - 1)) << sh\n this[this.t++] = x >> (BigInteger.DB - sh)\n } else this[this.t - 1] |= x << sh\n sh += k\n if (sh >= BigInteger.DB) sh -= BigInteger.DB\n }\n if (k === 8 && ((s[0] as number) & 0x80) !== 0) {\n this.s = -1\n if (sh > 0) this[this.t - 1] |= ((1 << (BigInteger.DB - sh)) - 1) << sh\n }\n this.clamp()\n if (mi) BigInteger.ZERO.subTo(this, this)\n }\n\n // clamp off excess high words\n clamp(): void {\n const c = this.s & BigInteger.DM\n while (this.t > 0 && this[this.t - 1] === c) --this.t\n }\n\n // return string representation in given radix (default to 16)\n toString(b = 16): string {\n if (this.s < 0) return '-' + this.negate().toString(b)\n let k\n if (b === 16) k = 4\n else if (b === 8) k = 3\n else if (b === 2) k = 1\n else if (b === 32) k = 5\n else if (b === 64) k = 6\n else if (b === 4) k = 2\n else return this.toRadix(b)\n const km = (1 << k) - 1\n let d,\n m = false,\n r = '',\n i = this.t\n let p = BigInteger.DB - ((i * BigInteger.DB) % k)\n if (i-- > 0) {\n if (p < BigInteger.DB && (d = this[i] >> p) > 0) {\n m = true\n r = int2char(d)\n }\n while (i >= 0) {\n if (p < k) {\n d = (this[i] & ((1 << p) - 1)) << (k - p)\n d |= this[--i] >> (p += BigInteger.DB - k)\n } else {\n d = (this[i] >> (p -= k)) & km\n if (p <= 0) {\n p += BigInteger.DB\n --i\n }\n }\n if (d > 0) m = true\n if (m) r += int2char(d)\n }\n }\n return m ? r : '0'\n }\n\n // -this\n negate(): BigInteger {\n const r = new BigInteger()\n BigInteger.ZERO.subTo(this, r)\n return r\n }\n\n // |this|\n abs(): BigInteger {\n return this.s < 0 ? this.negate() : this\n }\n\n // return + if this > a, - if this < a, 0 if equal\n compareTo(a: BigInteger): number {\n let r = this.s - a.s\n if (r !== 0) return r\n let i = this.t\n r = i - a.t\n if (r !== 0) return r\n while (--i >= 0) if ((r = this[i] - a[i]) !== 0) return r\n return 0\n }\n\n // return the number of bits in \"this\"\n bitLength(): number {\n if (this.t <= 0) return 0\n return (\n BigInteger.DB * (this.t - 1) +\n nbits(this[this.t - 1] ^ (this.s & BigInteger.DM))\n )\n }\n\n // r = this << n*DB\n dlShiftTo(n: number, r: BigInteger): void {\n let i\n for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]\n for (i = n - 1; i >= 0; --i) r[i] = 0\n r.t = this.t + n\n r.s = this.s\n }\n\n // r = this >> n*DB\n drShiftTo(n: number, r: BigInteger): void {\n for (let i = n; i < this.t; ++i) r[i - n] = this[i]\n r.t = Math.max(this.t - n, 0)\n r.s = this.s\n }\n\n // r = this << n\n lShiftTo(n: number, r: BigInteger): void {\n const bs = n % BigInteger.DB\n const cbs = BigInteger.DB - bs\n const bm = (1 << cbs) - 1\n const ds = Math.floor(n / BigInteger.DB)\n let c = (this.s << bs) & BigInteger.DM,\n i\n for (i = this.t - 1; i >= 0; --i) {\n r[i + ds + 1] = (this[i] >> cbs) | c\n c = (this[i] & bm) << bs\n }\n for (i = ds - 1; i >= 0; --i) r[i] = 0\n r[ds] = c\n r.t = this.t + ds + 1\n r.s = this.s\n r.clamp()\n }\n\n // r = this >> n\n rShiftTo(n: number, r: BigInteger): void {\n r.s = this.s\n const ds = Math.floor(n / BigInteger.DB)\n if (ds >= this.t) {\n r.t = 0\n return\n }\n const bs = n % BigInteger.DB\n const cbs = BigInteger.DB - bs\n const bm = (1 << bs) - 1\n r[0] = this[ds] >> bs\n for (let i = ds + 1; i < this.t; ++i) {\n r[i - ds - 1] |= (this[i] & bm) << cbs\n r[i - ds] = this[i] >> bs\n }\n if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs\n r.t = this.t - ds\n r.clamp()\n }\n\n // r = this - a\n subTo(a: BigInteger, r: BigInteger): void {\n const m = Math.min(a.t, this.t)\n let i = 0,\n c = 0\n while (i < m) {\n c += this[i] - a[i]\n r[i++] = c & BigInteger.DM\n c >>= BigInteger.DB\n }\n if (a.t < this.t) {\n c -= a.s\n while (i < this.t) {\n c += this[i]\n r[i++] = c & BigInteger.DM\n c >>= BigInteger.DB\n }\n c += this.s\n } else {\n c += this.s\n while (i < a.t) {\n c -= a[i]\n r[i++] = c & BigInteger.DM\n c >>= BigInteger.DB\n }\n c -= a.s\n }\n r.s = c < 0 ? -1 : 0\n if (c < -1) r[i++] = BigInteger.DV + c\n else if (c > 0) r[i++] = c\n r.t = i\n r.clamp()\n }\n\n // r = this * a, r !== this,a (HAC 14.12)\n // \"this\" should be the larger one if appropriate.\n multiplyTo(a: BigInteger, r: BigInteger): void {\n const x = this.abs(),\n y = a.abs()\n let i = x.t\n r.t = i + y.t\n while (--i >= 0) r[i] = 0\n for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t)\n r.s = 0\n r.clamp()\n if (this.s !== a.s) BigInteger.ZERO.subTo(r, r)\n }\n\n // r = this^2, r !== this (HAC 14.16)\n squareTo(r: BigInteger): void {\n const x = this.abs()\n let i = (r.t = 2 * x.t)\n while (--i >= 0) r[i] = 0\n for (i = 0; i < x.t - 1; ++i) {\n const c = x.am(i, x[i], r, 2 * i, 0, 1)\n if (\n (r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >=\n BigInteger.DV\n ) {\n r[i + x.t] -= BigInteger.DV\n r[i + x.t + 1] = 1\n }\n }\n if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1)\n r.s = 0\n r.clamp()\n }\n\n // divide this by m, quotient and remainder to q, r (HAC 14.20)\n // r !== q, this !== m. q or r may be null.\n divRemTo(m: BigInteger, q?: BigInteger, r?: BigInteger): void {\n const pm = m.abs()\n if (pm.t <= 0) return\n const pt = this.abs()\n if (pt.t < pm.t) {\n if (q) q.fromInt(0)\n if (r) this.copyTo(r)\n return\n }\n if (!r) r = new BigInteger()\n const y = new BigInteger(),\n ts = this.s,\n ms = m.s\n const nsh = BigInteger.DB - nbits(pm[pm.t - 1]) // normalize modulus\n if (nsh > 0) {\n pm.lShiftTo(nsh, y)\n pt.lShiftTo(nsh, r)\n } else {\n pm.copyTo(y)\n pt.copyTo(r)\n }\n const ys = y.t\n const y0 = y[ys - 1]\n if (y0 === 0) return\n const yt =\n y0 * (1 << BigInteger.F1) + (ys > 1 ? y[ys - 2] >> BigInteger.F2 : 0)\n const d1 = BigInteger.FV / yt,\n d2 = (1 << BigInteger.F1) / yt,\n e = 1 << BigInteger.F2,\n t = q || new BigInteger()\n let i = r.t,\n j = i - ys\n y.dlShiftTo(j, t)\n if (r.compareTo(t) >= 0) {\n r[r.t++] = 1\n r.subTo(t, r)\n }\n BigInteger.ONE.dlShiftTo(ys, t)\n t.subTo(y, y) // \"negative\" y so we can replace sub with am later\n while (y.t < ys) y[y.t++] = 0\n while (--j >= 0) {\n // Estimate quotient digit\n let qd =\n r[--i] === y0\n ? BigInteger.DM\n : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2)\n if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) {\n // Try it out\n y.dlShiftTo(j, t)\n r.subTo(t, r)\n while (r[i] < --qd) r.subTo(t, r)\n }\n }\n if (q) {\n r.drShiftTo(ys, q)\n if (ts !== ms) BigInteger.ZERO.subTo(q, q)\n }\n r.t = ys\n r.clamp()\n if (nsh > 0) r.rShiftTo(nsh, r) // Denormalize remainder\n if (ts < 0) BigInteger.ZERO.subTo(r, r)\n }\n\n // this mod a\n mod(a: BigInteger): BigInteger {\n const r = new BigInteger()\n this.abs().divRemTo(a, undefined, r)\n if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r)\n return r\n }\n\n // return \"-1/this % 2^DB\"; useful for Mont. reduction\n // justification:\n // xy === 1 (mod m)\n // xy = 1+km\n // xy(2-xy) = (1+km)(1-km)\n // x[y(2-xy)] = 1-k^2m^2\n // x[y(2-xy)] === 1 (mod m^2)\n // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2\n // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.\n // JS multiply \"overflows\" differently from C/C++, so care is needed here.\n invDigit(): number {\n if (this.t < 1) return 0\n const x = this[0]\n if ((x & 1) === 0) return 0\n let y = x & 3 // y === 1/x mod 2^2\n y = (y * (2 - (x & 0xf) * y)) & 0xf // y === 1/x mod 2^4\n y = (y * (2 - (x & 0xff) * y)) & 0xff // y === 1/x mod 2^8\n y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff // y === 1/x mod 2^16\n // last step - calculate inverse mod DV directly;\n // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints\n y = (y * (2 - ((x * y) % BigInteger.DV))) % BigInteger.DV // y === 1/x mod 2^dbits\n // we really want the negative inverse, and -DV < y < DV\n return y > 0 ? BigInteger.DV - y : -y\n }\n\n // true iff this is even\n isEven(): boolean {\n return (this.t > 0 ? this[0] & 1 : this.s) === 0\n }\n\n // this^e, e < 2^32, doing sqr and mul with \"r\" (HAC 14.79)\n exp(e: number, z: Reducer): BigInteger {\n if (e > 0xffffffff || e < 1) return BigInteger.ONE\n const g = z.convert(this)\n let r = new BigInteger(),\n r2 = new BigInteger(),\n i = nbits(e) - 1\n g.copyTo(r)\n while (--i >= 0) {\n z.sqrTo(r, r2)\n if ((e & (1 << i)) > 0) z.mulTo(r2, g, r)\n else {\n const t = r\n r = r2\n r2 = t\n }\n }\n return z.revert(r)\n }\n\n // this^e % m, 0 <= e < 2^32\n modPowInt(e: number, m: BigInteger): BigInteger {\n let z\n if (e < 256 || m.isEven()) z = new Classic(m)\n else z = new Montgomery(m)\n return this.exp(e, z)\n }\n\n clone(): BigInteger {\n const r = new BigInteger()\n this.copyTo(r)\n return r\n }\n\n // return value as integer\n intValue(): number {\n if (this.s < 0) {\n if (this.t === 1) return this[0] - BigInteger.DV\n else if (this.t === 0) return -1\n } else if (this.t === 1) return this[0]\n else if (this.t === 0) return 0\n // assumes 16 < DB < 32\n return (\n ((this[1] & ((1 << (32 - BigInteger.DB)) - 1)) << BigInteger.DB) | this[0]\n )\n }\n\n // return value as byte\n byteValue(): number {\n return this.t === 0 ? this.s : (this[0] << 24) >> 24\n }\n\n // return value as short (assumes DB>=16)\n shortValue(): number {\n return this.t === 0 ? this.s : (this[0] << 16) >> 16\n }\n\n // return x s.t. r^x < DV\n chunkSize(r: number): number {\n return Math.floor((Math.LN2 * BigInteger.DB) / Math.log(r))\n }\n\n // 0 if this === 0, 1 if this > 0, -1 if this < 0\n signum(): -1 | 0 | 1 {\n if (this.s < 0) return -1\n else if (this.t <= 0 || (this.t === 1 && this[0] <= 0)) return 0\n else return 1\n }\n\n // convert to radix string\n toRadix(b: number): string {\n if (!b) b = 10\n if (this.signum() === 0 || b < 2 || b > 36) return '0'\n const cs = this.chunkSize(b)\n const a = Math.pow(b, cs)\n const d = new BigInteger(a),\n y = new BigInteger(),\n z = new BigInteger()\n let r = ''\n this.divRemTo(d, y, z)\n while (y.signum() > 0) {\n r = (a + z.intValue()).toString(b).substr(1) + r\n y.divRemTo(d, y, z)\n }\n return z.intValue().toString(b) + r\n }\n\n // convert from radix string\n fromRadix(s: string, b: number): void {\n this.fromInt(0)\n if (!b) b = 10\n const cs = this.chunkSize(b)\n const d = Math.pow(b, cs)\n let mi = false,\n j = 0,\n w = 0\n for (let i = 0; i < s.length; ++i) {\n const x = intAt(s, i)\n if (x < 0) {\n if (s.charAt(i) === '-' && this.signum() === 0) mi = true\n continue\n }\n w = b * w + x\n if (++j >= cs) {\n this.dMultiply(d)\n this.dAddOffset(w, 0)\n j = 0\n w = 0\n }\n }\n if (j > 0) {\n this.dMultiply(Math.pow(b, j))\n this.dAddOffset(w, 0)\n }\n if (mi) BigInteger.ZERO.subTo(this, this)\n }\n\n // alternate constructor\n fromNumber(a: number, b: number | SeededRandom, c?: number): void {\n if ('number' === typeof b) {\n // new BigInteger(int,int,RNG)\n if (a < 2) this.fromInt(1)\n else {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.fromNumber(a, c!)\n if (!this.testBit(a - 1))\n // force MSB set\n this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this)\n if (this.isEven()) this.dAddOffset(1, 0) // force odd\n while (!this.isProbablePrime(b)) {\n this.dAddOffset(2, 0)\n if (this.bitLength() > a)\n this.subTo(BigInteger.ONE.shiftLeft(a - 1), this)\n }\n }\n } else {\n // new BigInteger(int,RNG)\n const x: number[] = [],\n t = a & 7\n x.length = (a >> 3) + 1\n b.nextBytes(x)\n if (t > 0) x[0] &= (1 << t) - 1\n else x[0] = 0\n this.fromString(x, 256)\n }\n }\n\n // convert to bigendian byte array\n toByteArray(): ByteArray {\n const r = []\n let i = this.t\n r[0] = this.s\n let p = BigInteger.DB - ((i * BigInteger.DB) % 8),\n d,\n k = 0\n if (i-- > 0) {\n if (\n p < BigInteger.DB &&\n (d = this[i] >> p) !== (this.s & BigInteger.DM) >> p\n )\n r[k++] = d | (this.s << (BigInteger.DB - p))\n while (i >= 0) {\n if (p < 8) {\n d = (this[i] & ((1 << p) - 1)) << (8 - p)\n d |= this[--i] >> (p += BigInteger.DB - 8)\n } else {\n d = (this[i] >> (p -= 8)) & 0xff\n if (p <= 0) {\n p += BigInteger.DB\n --i\n }\n }\n if ((d & 0x80) !== 0) d |= -256\n if (k === 0 && (this.s & 0x80) !== (d & 0x80)) ++k\n if (k > 0 || d !== this.s) r[k++] = d\n }\n }\n return r\n }\n\n equals(a: BigInteger): boolean {\n return this.compareTo(a) === 0\n }\n\n min(a: BigInteger): BigInteger {\n return this.compareTo(a) < 0 ? this : a\n }\n\n max(a: BigInteger): BigInteger {\n return this.compareTo(a) > 0 ? this : a\n }\n\n // r = this op a (bitwise)\n bitwiseTo(a: BigInteger, op: Op, r: BigInteger): void {\n const m = Math.min(a.t, this.t)\n let f\n for (let i = 0; i < m; ++i) r[i] = op(this[i], a[i])\n if (a.t < this.t) {\n f = a.s & BigInteger.DM\n for (let i = m; i < this.t; ++i) r[i] = op(this[i], f)\n r.t = this.t\n } else {\n f = this.s & BigInteger.DM\n for (let i = m; i < a.t; ++i) r[i] = op(f, a[i])\n r.t = a.t\n }\n r.s = op(this.s, a.s)\n r.clamp()\n }\n\n // this & a\n and(a: BigInteger): BigInteger {\n const r = new BigInteger()\n this.bitwiseTo(a, op_and, r)\n return r\n }\n\n // this | a\n or(a: BigInteger): BigInteger {\n const r = new BigInteger()\n this.bitwiseTo(a, op_or, r)\n return r\n }\n\n // this ^ a\n xor(a: BigInteger): BigInteger {\n const r = new BigInteger()\n this.bitwiseTo(a, op_xor, r)\n return r\n }\n\n // this & ~a\n andNot(a: BigInteger): BigInteger {\n const r = new BigInteger()\n this.bitwiseTo(a, op_andnot, r)\n return r\n }\n\n // ~this\n not(): BigInteger {\n const r = new BigInteger()\n for (let i = 0; i < this.t; ++i) r[i] = BigInteger.DM & ~this[i]\n r.t = this.t\n r.s = ~this.s\n return r\n }\n\n // this << n\n shiftLeft(n: number): BigInteger {\n const r = new BigInteger()\n if (n < 0) this.rShiftTo(-n, r)\n else this.lShiftTo(n, r)\n return r\n }\n\n // this >> n\n shiftRight(n: number): BigInteger {\n const r = new BigInteger()\n if (n < 0) this.lShiftTo(-n, r)\n else this.rShiftTo(n, r)\n return r\n }\n\n // returns index of lowest 1-bit (or -1 if none)\n getLowestSetBit(): number {\n for (let i = 0; i < this.t; ++i)\n if (this[i] !== 0) return i * BigInteger.DB + lbit(this[i])\n if (this.s < 0) return this.t * BigInteger.DB\n return -1\n }\n\n // return number of set bits\n bitCount(): number {\n const x = this.s & BigInteger.DM\n let r = 0\n for (let i = 0; i < this.t; ++i) r += cbit(this[i] ^ x)\n return r\n }\n\n // true iff nth bit is set\n testBit(n: number): boolean {\n const j = Math.floor(n / BigInteger.DB)\n if (j >= this.t) return this.s !== 0\n return (this[j] & (1 << n % BigInteger.DB)) !== 0\n }\n\n // this op (1<>= BigInteger.DB\n }\n if (a.t < this.t) {\n c += a.s\n while (i < this.t) {\n c += this[i]\n r[i++] = c & BigInteger.DM\n c >>= BigInteger.DB\n }\n c += this.s\n } else {\n c += this.s\n while (i < a.t) {\n c += a[i]\n r[i++] = c & BigInteger.DM\n c >>= BigInteger.DB\n }\n c += a.s\n }\n r.s = c < 0 ? -1 : 0\n if (c > 0) r[i++] = c\n else if (c < -1) r[i++] = BigInteger.DV + c\n r.t = i\n r.clamp()\n }\n\n // this + a\n add(a: BigInteger): BigInteger {\n const r = new BigInteger()\n this.addTo(a, r)\n return r\n }\n\n // this - a\n subtract(a: BigInteger): BigInteger {\n const r = new BigInteger()\n this.subTo(a, r)\n return r\n }\n\n // this * a\n multiply(a: BigInteger): BigInteger {\n const r = new BigInteger()\n this.multiplyTo(a, r)\n return r\n }\n\n // JSBN-specific extension\n // this^2\n square(): BigInteger {\n const r = new BigInteger()\n this.squareTo(r)\n return r\n }\n\n // this / a\n divide(a: BigInteger): BigInteger {\n const r = new BigInteger()\n this.divRemTo(a, r, undefined)\n return r\n }\n\n // this % a\n remainder(a: BigInteger): BigInteger {\n const r = new BigInteger()\n this.divRemTo(a, undefined, r)\n return r\n }\n\n // [this/a,this%a]\n divideAndRemainder(a: BigInteger): [BigInteger, BigInteger] {\n const q = new BigInteger(),\n r = new BigInteger()\n this.divRemTo(a, q, r)\n return [q, r]\n }\n\n // this *= n, this >= 0, 1 < n < DV\n protected dMultiply(n: number): void {\n this[this.t] = this.am(0, n - 1, this, 0, 0, this.t)\n ++this.t\n this.clamp()\n }\n\n // this += n << w words, this >= 0\n dAddOffset(n: number, w: number): void {\n if (n === 0) return\n while (this.t <= w) this[this.t++] = 0\n this[w] += n\n while (this[w] >= BigInteger.DV) {\n this[w] -= BigInteger.DV\n if (++w >= this.t) this[this.t++] = 0\n ++this[w]\n }\n }\n\n // this^e\n pow(e: number): BigInteger {\n return this.exp(e, new NullExp())\n }\n\n // r = lower n words of \"this * a\", a.t <= n\n // \"this\" should be the larger one if appropriate.\n multiplyLowerTo(a: BigInteger, n: number, r: BigInteger): void {\n let i = Math.min(this.t + a.t, n)\n r.s = 0 // assumes a,this >= 0\n r.t = i\n while (i > 0) r[--i] = 0\n let j\n for (j = r.t - this.t; i < j; ++i)\n r[i + this.t] = this.am(0, a[i], r, i, 0, this.t)\n for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i)\n r.clamp()\n }\n\n // r = \"this * a\" without lower n words, n > 0\n // \"this\" should be the larger one if appropriate.\n multiplyUpperTo(a: BigInteger, n: number, r: BigInteger): void {\n --n\n let i = (r.t = this.t + a.t - n)\n r.s = 0 // assumes a,this >= 0\n while (--i >= 0) r[i] = 0\n for (i = Math.max(n - this.t, 0); i < a.t; ++i)\n r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n)\n r.clamp()\n r.drShiftTo(1, r)\n }\n\n // this^e % m (HAC 14.85)\n modPow(e: BigInteger, m: BigInteger): BigInteger {\n let i = e.bitLength(),\n k,\n r = new BigInteger(1),\n z\n if (i <= 0) return r\n else if (i < 18) k = 1\n else if (i < 48) k = 3\n else if (i < 144) k = 4\n else if (i < 768) k = 5\n else k = 6\n if (i < 8) z = new Classic(m)\n else if (m.isEven()) z = new Barrett(m)\n else z = new Montgomery(m)\n\n // precomputation\n const g: BigInteger[] = [],\n k1 = k - 1,\n km = (1 << k) - 1\n let n = 3\n g[1] = z.convert(this)\n if (k > 1) {\n const g2 = new BigInteger()\n z.sqrTo(g[1], g2)\n while (n <= km) {\n g[n] = new BigInteger()\n z.mulTo(g2, g[n - 2], g[n])\n n += 2\n }\n }\n\n let j = e.t - 1,\n w,\n is1 = true,\n r2 = new BigInteger(),\n t\n i = nbits(e[j]) - 1\n while (j >= 0) {\n if (i >= k1) w = (e[j] >> (i - k1)) & km\n else {\n w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i)\n if (j > 0) w |= e[j - 1] >> (BigInteger.DB + i - k1)\n }\n\n n = k\n while ((w & 1) === 0) {\n w >>= 1\n --n\n }\n if ((i -= n) < 0) {\n i += BigInteger.DB\n --j\n }\n if (is1) {\n // ret === 1, don't bother squaring or multiplying it\n g[w].copyTo(r)\n is1 = false\n } else {\n while (n > 1) {\n z.sqrTo(r, r2)\n z.sqrTo(r2, r)\n n -= 2\n }\n if (n > 0) z.sqrTo(r, r2)\n else {\n t = r\n r = r2\n r2 = t\n }\n z.mulTo(r2, g[w], r)\n }\n\n while (j >= 0 && (e[j] & (1 << i)) === 0) {\n z.sqrTo(r, r2)\n t = r\n r = r2\n r2 = t\n if (--i < 0) {\n i = BigInteger.DB - 1\n --j\n }\n }\n }\n return z.revert(r)\n }\n\n // gcd(this,a) (HAC 14.54)\n gcd(a: BigInteger): BigInteger {\n let x = this.s < 0 ? this.negate() : this.clone()\n let y = a.s < 0 ? a.negate() : a.clone()\n if (x.compareTo(y) < 0) {\n const t = x\n x = y\n y = t\n }\n let i = x.getLowestSetBit(),\n g = y.getLowestSetBit()\n if (g < 0) return x\n if (i < g) g = i\n if (g > 0) {\n x.rShiftTo(g, x)\n y.rShiftTo(g, y)\n }\n while (x.signum() > 0) {\n if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x)\n if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y)\n if (x.compareTo(y) >= 0) {\n x.subTo(y, x)\n x.rShiftTo(1, x)\n } else {\n y.subTo(x, y)\n y.rShiftTo(1, y)\n }\n }\n if (g > 0) y.lShiftTo(g, y)\n return y\n }\n\n // this % n, n < 2^26\n modInt(n: number): number {\n if (n <= 0) return 0\n const d = BigInteger.DV % n\n let r = this.s < 0 ? n - 1 : 0\n if (this.t > 0)\n if (d === 0) r = this[0] % n\n else for (let i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n\n return r\n }\n\n // 1/this % m (HAC 14.61)\n modInverse(m: BigInteger): BigInteger {\n const ac = m.isEven()\n if ((this.isEven() && ac) || m.signum() === 0) return BigInteger.ZERO\n const u = m.clone(),\n v = this.clone()\n const a = new BigInteger(1),\n b = new BigInteger(0),\n c = new BigInteger(0),\n d = new BigInteger(1)\n while (u.signum() !== 0) {\n while (u.isEven()) {\n u.rShiftTo(1, u)\n if (ac) {\n if (!a.isEven() || !b.isEven()) {\n a.addTo(this, a)\n b.subTo(m, b)\n }\n a.rShiftTo(1, a)\n } else if (!b.isEven()) b.subTo(m, b)\n b.rShiftTo(1, b)\n }\n while (v.isEven()) {\n v.rShiftTo(1, v)\n if (ac) {\n if (!c.isEven() || !d.isEven()) {\n c.addTo(this, c)\n d.subTo(m, d)\n }\n c.rShiftTo(1, c)\n } else if (!d.isEven()) d.subTo(m, d)\n d.rShiftTo(1, d)\n }\n if (u.compareTo(v) >= 0) {\n u.subTo(v, u)\n if (ac) a.subTo(c, a)\n b.subTo(d, b)\n } else {\n v.subTo(u, v)\n if (ac) c.subTo(a, c)\n d.subTo(b, d)\n }\n }\n if (v.compareTo(BigInteger.ONE) !== 0) return BigInteger.ZERO\n if (d.compareTo(m) >= 0) return d.subtract(m)\n if (d.signum() < 0) d.addTo(m, d)\n else return d\n if (d.signum() < 0) return d.add(m)\n else return d\n }\n\n static lowprimes = [\n 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,\n 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,\n 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233,\n 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,\n 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,\n 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,\n 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607,\n 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,\n 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811,\n 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,\n 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997,\n ]\n static lplim =\n (1 << 26) / BigInteger.lowprimes[BigInteger.lowprimes.length - 1]\n\n // test primality with certainty >= 1-.5^t\n isProbablePrime(t: number): boolean {\n const x = this.abs()\n let i\n if (\n x.t === 1 &&\n x[0] <= BigInteger.lowprimes[BigInteger.lowprimes.length - 1]\n ) {\n for (i = 0; i < BigInteger.lowprimes.length; ++i)\n if (x[0] === BigInteger.lowprimes[i]) return true\n return false\n }\n if (x.isEven()) return false\n i = 1\n while (i < BigInteger.lowprimes.length) {\n let m = BigInteger.lowprimes[i],\n j = i + 1\n while (j < BigInteger.lowprimes.length && m < BigInteger.lplim)\n m *= BigInteger.lowprimes[j++]\n m = x.modInt(m)\n while (i < j) if (m % BigInteger.lowprimes[i++] === 0) return false\n }\n return x.millerRabin(t)\n }\n\n // true if probably prime (HAC 4.24, Miller-Rabin)\n millerRabin(t: number): boolean {\n const n1 = this.subtract(BigInteger.ONE)\n const k = n1.getLowestSetBit()\n if (k <= 0) return false\n const r = n1.shiftRight(k)\n t = (t + 1) >> 1\n if (t > BigInteger.lowprimes.length) t = BigInteger.lowprimes.length\n const a = new BigInteger()\n for (let i = 0; i < t; ++i) {\n //Pick bases at random, instead of starting at 2\n a.fromInt(\n BigInteger.lowprimes[\n Math.floor(math.random() * BigInteger.lowprimes.length)\n ],\n )\n let y = a.modPow(r, this)\n if (y.compareTo(BigInteger.ONE) !== 0 && y.compareTo(n1) !== 0) {\n let j = 1\n while (j++ < k && y.compareTo(n1) !== 0) {\n y = y.modPowInt(2, this)\n if (y.compareTo(BigInteger.ONE) === 0) return false\n }\n if (y.compareTo(n1) !== 0) return false\n }\n }\n return true\n }\n}\n\n// Digit conversions\nconst BI_RM = '0123456789abcdefghijklmnopqrstuvwxyz'\nconst BI_RC: number[] = []\nlet rr, vv\nrr = '0'.charCodeAt(0)\nfor (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv\nrr = 'a'.charCodeAt(0)\nfor (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv\nrr = 'A'.charCodeAt(0)\nfor (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv\n\nexport function int2char(n: number): string {\n return BI_RM.charAt(n)\n}\n\nfunction intAt(s: string, i: number): number {\n const c = BI_RC[s.charCodeAt(i)]\n return c == null ? -1 : c\n}\n\n// returns bit length of the integer x\nfunction nbits(x: number): number {\n let r = 1,\n t\n if ((t = x >>> 16) !== 0) {\n x = t\n r += 16\n }\n if ((t = x >> 8) !== 0) {\n x = t\n r += 8\n }\n if ((t = x >> 4) !== 0) {\n x = t\n r += 4\n }\n if ((t = x >> 2) !== 0) {\n x = t\n r += 2\n }\n if ((t = x >> 1) !== 0) {\n // x = t\n r += 1\n }\n return r\n}\n\ninterface Reducer {\n convert(x: BigInteger): BigInteger\n revert(x: BigInteger): BigInteger\n reduce(x: BigInteger): void\n mulTo(x: BigInteger, y: BigInteger, r: BigInteger): void\n sqrTo(x: BigInteger, r: BigInteger): void\n}\n\n// Modular reduction using \"classic\" algorithm\nclass Classic implements Reducer {\n constructor(private readonly m: BigInteger) {}\n\n convert(x: BigInteger): BigInteger {\n if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m)\n else return x\n }\n\n revert(x: BigInteger): BigInteger {\n return x\n }\n\n reduce(x: BigInteger): void {\n x.divRemTo(this.m, undefined, x)\n }\n\n mulTo(x: BigInteger, y: BigInteger, r: BigInteger): void {\n x.multiplyTo(y, r)\n this.reduce(r)\n }\n\n sqrTo(x: BigInteger, r: BigInteger): void {\n x.squareTo(r)\n this.reduce(r)\n }\n}\n\n// Montgomery reduction\nclass Montgomery implements Reducer {\n private readonly m: BigInteger\n private readonly mp: number\n private readonly mpl: number\n private readonly mph: number\n private readonly um: number\n private readonly mt2: number\n\n constructor(m: BigInteger) {\n this.m = m\n this.mp = m.invDigit()\n this.mpl = this.mp & 0x7fff\n this.mph = this.mp >> 15\n this.um = (1 << (BigInteger.DB - 15)) - 1\n this.mt2 = 2 * m.t\n }\n\n // xR mod m\n convert(x: BigInteger): BigInteger {\n const r = new BigInteger()\n x.abs().dlShiftTo(this.m.t, r)\n r.divRemTo(this.m, undefined, r)\n if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r)\n return r\n }\n\n // x/R mod m\n revert(x: BigInteger): BigInteger {\n const r = new BigInteger()\n x.copyTo(r)\n this.reduce(r)\n return r\n }\n\n // x = x/R mod m (HAC 14.32)\n reduce(x: BigInteger): void {\n while (x.t <= this.mt2)\n // pad x so am has enough room later\n x[x.t++] = 0\n for (let i = 0; i < this.m.t; ++i) {\n // faster way of calculating u0 = x[i]*mp mod DV\n let j = x[i] & 0x7fff\n const u0 =\n (j * this.mpl +\n (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) &\n BigInteger.DM\n // use am to combine the multiply-shift-add into one call\n j = i + this.m.t\n x[j] += this.m.am(0, u0, x, i, 0, this.m.t)\n // propagate carry\n while (x[j] >= BigInteger.DV) {\n x[j] -= BigInteger.DV\n x[++j]++\n }\n }\n x.clamp()\n x.drShiftTo(this.m.t, x)\n if (x.compareTo(this.m) >= 0) x.subTo(this.m, x)\n }\n\n // r = \"x^2/R mod m\"; x !== r\n sqrTo(x: BigInteger, r: BigInteger): void {\n x.squareTo(r)\n this.reduce(r)\n }\n\n // r = \"xy/R mod m\"; x,y !== r\n mulTo(x: BigInteger, y: BigInteger, r: BigInteger): void {\n x.multiplyTo(y, r)\n this.reduce(r)\n }\n}\n\n// return index of lowest 1-bit in x, x < 2^31\nfunction lbit(x: number): number {\n if (x === 0) return -1\n let r = 0\n if ((x & 0xffff) === 0) {\n x >>= 16\n r += 16\n }\n if ((x & 0xff) === 0) {\n x >>= 8\n r += 8\n }\n if ((x & 0xf) === 0) {\n x >>= 4\n r += 4\n }\n if ((x & 3) === 0) {\n x >>= 2\n r += 2\n }\n if ((x & 1) === 0) ++r\n return r\n}\n\n// return number of 1 bits in x\nfunction cbit(x: number): number {\n let r = 0\n while (x !== 0) {\n x &= x - 1\n ++r\n }\n return r\n}\n\n// A \"null\" reducer\nclass NullExp implements Reducer {\n convert = nNop\n revert = nNop\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n reduce = (): void => {}\n\n mulTo(x: BigInteger, y: BigInteger, r: BigInteger): void {\n x.multiplyTo(y, r)\n }\n\n sqrTo(x: BigInteger, r: BigInteger): void {\n x.squareTo(r)\n }\n}\n\nfunction nNop(x: BigInteger): BigInteger {\n return x\n}\n\n// Barrett modular reduction\n\nclass Barrett implements Reducer {\n private readonly r2: BigInteger\n private readonly q3: BigInteger\n private readonly mu: BigInteger\n private readonly m: BigInteger\n\n constructor(m: BigInteger) {\n // setup Barrett\n this.r2 = new BigInteger()\n this.q3 = new BigInteger()\n BigInteger.ONE.dlShiftTo(2 * m.t, this.r2)\n this.mu = this.r2.divide(m)\n this.m = m\n }\n\n convert(x: BigInteger): BigInteger {\n if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m)\n else if (x.compareTo(this.m) < 0) return x\n else {\n const r = new BigInteger()\n x.copyTo(r)\n this.reduce(r)\n return r\n }\n }\n\n revert(x: BigInteger): BigInteger {\n return x\n }\n\n // x = x mod m (HAC 14.42)\n reduce(x: BigInteger): void {\n x.drShiftTo(this.m.t - 1, this.r2)\n if (x.t > this.m.t + 1) {\n x.t = this.m.t + 1\n x.clamp()\n }\n this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3)\n this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2)\n while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1)\n x.subTo(this.r2, x)\n while (x.compareTo(this.m) >= 0) x.subTo(this.m, x)\n }\n\n // r = x^2 mod m; x !== r\n sqrTo(x: BigInteger, r: BigInteger): void {\n x.squareTo(r)\n this.reduce(r)\n }\n\n // r = x*y mod m; x,y !== r\n mulTo(x: BigInteger, y: BigInteger, r: BigInteger): void {\n x.multiplyTo(y, r)\n this.reduce(r)\n }\n}\n","// From: https://github.com/tracker1/cryptico-js/blob/57b32417967b9c9b75c47c04971f72a120b59a67/src/hash.js\n\nimport { ByteArray } from '../type'\n\n/**\n *\n * Secure Hash Algorithm (SHA256)\n * http://www.webtoolkit.info/\n *\n * Original code by Angel Marin, Paul Johnston.\n *\n **/\nexport function sha256(msg: string): string {\n const chrsz = 8\n const hexcase = 0\n\n function safe_add(x: number, y: number): number {\n const lsw = (x & 0xffff) + (y & 0xffff)\n const msw = (x >> 16) + (y >> 16) + (lsw >> 16)\n return (msw << 16) | (lsw & 0xffff)\n }\n\n function S(X: number, n: number): number {\n return (X >>> n) | (X << (32 - n))\n }\n function R(X: number, n: number): number {\n return X >>> n\n }\n function Ch(x: number, y: number, z: number): number {\n return (x & y) ^ (~x & z)\n }\n function Maj(x: number, y: number, z: number): number {\n return (x & y) ^ (x & z) ^ (y & z)\n }\n function Sigma0256(x: number): number {\n return S(x, 2) ^ S(x, 13) ^ S(x, 22)\n }\n function Sigma1256(x: number): number {\n return S(x, 6) ^ S(x, 11) ^ S(x, 25)\n }\n function Gamma0256(x: number): number {\n return S(x, 7) ^ S(x, 18) ^ R(x, 3)\n }\n function Gamma1256(x: number): number {\n return S(x, 17) ^ S(x, 19) ^ R(x, 10)\n }\n\n function core_sha256(m: ByteArray, l: number): ByteArray {\n const K = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,\n 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,\n 0xfc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n 0x6ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,\n 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,\n 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n ]\n const HASH = [\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c,\n 0x1f83d9ab, 0x5be0cd19,\n ]\n const W = new Array(64)\n let a, b, c, d, e, f, g, h\n let T1, T2\n\n m[l >> 5] |= 0x80 << (24 - (l % 32))\n m[(((l + 64) >> 9) << 4) + 15] = l\n\n for (let i = 0; i < m.length; i += 16) {\n a = HASH[0]\n b = HASH[1]\n c = HASH[2]\n d = HASH[3]\n e = HASH[4]\n f = HASH[5]\n g = HASH[6]\n h = HASH[7]\n\n for (let j = 0; j < 64; j++) {\n if (j < 16) W[j] = m[j + i]\n else\n W[j] = safe_add(\n safe_add(\n safe_add(Gamma1256(W[j - 2]), W[j - 7]),\n Gamma0256(W[j - 15]),\n ),\n W[j - 16],\n )\n\n T1 = safe_add(\n safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]),\n W[j],\n )\n T2 = safe_add(Sigma0256(a), Maj(a, b, c))\n\n h = g\n g = f\n f = e\n e = safe_add(d, T1)\n d = c\n c = b\n b = a\n a = safe_add(T1, T2)\n }\n\n HASH[0] = safe_add(a, HASH[0])\n HASH[1] = safe_add(b, HASH[1])\n HASH[2] = safe_add(c, HASH[2])\n HASH[3] = safe_add(d, HASH[3])\n HASH[4] = safe_add(e, HASH[4])\n HASH[5] = safe_add(f, HASH[5])\n HASH[6] = safe_add(g, HASH[6])\n HASH[7] = safe_add(h, HASH[7])\n }\n return HASH\n }\n\n function str2binb(str: string): ByteArray {\n const bin: ByteArray = []\n const mask = (1 << chrsz) - 1\n for (let i = 0; i < str.length * chrsz; i += chrsz) {\n bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - (i % 32))\n }\n return bin\n }\n\n function binb2hex(binarray: ByteArray): string {\n const hex_tab = hexcase ? '0123456789ABCDEF' : '0123456789abcdef'\n let str = ''\n for (let i = 0; i < binarray.length * 4; i++) {\n str +=\n hex_tab.charAt((binarray[i >> 2] >> ((3 - (i % 4)) * 8 + 4)) & 0xf) +\n hex_tab.charAt((binarray[i >> 2] >> ((3 - (i % 4)) * 8)) & 0xf)\n }\n return str\n }\n\n msg = Utf8Encode(msg)\n return binb2hex(core_sha256(str2binb(msg), msg.length * chrsz))\n}\n\n/**\n *\n * Secure Hash Algorithm (SHA1)\n * http://www.webtoolkit.info/\n *\n **/\nexport function sha1(msg: string): string {\n function rotate_left(n: number, s: number): number {\n const t4 = (n << s) | (n >>> (32 - s))\n return t4\n }\n\n // function lsb_hex(val: number): string {\n // let str = ''\n // let vh\n // let vl\n //\n // for (let i = 0; i <= 6; i += 2) {\n // vh = (val >>> (i * 4 + 4)) & 0x0f\n // vl = (val >>> (i * 4)) & 0x0f\n // str += vh.toString(16) + vl.toString(16)\n // }\n // return str\n // }\n\n function cvt_hex(val: number): string {\n let str = ''\n let v\n\n for (let i = 7; i >= 0; i--) {\n v = (val >>> (i * 4)) & 0x0f\n str += v.toString(16)\n }\n return str\n }\n\n let blockstart\n let i, j\n const W = new Array(80)\n let H0 = 0x67452301\n let H1 = 0xefcdab89\n let H2 = 0x98badcfe\n let H3 = 0x10325476\n let H4 = 0xc3d2e1f0\n let A, B, C, D, E\n let temp\n\n msg = Utf8Encode(msg)\n\n const msg_len = msg.length\n\n const word_array = []\n for (i = 0; i < msg_len - 3; i += 4) {\n j =\n (msg.charCodeAt(i) << 24) |\n (msg.charCodeAt(i + 1) << 16) |\n (msg.charCodeAt(i + 2) << 8) |\n msg.charCodeAt(i + 3)\n word_array.push(j)\n }\n\n switch (msg_len % 4) {\n case 0:\n i = 0x080000000\n break\n case 1:\n i = (msg.charCodeAt(msg_len - 1) << 24) | 0x0800000\n break\n\n case 2:\n i =\n (msg.charCodeAt(msg_len - 2) << 24) |\n (msg.charCodeAt(msg_len - 1) << 16) |\n 0x08000\n break\n\n case 3:\n i =\n (msg.charCodeAt(msg_len - 3) << 24) |\n (msg.charCodeAt(msg_len - 2) << 16) |\n (msg.charCodeAt(msg_len - 1) << 8) |\n 0x80\n break\n }\n\n word_array.push(i)\n\n while (word_array.length % 16 !== 14) word_array.push(0)\n\n word_array.push(msg_len >>> 29)\n word_array.push((msg_len << 3) & 0x0ffffffff)\n\n for (blockstart = 0; blockstart < word_array.length; blockstart += 16) {\n for (i = 0; i < 16; i++) W[i] = word_array[blockstart + i]\n for (i = 16; i <= 79; i++)\n W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1)\n\n A = H0\n B = H1\n C = H2\n D = H3\n E = H4\n\n for (i = 0; i <= 19; i++) {\n temp =\n (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5a827999) &\n 0x0ffffffff\n E = D\n D = C\n C = rotate_left(B, 30)\n B = A\n A = temp\n }\n\n for (i = 20; i <= 39; i++) {\n temp =\n (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ed9eba1) & 0x0ffffffff\n E = D\n D = C\n C = rotate_left(B, 30)\n B = A\n A = temp\n }\n\n for (i = 40; i <= 59; i++) {\n temp =\n (rotate_left(A, 5) +\n ((B & C) | (B & D) | (C & D)) +\n E +\n W[i] +\n 0x8f1bbcdc) &\n 0x0ffffffff\n E = D\n D = C\n C = rotate_left(B, 30)\n B = A\n A = temp\n }\n\n for (i = 60; i <= 79; i++) {\n temp =\n (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xca62c1d6) & 0x0ffffffff\n E = D\n D = C\n C = rotate_left(B, 30)\n B = A\n A = temp\n }\n\n H0 = (H0 + A) & 0x0ffffffff\n H1 = (H1 + B) & 0x0ffffffff\n H2 = (H2 + C) & 0x0ffffffff\n H3 = (H3 + D) & 0x0ffffffff\n H4 = (H4 + E) & 0x0ffffffff\n }\n\n const ret =\n cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4)\n\n return ret.toLowerCase()\n}\n\n/**\n *\n * MD5 (Message-Digest Algorithm)\n * http://www.webtoolkit.info/\n *\n **/\nexport function md5(msg: string): string {\n function RotateLeft(lValue: number, iShiftBits: number): number {\n return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits))\n }\n\n function AddUnsigned(lX: number, lY: number): number {\n const lX8 = lX & 0x80000000\n const lY8 = lY & 0x80000000\n const lX4 = lX & 0x40000000\n const lY4 = lY & 0x40000000\n const lResult = (lX & 0x3fffffff) + (lY & 0x3fffffff)\n if (lX4 & lY4) {\n return lResult ^ 0x80000000 ^ lX8 ^ lY8\n }\n if (lX4 | lY4) {\n if (lResult & 0x40000000) {\n return lResult ^ 0xc0000000 ^ lX8 ^ lY8\n } else {\n return lResult ^ 0x40000000 ^ lX8 ^ lY8\n }\n } else {\n return lResult ^ lX8 ^ lY8\n }\n }\n\n function F(x: number, y: number, z: number): number {\n return (x & y) | (~x & z)\n }\n function G(x: number, y: number, z: number): number {\n return (x & z) | (y & ~z)\n }\n function H(x: number, y: number, z: number): number {\n return x ^ y ^ z\n }\n function I(x: number, y: number, z: number): number {\n return y ^ (x | ~z)\n }\n\n function FF(\n a: number,\n b: number,\n c: number,\n d: number,\n x: number,\n s: number,\n ac: number,\n ): number {\n a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac))\n return AddUnsigned(RotateLeft(a, s), b)\n }\n\n function GG(\n a: number,\n b: number,\n c: number,\n d: number,\n x: number,\n s: number,\n ac: number,\n ): number {\n a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac))\n return AddUnsigned(RotateLeft(a, s), b)\n }\n\n function HH(\n a: number,\n b: number,\n c: number,\n d: number,\n x: number,\n s: number,\n ac: number,\n ): number {\n a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac))\n return AddUnsigned(RotateLeft(a, s), b)\n }\n\n function II(\n a: number,\n b: number,\n c: number,\n d: number,\n x: number,\n s: number,\n ac: number,\n ): number {\n a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac))\n return AddUnsigned(RotateLeft(a, s), b)\n }\n\n function ConvertToWordArray(str: string): ByteArray {\n let lWordCount\n const lMessageLength = str.length\n const lNumberOfWords_temp1 = lMessageLength + 8\n const lNumberOfWords_temp2 =\n (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64\n const lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16\n const lWordArray: ByteArray = Array(lNumberOfWords - 1)\n let lBytePosition = 0\n let lByteCount = 0\n while (lByteCount < lMessageLength) {\n lWordCount = (lByteCount - (lByteCount % 4)) / 4\n lBytePosition = (lByteCount % 4) * 8\n lWordArray[lWordCount] =\n lWordArray[lWordCount] | (str.charCodeAt(lByteCount) << lBytePosition)\n lByteCount++\n }\n lWordCount = (lByteCount - (lByteCount % 4)) / 4\n lBytePosition = (lByteCount % 4) * 8\n lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition)\n lWordArray[lNumberOfWords - 2] = lMessageLength << 3\n lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29\n return lWordArray\n }\n\n function WordToHex(lValue: number): string {\n let WordToHexValue = '',\n WordToHexValue_temp = '',\n lByte,\n lCount\n for (lCount = 0; lCount <= 3; lCount++) {\n lByte = (lValue >>> (lCount * 8)) & 255\n WordToHexValue_temp = '0' + lByte.toString(16)\n WordToHexValue =\n WordToHexValue +\n WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2)\n }\n return WordToHexValue\n }\n\n let k, AA, BB, CC, DD, a, b, c, d\n const S11 = 7,\n S12 = 12,\n S13 = 17,\n S14 = 22\n const S21 = 5,\n S22 = 9,\n S23 = 14,\n S24 = 20\n const S31 = 4,\n S32 = 11,\n S33 = 16,\n S34 = 23\n const S41 = 6,\n S42 = 10,\n S43 = 15,\n S44 = 21\n\n msg = Utf8Encode(msg)\n\n const x = ConvertToWordArray(msg)\n\n a = 0x67452301\n b = 0xefcdab89\n c = 0x98badcfe\n d = 0x10325476\n\n for (k = 0; k < x.length; k += 16) {\n AA = a\n BB = b\n CC = c\n DD = d\n a = FF(a, b, c, d, x[k + 0], S11, 0xd76aa478)\n d = FF(d, a, b, c, x[k + 1], S12, 0xe8c7b756)\n c = FF(c, d, a, b, x[k + 2], S13, 0x242070db)\n b = FF(b, c, d, a, x[k + 3], S14, 0xc1bdceee)\n a = FF(a, b, c, d, x[k + 4], S11, 0xf57c0faf)\n d = FF(d, a, b, c, x[k + 5], S12, 0x4787c62a)\n c = FF(c, d, a, b, x[k + 6], S13, 0xa8304613)\n b = FF(b, c, d, a, x[k + 7], S14, 0xfd469501)\n a = FF(a, b, c, d, x[k + 8], S11, 0x698098d8)\n d = FF(d, a, b, c, x[k + 9], S12, 0x8b44f7af)\n c = FF(c, d, a, b, x[k + 10], S13, 0xffff5bb1)\n b = FF(b, c, d, a, x[k + 11], S14, 0x895cd7be)\n a = FF(a, b, c, d, x[k + 12], S11, 0x6b901122)\n d = FF(d, a, b, c, x[k + 13], S12, 0xfd987193)\n c = FF(c, d, a, b, x[k + 14], S13, 0xa679438e)\n b = FF(b, c, d, a, x[k + 15], S14, 0x49b40821)\n a = GG(a, b, c, d, x[k + 1], S21, 0xf61e2562)\n d = GG(d, a, b, c, x[k + 6], S22, 0xc040b340)\n c = GG(c, d, a, b, x[k + 11], S23, 0x265e5a51)\n b = GG(b, c, d, a, x[k + 0], S24, 0xe9b6c7aa)\n a = GG(a, b, c, d, x[k + 5], S21, 0xd62f105d)\n d = GG(d, a, b, c, x[k + 10], S22, 0x2441453)\n c = GG(c, d, a, b, x[k + 15], S23, 0xd8a1e681)\n b = GG(b, c, d, a, x[k + 4], S24, 0xe7d3fbc8)\n a = GG(a, b, c, d, x[k + 9], S21, 0x21e1cde6)\n d = GG(d, a, b, c, x[k + 14], S22, 0xc33707d6)\n c = GG(c, d, a, b, x[k + 3], S23, 0xf4d50d87)\n b = GG(b, c, d, a, x[k + 8], S24, 0x455a14ed)\n a = GG(a, b, c, d, x[k + 13], S21, 0xa9e3e905)\n d = GG(d, a, b, c, x[k + 2], S22, 0xfcefa3f8)\n c = GG(c, d, a, b, x[k + 7], S23, 0x676f02d9)\n b = GG(b, c, d, a, x[k + 12], S24, 0x8d2a4c8a)\n a = HH(a, b, c, d, x[k + 5], S31, 0xfffa3942)\n d = HH(d, a, b, c, x[k + 8], S32, 0x8771f681)\n c = HH(c, d, a, b, x[k + 11], S33, 0x6d9d6122)\n b = HH(b, c, d, a, x[k + 14], S34, 0xfde5380c)\n a = HH(a, b, c, d, x[k + 1], S31, 0xa4beea44)\n d = HH(d, a, b, c, x[k + 4], S32, 0x4bdecfa9)\n c = HH(c, d, a, b, x[k + 7], S33, 0xf6bb4b60)\n b = HH(b, c, d, a, x[k + 10], S34, 0xbebfbc70)\n a = HH(a, b, c, d, x[k + 13], S31, 0x289b7ec6)\n d = HH(d, a, b, c, x[k + 0], S32, 0xeaa127fa)\n c = HH(c, d, a, b, x[k + 3], S33, 0xd4ef3085)\n b = HH(b, c, d, a, x[k + 6], S34, 0x4881d05)\n a = HH(a, b, c, d, x[k + 9], S31, 0xd9d4d039)\n d = HH(d, a, b, c, x[k + 12], S32, 0xe6db99e5)\n c = HH(c, d, a, b, x[k + 15], S33, 0x1fa27cf8)\n b = HH(b, c, d, a, x[k + 2], S34, 0xc4ac5665)\n a = II(a, b, c, d, x[k + 0], S41, 0xf4292244)\n d = II(d, a, b, c, x[k + 7], S42, 0x432aff97)\n c = II(c, d, a, b, x[k + 14], S43, 0xab9423a7)\n b = II(b, c, d, a, x[k + 5], S44, 0xfc93a039)\n a = II(a, b, c, d, x[k + 12], S41, 0x655b59c3)\n d = II(d, a, b, c, x[k + 3], S42, 0x8f0ccc92)\n c = II(c, d, a, b, x[k + 10], S43, 0xffeff47d)\n b = II(b, c, d, a, x[k + 1], S44, 0x85845dd1)\n a = II(a, b, c, d, x[k + 8], S41, 0x6fa87e4f)\n d = II(d, a, b, c, x[k + 15], S42, 0xfe2ce6e0)\n c = II(c, d, a, b, x[k + 6], S43, 0xa3014314)\n b = II(b, c, d, a, x[k + 13], S44, 0x4e0811a1)\n a = II(a, b, c, d, x[k + 4], S41, 0xf7537e82)\n d = II(d, a, b, c, x[k + 11], S42, 0xbd3af235)\n c = II(c, d, a, b, x[k + 2], S43, 0x2ad7d2bb)\n b = II(b, c, d, a, x[k + 9], S44, 0xeb86d391)\n a = AddUnsigned(a, AA)\n b = AddUnsigned(b, BB)\n c = AddUnsigned(c, CC)\n d = AddUnsigned(d, DD)\n }\n\n const temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d)\n\n return temp.toLowerCase()\n}\n\nfunction Utf8Encode(str: string): string {\n str = str.replace(/\\r\\n/g, '\\n')\n let utftext = ''\n\n for (let n = 0; n < str.length; n++) {\n const c = str.charCodeAt(n)\n\n if (c < 128) {\n utftext += String.fromCharCode(c)\n } else if (c > 127 && c < 2048) {\n utftext += String.fromCharCode((c >> 6) | 192)\n utftext += String.fromCharCode((c & 63) | 128)\n } else {\n utftext += String.fromCharCode((c >> 12) | 224)\n utftext += String.fromCharCode(((c >> 6) & 63) | 128)\n utftext += String.fromCharCode((c & 63) | 128)\n }\n }\n\n return utftext\n}\n","import * as native from './native'\nimport * as node from './node'\n\nexport type HashFunc = (s: string) => string\n\nexport const sha256 = (\n process.env.NODEJS ? node.sha256 : native.sha256\n) as HashFunc\n\nexport const sha1 = (process.env.NODEJS ? node.sha1 : native.sha1) as HashFunc\n\nexport const md5 = (process.env.NODEJS ? node.md5 : native.md5) as HashFunc\n","import crypto from 'crypto'\n\nexport function sha256(msg: string): string {\n return crypto.createHash('sha256').update(msg, 'utf8').digest('hex')\n}\n\nexport function sha1(msg: string): string {\n return crypto.createHash('sha1').update(msg, 'utf8').digest('hex')\n}\n\nexport function md5(msg: string): string {\n return crypto.createHash('md5').update(msg, 'utf8').digest('hex')\n}\n","// Depends on jsbn.js and rng.js\n// Version 1.1: support utf-8 encoding in pkcs1pad2\n// convert a (hex) string to a bignum object\n\nimport { BigInteger } from './jsbn'\nimport { SecureRandom, SeededRandom } from './random'\nimport { sha1, sha256 } from './hash'\n\nexport function parseBigInt(str: string, r: number): BigInteger {\n return new BigInteger(str, r)\n}\n\nexport function linebrk(s: string, n: number): string {\n let ret = ''\n let i = 0\n while (i + n < s.length) {\n ret += s.substring(i, i + n) + '\\n'\n i += n\n }\n return ret + s.substring(i, s.length)\n}\n\nexport function byte2Hex(b: number): string {\n if (b < 0x10) return '0' + b.toString(16)\n else return b.toString(16)\n}\n\n// PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint\nexport function pkcs1pad2(s: string, n: number): BigInteger {\n if (n < s.length + 11) {\n // TODO: fix for utf-8\n //throw \"Message too long for RSA (n=\" + n + \", l=\" + s.length + \")\"\n //return null;\n throw 'Message too long for RSA (n=' + n + ', l=' + s.length + ')'\n }\n const ba = []\n let i = s.length - 1\n while (i >= 0 && n > 0) {\n const c = s.charCodeAt(i--)\n if (c < 128) {\n // encode using utf-8\n ba[--n] = c\n } else if (c > 127 && c < 2048) {\n ba[--n] = (c & 63) | 128\n ba[--n] = (c >> 6) | 192\n } else {\n ba[--n] = (c & 63) | 128\n ba[--n] = ((c >> 6) & 63) | 128\n ba[--n] = (c >> 12) | 224\n }\n }\n ba[--n] = 0\n const rng = new SecureRandom()\n const x = []\n while (n > 2) {\n // random non-zero pad\n x[0] = 0\n while (x[0] === 0) rng.nextBytes(x)\n ba[--n] = x[0]\n }\n ba[--n] = 2\n ba[--n] = 0\n return new BigInteger(ba)\n}\n\ntype RSAKeyKey = 'n' | 'e' | 'd' | 'p' | 'q' | 'dmp1' | 'dmq1' | 'coeff'\n\n// \"empty\" RSA key constructor\nexport class RSAKey {\n n = new BigInteger()\n e = 0\n private d = new BigInteger()\n private p = new BigInteger()\n private q = new BigInteger()\n private dmp1 = new BigInteger()\n private dmq1 = new BigInteger()\n private coeff = new BigInteger()\n\n // Return the PKCS#1 RSA encryption of \"text\" as a Base64-encoded string\n // encryptB64(text: string): string | null {\n // const h = this.encrypt(text)\n // if (h) return hex2b64(h)\n // else return null\n // }\n\n // Set the public key fields N and e from hex strings\n setPublic(N: string, E: string): void {\n if (N && E) {\n this.n = parseBigInt(N, 16)\n this.e = parseInt(E, 16)\n } else throw 'Invalid RSA public key'\n }\n\n // Perform raw public operation on \"x\": return x^e (mod n)\n doPublic(x: BigInteger): BigInteger {\n return x.modPowInt(this.e, this.n)\n }\n\n // Return the PKCS#1 RSA encryption of \"text\" as an even-length hex string\n encrypt(text: string): string {\n const m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3)\n // if (!m) return null\n const c = this.doPublic(m)\n // if (!c) return null\n const h = c.toString(16)\n if ((h.length & 1) === 0) return h\n else return '0' + h\n }\n\n // Set the private key fields N, e, and d from hex strings\n setPrivate(N: string, E: string, D: string): void {\n if (!N && !E && N.length > 0 && E.length > 0) {\n this.n = parseBigInt(N, 16)\n this.e = parseInt(E, 16)\n this.d = parseBigInt(D, 16)\n } else throw 'Invalid RSA private key'\n }\n\n // Set the private key fields N, e, d and CRT params from hex strings\n setPrivateEx(\n N: string,\n E: string,\n D: string,\n P: string,\n Q: string,\n DP: string,\n DQ: string,\n C: string,\n ): void {\n if (!N && !E && N.length > 0 && E.length > 0) {\n this.n = parseBigInt(N, 16)\n this.e = parseInt(E, 16)\n this.d = parseBigInt(D, 16)\n this.p = parseBigInt(P, 16)\n this.q = parseBigInt(Q, 16)\n this.dmp1 = parseBigInt(DP, 16)\n this.dmq1 = parseBigInt(DQ, 16)\n this.coeff = parseBigInt(C, 16)\n } else throw new Error('Invalid RSA private key')\n }\n\n // Generate a new random private key B bits long, using public expt E\n generate(B: number, E: string): void {\n const rng = new SeededRandom()\n const qs = B >> 1\n this.e = parseInt(E, 16)\n const ee = new BigInteger(E, 16)\n for (;;) {\n for (;;) {\n this.p = new BigInteger(B - qs, 1, rng)\n if (\n this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) ===\n 0 &&\n this.p.isProbablePrime(10)\n )\n break\n }\n for (;;) {\n this.q = new BigInteger(qs, 1, rng)\n if (\n this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) ===\n 0 &&\n this.q.isProbablePrime(10)\n )\n break\n }\n if (this.p.compareTo(this.q) <= 0) {\n const t = this.p\n this.p = this.q\n this.q = t\n }\n const p1 = this.p.subtract(BigInteger.ONE)\n const q1 = this.q.subtract(BigInteger.ONE)\n const phi = p1.multiply(q1)\n if (phi.gcd(ee).compareTo(BigInteger.ONE) === 0) {\n this.n = this.p.multiply(this.q)\n this.d = ee.modInverse(phi)\n this.dmp1 = this.d.mod(p1)\n this.dmq1 = this.d.mod(q1)\n this.coeff = this.q.modInverse(this.p)\n break\n }\n }\n }\n\n // Perform raw private operation on \"x\": return x^d (mod n)\n protected doPrivate(x: BigInteger): BigInteger {\n if (!this.p || !this.q) return x.modPow(this.d, this.n)\n // TODO: re-calculate any missing CRT params\n let xp = x.mod(this.p).modPow(this.dmp1, this.p)\n const xq = x.mod(this.q).modPow(this.dmq1, this.q)\n while (xp.compareTo(xq) < 0) xp = xp.add(this.p)\n return xp\n .subtract(xq)\n .multiply(this.coeff)\n .mod(this.p)\n .multiply(this.q)\n .add(xq)\n }\n\n // Return the PKCS#1 RSA decryption of \"ctext\".\n // \"ctext\" is an even-length hex string and the output is a plain string.\n decrypt(ctext: string): string | null {\n const c = parseBigInt(ctext, 16)\n const m = this.doPrivate(c)\n if (!(m instanceof BigInteger)) return null\n return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3)\n }\n\n signString = _rsasign_signString\n signStringWithSHA1 = _rsasign_signStringWithSHA1\n signStringWithSHA256 = _rsasign_signStringWithSHA256\n verifyHexSignatureForMessage = _rsasign_verifyHexSignatureForMessage\n verifyString = _rsasign_verifyString\n\n toJSON(): string {\n return JSON.stringify({\n coeff: this.coeff.toString(16),\n d: this.d.toString(16),\n dmp1: this.dmp1.toString(16),\n dmq1: this.dmq1.toString(16),\n e: this.e.toString(16),\n n: this.n.toString(16),\n p: this.p.toString(16),\n q: this.q.toString(16),\n })\n }\n\n static parse(key: string | Record): RSAKey | null {\n const json = (typeof key === 'string' ? JSON.parse(key) : key) as Record<\n RSAKeyKey,\n string\n >\n if (!json) {\n return null\n }\n\n const rsa = new RSAKey()\n rsa.setPrivateEx(\n json.n,\n json.e,\n json.d,\n json.p,\n json.q,\n json.dmp1,\n json.dmq1,\n json.coeff,\n )\n\n return rsa\n }\n}\n\n// Version 1.1: support utf-8 decoding in pkcs1unpad2\n// Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext\nexport function pkcs1unpad2(d: BigInteger, n: number): string | null {\n const b = d.toByteArray()\n let i = 0\n while (i < b.length && b[i] === 0) ++i\n if (b.length - i !== n - 1 || b[i] !== 2) return null\n ++i\n while (b[i] !== 0) if (++i >= b.length) return null\n let ret = ''\n while (++i < b.length) {\n const c = b[i] & 255\n if (c < 128) {\n // utf-8 decode\n ret += String.fromCharCode(c)\n } else if (c > 191 && c < 224) {\n ret += String.fromCharCode(((c & 31) << 6) | (b[i + 1] & 63))\n ++i\n } else {\n ret += String.fromCharCode(\n ((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63),\n )\n i += 2\n }\n }\n return ret\n}\n\n//\n// rsa-sign.js - adding signing functions to RSAKey class.\n//\n//\n// version: 1.0 (2010-Jun-03)\n//\n// Copyright (c) 2010 Kenji Urushima (kenji.urushima@gmail.com)\n//\n// This software is licensed under the terms of the MIT License.\n// http://www.opensource.org/licenses/mit-license.php\n//\n// The above copyright and license notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// Depends on:\n// function sha1(s) of sha1.js\n// jsbn.js\n// jsbn2.js\n// rsa.js\n// rsa2.js\n//\n// keysize / pmstrlen\n// 512 / 128\n// 1024 / 256\n// 2048 / 512\n// 4096 / 1024\n// As for _RSASGIN_DIHEAD values for each hash algorithm, see PKCS#1 v2.1 spec (p38).\nconst _RSASIGN_DIHEAD = {\n sha1: '3021300906052b0e03021a05000414',\n sha256: '3031300d060960864801650304020105000420',\n // md2: '3020300c06082a864886f70d020205000410',\n // md5: '3020300c06082a864886f70d020505000410',\n // sha384: '3041300d060960864801650304020205000430',\n // sha512: '3051300d060960864801650304020305000440',\n}\nconst _RSASIGN_HASHHEXFUNC = {\n sha1,\n sha256,\n}\ntype HashAlg = keyof typeof _RSASIGN_HASHHEXFUNC\n\n// ========================================================================\n// Signature Generation\n// ========================================================================\n\nfunction _rsasign_getHexPaddedDigestInfoForString(\n s: string,\n keySize: number,\n hashAlg: HashAlg,\n): string {\n const pmStrLen = keySize / 4\n const hashFunc = _RSASIGN_HASHHEXFUNC[hashAlg]\n const sHashHex = hashFunc(s)\n\n const sHead = '0001'\n const sTail = '00' + _RSASIGN_DIHEAD[hashAlg] + sHashHex\n let sMid = ''\n const fLen = pmStrLen - sHead.length - sTail.length\n for (let i = 0; i < fLen; i += 2) {\n sMid += 'ff'\n }\n const sPaddedMessageHex = sHead + sMid + sTail\n return sPaddedMessageHex\n}\n\nfunction _rsasign_signString(\n this: RSAKey,\n s: string,\n hashAlg: HashAlg,\n): string {\n const hPM = _rsasign_getHexPaddedDigestInfoForString(\n s,\n this.n.bitLength(),\n hashAlg,\n )\n const biPaddedMessage = parseBigInt(hPM, 16)\n const biSign = this.doPrivate(biPaddedMessage)\n const hexSign = biSign.toString(16)\n return hexSign\n}\n\nfunction _rsasign_signStringWithSHA1(this: RSAKey, s: string): string {\n const hPM = _rsasign_getHexPaddedDigestInfoForString(\n s,\n this.n.bitLength(),\n 'sha1',\n )\n const biPaddedMessage = parseBigInt(hPM, 16)\n const biSign = this.doPrivate(biPaddedMessage)\n const hexSign = biSign.toString(16)\n return hexSign\n}\n\nfunction _rsasign_signStringWithSHA256(this: RSAKey, s: string): string {\n const hPM = _rsasign_getHexPaddedDigestInfoForString(\n s,\n this.n.bitLength(),\n 'sha256',\n )\n const biPaddedMessage = parseBigInt(hPM, 16)\n const biSign = this.doPrivate(biPaddedMessage)\n const hexSign = biSign.toString(16)\n return hexSign\n}\n\n// ========================================================================\n// Signature Verification\n// ========================================================================\n\nfunction _rsasign_getDecryptSignatureBI(\n biSig: BigInteger,\n hN: string,\n hE: string,\n): BigInteger {\n const rsa = new RSAKey()\n rsa.setPublic(hN, hE)\n const biDecryptedSig = rsa.doPublic(biSig)\n return biDecryptedSig\n}\n\nfunction _rsasign_getHexDigestInfoFromSig(\n biSig: BigInteger,\n hN: string,\n hE: string,\n): string {\n const biDecryptedSig = _rsasign_getDecryptSignatureBI(biSig, hN, hE)\n const hDigestInfo = biDecryptedSig.toString(16).replace(/^1f+00/, '')\n return hDigestInfo\n}\n\nfunction _rsasign_getAlgNameAndHashFromHexDisgestInfo(\n hDigestInfo: string,\n): [HashAlg, string] | [] {\n for (const algName in _RSASIGN_DIHEAD) {\n const head = _RSASIGN_DIHEAD[algName as HashAlg]\n const len = head.length\n if (hDigestInfo.substring(0, len) === head) {\n return [algName as HashAlg, hDigestInfo.substring(len)]\n }\n }\n return []\n}\n\nfunction _rsasign_verifySignatureWithArgs(\n sMsg: string,\n biSig: BigInteger,\n hN: string,\n hE: string,\n): boolean {\n const hDigestInfo = _rsasign_getHexDigestInfoFromSig(biSig, hN, hE)\n const digestInfoAry =\n _rsasign_getAlgNameAndHashFromHexDisgestInfo(hDigestInfo)\n if (digestInfoAry.length === 0) return false\n const algName = digestInfoAry[0]\n const diHashValue = digestInfoAry[1]\n const ff = _RSASIGN_HASHHEXFUNC[algName]\n const msgHashValue = ff(sMsg)\n return diHashValue === msgHashValue\n}\n\nfunction _rsasign_verifyHexSignatureForMessage(\n this: RSAKey,\n sMsg: string,\n hSig: string,\n): boolean {\n const biSig = parseBigInt(hSig, 16)\n const result = _rsasign_verifySignatureWithArgs(\n sMsg,\n biSig,\n this.n.toString(16),\n this.e.toString(16),\n )\n return result\n}\n\nfunction _rsasign_verifyString(\n this: RSAKey,\n sMsg: string,\n hSig: string,\n): boolean {\n hSig = hSig.replace(/[ \\n]+/g, '')\n const biSig = parseBigInt(hSig, 16)\n const biDecryptedSig = this.doPublic(biSig)\n const hDigestInfo = biDecryptedSig.toString(16).replace(/^1f+00/, '')\n const digestInfoAry =\n _rsasign_getAlgNameAndHashFromHexDisgestInfo(hDigestInfo)\n\n if (digestInfoAry.length === 0) return false\n const algName = digestInfoAry[0]\n const diHashValue = digestInfoAry[1]\n const ff = _RSASIGN_HASHHEXFUNC[algName]\n const msgHashValue = ff(sMsg)\n return diHashValue === msgHashValue\n}\n","import { aes, AESKey } from './aes'\nimport { int2char } from './jsbn'\nimport { math, SecureRandom } from './random'\nimport { md5, sha256 } from './hash'\nimport { RSAKey } from './rsa'\nimport { ByteArray } from './type'\n\nconst base64Chars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nconst magic = '::52cee64bb3a38f6403386519a39ac91c::'\n\naes.Init()\n\ntype DecryptStatusSuccessForSignature = {\n status: 'success'\n plaintext: string\n signature: Signature\n publicKeyString: Signature extends 'unsigned' ? never : string\n}\ntype DecryptStatusSuccess =\n | DecryptStatusSuccessForSignature<'unsigned'>\n | DecryptStatusSuccessForSignature<'verified' | 'forged'>\ntype DecryptStatusFailure = { status: 'Invalid public key' | 'failure' }\n\nexport class cryptico {\n static b256to64(t: string): string {\n let a = 0, // Should be reassigned before read\n c,\n n\n let r = '',\n // l = 0,\n s = 0\n const tl = t.length\n for (n = 0; n < tl; n++) {\n c = t.charCodeAt(n)\n if (s === 0) {\n r += base64Chars.charAt((c >> 2) & 63)\n a = (c & 3) << 4\n } else if (s === 1) {\n r += base64Chars.charAt(a | ((c >> 4) & 15))\n a = (c & 15) << 2\n } else if (s === 2) {\n r += base64Chars.charAt(a | ((c >> 6) & 3))\n // l += 1\n r += base64Chars.charAt(c & 63)\n }\n // l += 1\n s += 1\n if (s === 3) s = 0\n }\n if (s > 0) {\n r += base64Chars.charAt(a)\n // l += 1\n r += '='\n // l += 1\n }\n if (s === 1) {\n r += '='\n }\n return r\n }\n\n static b64to256(t: string): string {\n let c, n\n let r = '',\n s = 0,\n a = 0\n const tl = t.length\n for (n = 0; n < tl; n++) {\n c = base64Chars.indexOf(t.charAt(n))\n if (c >= 0) {\n if (s) r += String.fromCharCode(a | ((c >> (6 - s)) & 255))\n s = (s + 2) & 7\n a = (c << s) & 255\n }\n }\n return r\n }\n\n static b16to64(h: string): string {\n let i\n let c\n let ret = ''\n if (h.length % 2 === 1) {\n h = '0' + h\n }\n for (i = 0; i + 3 <= h.length; i += 3) {\n c = parseInt(h.substring(i, i + 3), 16)\n ret += base64Chars.charAt(c >> 6) + base64Chars.charAt(c & 63)\n }\n if (i + 1 === h.length) {\n c = parseInt(h.substring(i, i + 1), 16)\n ret += base64Chars.charAt(c << 2)\n } else if (i + 2 === h.length) {\n c = parseInt(h.substring(i, i + 2), 16)\n ret += base64Chars.charAt(c >> 2) + base64Chars.charAt((c & 3) << 4)\n }\n while ((ret.length & 3) > 0) ret += '='\n return ret\n }\n\n static b64to16(s: string): string {\n let ret = ''\n let i\n let k = 0\n let slop = 0 // Should be reassigned before read\n for (i = 0; i < s.length; ++i) {\n if (s.charAt(i) === '=') break\n const v = base64Chars.indexOf(s.charAt(i))\n if (v < 0) continue\n if (k === 0) {\n ret += int2char(v >> 2)\n slop = v & 3\n k = 1\n } else if (k === 1) {\n ret += int2char((slop << 2) | (v >> 4))\n slop = v & 0xf\n k = 2\n } else if (k === 2) {\n ret += int2char(slop)\n ret += int2char(v >> 2)\n slop = v & 3\n k = 3\n } else {\n ret += int2char((slop << 2) | (v >> 4))\n ret += int2char(v & 0xf)\n k = 0\n }\n }\n if (k === 1) ret += int2char(slop << 2)\n return ret\n }\n\n // Converts a string to a byte array.\n static string2bytes(str: string): ByteArray {\n const bytes = []\n for (let i = 0; i < str.length; i++) {\n bytes.push(str.charCodeAt(i))\n }\n return bytes\n }\n\n // Converts a byte array to a string.\n static bytes2string(bytes: ByteArray): string {\n let str = ''\n for (let i = 0; i < bytes.length; i++) {\n str += String.fromCharCode(bytes[i])\n }\n return str\n }\n\n // Converts a UTF-8 string to ASCII string.\n static utf82string(str: string): string {\n return unescape(encodeURIComponent(str))\n }\n\n // Converts ascii string to a UTF-8 string.\n static string2utf8(uriencoded: string): string {\n return decodeURIComponent(escape(uriencoded))\n }\n\n // Converts a UTF-8 string to a byte array.\n static utf82bytes(str: string): ByteArray {\n const uriencoded = unescape(encodeURIComponent(str))\n return this.string2bytes(uriencoded)\n }\n\n // Converts a byte array to a UTF-8 string.\n static bytes2utf8(bytes: ByteArray): string {\n const uriencoded = this.bytes2string(bytes)\n return decodeURIComponent(escape(uriencoded))\n }\n\n // Returns a XOR b, where a and b are 16-byte byte arrays.\n static blockXOR(a: ByteArray, b: ByteArray): ByteArray {\n const xor = new Array(16) as ByteArray\n for (let i = 0; i < 16; i++) {\n xor[i] = a[i] ^ b[i]\n }\n return xor\n }\n\n // Returns a 16-byte initialization vector.\n static blockIV(): ByteArray {\n const r = new SecureRandom()\n const IV = new Array(16) as ByteArray\n r.nextBytes(IV)\n return IV\n }\n\n // Returns a copy of bytes with zeros appended to the end\n // so that the (length of bytes) % 16 === 0.\n static pad16(bytes: ByteArray): ByteArray {\n const newBytes = bytes.slice(0)\n const padding = (16 - (bytes.length % 16)) % 16\n for (let i = bytes.length; i < bytes.length + padding; i++) {\n newBytes.push(0)\n }\n return newBytes\n }\n\n // Removes trailing zeros from a byte array.\n static depad(bytes: ByteArray): ByteArray {\n let newBytes = bytes.slice(0)\n while (newBytes[newBytes.length - 1] === 0) {\n newBytes = newBytes.slice(0, newBytes.length - 1)\n }\n return newBytes\n }\n\n // AES CBC Encryption.\n static encryptAESCBC(plaintext: string, key: AESKey): string {\n const exkey = key.slice(0)\n aes.ExpandKey(exkey)\n let blocks = this.utf82bytes(plaintext)\n blocks = this.pad16(blocks)\n let encryptedBlocks = this.blockIV()\n for (let i = 0; i < blocks.length / 16; i++) {\n let tempBlock = blocks.slice(i * 16, i * 16 + 16)\n const prevBlock = encryptedBlocks.slice(i * 16, i * 16 + 16)\n tempBlock = this.blockXOR(prevBlock, tempBlock)\n aes.Encrypt(tempBlock, exkey)\n encryptedBlocks = encryptedBlocks.concat(tempBlock)\n }\n const ciphertext = this.bytes2string(encryptedBlocks)\n return this.b256to64(ciphertext)\n }\n\n // AES CBC Decryption.\n static decryptAESCBC(encryptedText: string, key: AESKey): string {\n const exkey = key.slice(0)\n aes.ExpandKey(exkey)\n const asciiText = this.b64to256(encryptedText)\n const encryptedBlocks = this.string2bytes(asciiText)\n let decryptedBlocks: ByteArray = []\n for (let i = 1; i < encryptedBlocks.length / 16; i++) {\n let tempBlock = encryptedBlocks.slice(i * 16, i * 16 + 16)\n const prevBlock = encryptedBlocks.slice((i - 1) * 16, (i - 1) * 16 + 16)\n aes.Decrypt(tempBlock, exkey)\n tempBlock = this.blockXOR(prevBlock, tempBlock)\n decryptedBlocks = decryptedBlocks.concat(tempBlock)\n }\n decryptedBlocks = this.depad(decryptedBlocks)\n return this.bytes2utf8(decryptedBlocks)\n }\n\n // Wraps a str to 60 characters.\n static wrap60(str: string): string {\n let outstr = ''\n for (let i = 0; i < str.length; i++) {\n if (i % 60 === 0 && i !== 0) outstr += '\\n'\n outstr += str[i]\n }\n return outstr\n }\n\n // Generate a random key for the AES-encrypted message. ciphertext.split\n static generateAESKey(): AESKey {\n const key = new Array(32) as ByteArray\n const r = new SecureRandom()\n r.nextBytes(key)\n return key\n }\n\n // Generates an RSA key from a passphrase.\n static generateRSAKey(passphrase: string, bitlength: number): RSAKey {\n math.seedrandom(sha256(passphrase))\n const rsa = new RSAKey()\n rsa.generate(bitlength, '03')\n return rsa\n }\n\n // Returns the ascii-armored version of the public key.\n static publicKeyString(rsakey: RSAKey): string {\n return this.b16to64(rsakey.n.toString(16))\n }\n\n // Returns an MD5 sum of a publicKeyString for easier identification.\n static publicKeyID(publicKeyString: string): string {\n return md5(publicKeyString)\n }\n\n static publicKeyFromString(str: string): RSAKey {\n const N = this.b64to16(str.split('|')[0])\n const E = '03'\n const rsa = new RSAKey()\n rsa.setPublic(N, E)\n return rsa\n }\n\n static encrypt(\n plaintext: string,\n publickeystring: string,\n signingkey: RSAKey,\n ): { status: string } | { status: 'success'; cipher: string } {\n {\n let cipherblock = ''\n const aeskey = this.generateAESKey()\n try {\n const publickey = this.publicKeyFromString(publickeystring)\n cipherblock +=\n this.b16to64(publickey.encrypt(this.bytes2string(aeskey))) + '?'\n } catch (err) {\n return { status: 'Invalid public key' }\n }\n if (signingkey) {\n const signString = this.sign(plaintext, signingkey)\n plaintext += magic\n plaintext += this.publicKeyString(signingkey)\n plaintext += magic\n plaintext += signString\n }\n cipherblock += this.encryptAESCBC(plaintext, aeskey)\n return { status: 'success', cipher: cipherblock }\n }\n }\n\n static decrypt(\n ciphertext: string,\n key: RSAKey,\n ): DecryptStatusSuccess | DecryptStatusFailure {\n const cipherblock = ciphertext.split('?')\n const aeskey = key.decrypt(this.b64to16(cipherblock[0]))\n if (aeskey == null) {\n return { status: 'failure' }\n }\n const aeskeyBytes = this.string2bytes(aeskey)\n const plaintext = this.decryptAESCBC(cipherblock[1], aeskeyBytes).split(\n magic,\n )\n if (plaintext.length > 1) {\n return this._confirm(plaintext)\n } else\n return {\n status: 'success',\n plaintext: plaintext[0],\n signature: 'unsigned',\n } as DecryptStatusSuccessForSignature<'unsigned'>\n }\n\n static sign(plaintext: string, signingkey: RSAKey): string {\n return this.b16to64(signingkey.signString(plaintext, 'sha256'))\n }\n\n static verify(plaintext: string[]): boolean {\n const result = this._confirm(plaintext)\n return result.status === 'success' && result.signature === 'verified'\n }\n\n private static _confirm(\n plaintext: string[],\n ): DecryptStatusSuccess | DecryptStatusFailure {\n if (plaintext.length === 3) {\n const publickey = this.publicKeyFromString(plaintext[1])\n const signature = this.b64to16(plaintext[2])\n if (publickey.verifyString(plaintext[0], signature)) {\n return {\n status: 'success',\n plaintext: plaintext[0],\n signature: 'verified',\n publicKeyString: this.publicKeyString(publickey),\n }\n } else {\n return {\n status: 'success',\n plaintext: plaintext[0],\n signature: 'forged',\n publicKeyString: this.publicKeyString(publickey),\n }\n }\n } else {\n return {\n status: 'failure',\n }\n }\n }\n}\n"],"names":["aes","Sbox","ShiftRowTab","Sbox_Inv","Array","ShiftRowTab_Inv","xtime","[object Object]","i","this","length","key","kl","ks","Rcon","temp","slice","j","block","l","AddRoundKey","SubBytes","ShiftRows","MixColumns","MixColumns_Inv","state","sbox","rkey","shifttab","h","concat","s0","s1","s2","s3","xh","h1","h2","pool","width","significance","Math","pow","overflow","startdenom","math","seed","use_entropy","mixkey","flatten","arguments","Date","getTime","arc4","ARC4","S","random","n","g","d","x","t","u","keylen","lowbits","count","s","r","obj","depth","result","typ","prop","indexOf","push","e","console","error","seedStr","smear","charCodeAt","mixed","forEach","v","String","fromCharCode","SeededRandom","ba","floor","Arcfour","rng_state","rng_pptr","rng_pool","rng_seed_time","rng_get_byte","init","next","SecureRandom","op_and","y","op_or","op_xor","op_andnot","BigInteger","BI_FP","a","b","c","fromNumber","fromInt","fromString","w","xl","m","DV","k","fromRadix","mi","sh","intAt","charAt","DB","clamp","ZERO","subTo","DM","negate","toString","toRadix","km","p","int2char","nbits","max","bs","cbs","bm","ds","min","abs","am","q","pm","pt","copyTo","ts","ms","nsh","lShiftTo","ys","y0","yt","F1","F2","d1","FV","d2","dlShiftTo","compareTo","ONE","qd","drShiftTo","rShiftTo","divRemTo","undefined","z","convert","r2","sqrTo","mulTo","revert","isEven","Classic","Montgomery","exp","LN2","log","signum","cs","chunkSize","intValue","substr","dMultiply","dAddOffset","testBit","bitwiseTo","shiftLeft","isProbablePrime","bitLength","nextBytes","op","f","lbit","cbit","changeBit","addTo","multiplyTo","squareTo","NullExp","Barrett","k1","g2","is1","clone","getLowestSetBit","ac","subtract","add","lowprimes","lplim","modInt","millerRabin","n1","shiftRight","modPow","modPowInt","BI_RC","rr","vv","mod","reduce","mp","invDigit","mpl","mph","um","mt2","u0","nNop","q3","mu","divide","multiplyUpperTo","multiplyLowerTo","Utf8Encode","str","replace","utftext","sha256","process","env","NODEJS","msg","crypto","createHash","update","digest","safe_add","lsw","X","R","Ch","Maj","Sigma0256","Sigma1256","Gamma0256","binarray","hex_tab","binb2hex","K","HASH","W","T1","T2","core_sha256","bin","str2binb","sha1","rotate_left","cvt_hex","val","blockstart","A","B","C","D","E","H0","H1","H2","H3","H4","msg_len","word_array","toLowerCase","md5","RotateLeft","lValue","iShiftBits","AddUnsigned","lX","lY","lX8","lY8","lX4","lY4","lResult","FF","F","GG","G","HH","H","II","I","WordToHex","lByte","lCount","WordToHexValue","WordToHexValue_temp","AA","BB","CC","DD","lWordCount","lMessageLength","lNumberOfWords_temp1","lNumberOfWords","lWordArray","lBytePosition","lByteCount","ConvertToWordArray","parseBigInt","pkcs1pad2","rng","RSAKey","N","parseInt","text","doPublic","P","Q","DP","DQ","Error","dmp1","dmq1","coeff","qs","ee","gcd","p1","q1","phi","multiply","modInverse","xp","xq","ctext","doPrivate","pkcs1unpad2","_rsasign_signString","_rsasign_signStringWithSHA1","_rsasign_signStringWithSHA256","_rsasign_verifyHexSignatureForMessage","_rsasign_verifyString","JSON","stringify","json","parse","rsa","setPrivateEx","toByteArray","ret","_RSASIGN_DIHEAD","_RSASIGN_HASHHEXFUNC","_rsasign_getHexPaddedDigestInfoForString","keySize","hashAlg","pmStrLen","sHashHex","hashFunc","sHead","sTail","sMid","fLen","biPaddedMessage","_rsasign_getHexDigestInfoFromSig","biSig","hN","hE","setPublic","_rsasign_getDecryptSignatureBI","_rsasign_getAlgNameAndHashFromHexDisgestInfo","hDigestInfo","algName","head","len","substring","sMsg","hSig","digestInfoAry","ff","_rsasign_verifySignatureWithArgs","base64Chars","magic","Init","tl","slop","bytes","unescape","encodeURIComponent","uriencoded","decodeURIComponent","escape","string2bytes","bytes2string","xor","IV","newBytes","padding","plaintext","exkey","ExpandKey","blocks","utf82bytes","pad16","encryptedBlocks","blockIV","tempBlock","prevBlock","blockXOR","Encrypt","ciphertext","b256to64","encryptedText","asciiText","b64to256","decryptedBlocks","Decrypt","depad","bytes2utf8","outstr","passphrase","bitlength","seedrandom","generate","rsakey","b16to64","publicKeyString","b64to16","split","publickeystring","signingkey","cipherblock","aeskey","generateAESKey","publickey","publicKeyFromString","encrypt","err","status","signString","sign","encryptAESCBC","cipher","decrypt","aeskeyBytes","decryptAESCBC","_confirm","signature","verifyString"],"mappings":"kSAyBaA,EAAa,CAExBC,KAAM,CACJ,GAAI,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,GAAI,EAAG,IAAK,GAAI,IAAK,IAAK,IAAK,IACtE,IAAK,IAAK,IAAK,IAAK,IAAK,GAAI,GAAI,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IACpE,IAAK,IAAK,IAAK,IAAK,GAAI,GAAI,GAAI,IAAK,IAAK,GAAI,IAAK,IAAK,IAAK,IAAK,IAAK,GACvE,GAAI,EAAG,IAAK,GAAI,IAAK,GAAI,IAAK,EAAG,IAAK,EAAG,GAAI,IAAK,IAAK,IAAK,GAAI,IAAK,IAAK,EAC1E,IAAK,GAAI,GAAI,GAAI,IAAK,GAAI,IAAK,GAAI,GAAI,IAAK,IAAK,GAAI,IAAK,GAAI,IAAK,GAAI,IACvE,EAAG,IAAK,GAAI,IAAK,IAAK,GAAI,IAAK,IAAK,IAAK,GAAI,GAAI,GAAI,GAAI,IAAK,IAAK,IAAK,IACxE,IAAK,GAAI,GAAI,GAAI,IAAK,GAAI,IAAK,EAAG,IAAK,GAAI,GAAI,IAAK,IAAK,GAAI,IAAK,GAAI,IACtE,IAAK,IAAK,GAAI,IAAK,IAAK,IAAK,IAAK,GAAI,GAAI,IAAK,IAAK,IAAK,IAAK,GAAI,GAAI,IACtE,GAAI,IAAK,GAAI,GAAI,IAAK,IAAK,IAAK,GAAI,IAAK,GAAI,GAAI,IAAK,GAAI,IAAK,GAAI,IAAK,GACxE,GAAI,IAAK,IAAK,GAAI,IAAK,IAAK,GAAI,IAAK,GAAI,GAAI,IAAK,IAAK,GAAI,GAAI,GAAI,GAAI,EACvE,GAAI,GAAI,IAAK,IAAK,IAAK,GAAI,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S,EAAExD,QACfiW,GAAOzS,EAAEkU,UAAU5X,EAAGA,EAAIiD,GAAK,KAC/BjD,GAAKiD,EAEP,OAAOkT,EAAMzS,EAAEkU,UAAU5X,EAAG0D,EAAExD"} \ No newline at end of file diff --git a/test/http.html b/test/http.html new file mode 100644 index 0000000..24a73f0 --- /dev/null +++ b/test/http.html @@ -0,0 +1,110 @@ + + + + + + + + + + + + + Vite App + + + diff --git a/test/sm2.js b/test/sm2.js new file mode 100644 index 0000000..e2a06f8 --- /dev/null +++ b/test/sm2.js @@ -0,0 +1,2102 @@ +window.sm2 = function(t) { + function i(r) { + if (e[r]) return e[r].exports; + var n = e[r] = { + i: r, + l: !1, + exports: {} + }; + return t[r].call(n.exports, n, n.exports, i), + n.l = !0, + n.exports + } + var e = {}; + return i.m = t, + i.c = e, + i.d = function(t, e, r) { + i.o(t, e) || Object.defineProperty(t, e, { + configurable: !1, + enumerable: !0, + get: r + }) + }, + i.n = function(t) { + var e = t && t.__esModule ? + function() { + return t. + default + }: + function() { + return t + }; + return i.d(e, "a", e), + e + }, + i.o = function(t, i) { + return Object.prototype.hasOwnProperty.call(t, i) + }, + i.p = "", + i(i.s = 3) +} ([function(t, i, e) { (function() { + function e(t, i, e) { + null != t && ("number" == typeof t ? this.fromNumber(t, i, e) : null == i && "string" != typeof t ? this.fromString(t, 256) : this.fromString(t, i)) + } + function r() { + return new e(null) + } + function n(t, i, e, r, n, s) { + for (; --s >= 0;) { + var o = i * this[t++] + e[r] + n; + n = Math.floor(o / 67108864), + e[r++] = 67108863 & o + } + return n + } + function s(t, i, e, r, n, s) { + for (var o = 32767 & i, + h = i >> 15; --s >= 0;) { + var u = 32767 & this[t], + a = this[t++] >> 15, + f = h * u + a * o; + u = o * u + ((32767 & f) << 15) + e[r] + (1073741823 & n), + n = (u >>> 30) + (f >>> 15) + h * a + (n >>> 30), + e[r++] = 1073741823 & u + } + return n + } + function o(t, i, e, r, n, s) { + for (var o = 16383 & i, + h = i >> 14; --s >= 0;) { + var u = 16383 & this[t], + a = this[t++] >> 14, + f = h * u + a * o; + u = o * u + ((16383 & f) << 14) + e[r] + n, + n = (u >> 28) + (f >> 14) + h * a, + e[r++] = 268435455 & u + } + return n + } + function h(t) { + return pi.charAt(t) + } + function u(t, i) { + var e = yi[t.charCodeAt(i)]; + return null == e ? -1 : e + } + function a(t) { + for (var i = this.t - 1; i >= 0; --i) t[i] = this[i]; + t.t = this.t, + t.s = this.s + } + function f(t) { + this.t = 1, + this.s = t < 0 ? -1 : 0, + t > 0 ? this[0] = t: t < -1 ? this[0] = t + this.DV: this.t = 0 + } + function l(t) { + var i = r(); + return i.fromInt(t), + i + } + function c(t, i) { + var r; + if (16 == i) r = 4; + else if (8 == i) r = 3; + else if (256 == i) r = 8; + else if (2 == i) r = 1; + else if (32 == i) r = 5; + else { + if (4 != i) return void this.fromRadix(t, i); + r = 2 + } + this.t = 0, + this.s = 0; + for (var n = t.length, + s = !1, + o = 0; --n >= 0;) { + var h = 8 == r ? 255 & t[n] : u(t, n); + h < 0 ? "-" == t.charAt(n) && (s = !0) : (s = !1, 0 == o ? this[this.t++] = h: o + r > this.DB ? (this[this.t - 1] |= (h & (1 << this.DB - o) - 1) << o, this[this.t++] = h >> this.DB - o) : this[this.t - 1] |= h << o, (o += r) >= this.DB && (o -= this.DB)) + } + 8 == r && 0 != (128 & t[0]) && (this.s = -1, o > 0 && (this[this.t - 1] |= (1 << this.DB - o) - 1 << o)), + this.clamp(), + s && e.ZERO.subTo(this, this) + } + function p() { + for (var t = this.s & this.DM; this.t > 0 && this[this.t - 1] == t;)--this.t + } + function y(t) { + if (this.s < 0) return "-" + this.negate().toString(t); + var i; + if (16 == t) i = 4; + else if (8 == t) i = 3; + else if (2 == t) i = 1; + else if (32 == t) i = 5; + else { + if (4 != t) return this.toRadix(t); + i = 2 + } + var e, r = (1 << i) - 1, + n = !1, + s = "", + o = this.t, + u = this.DB - o * this.DB % i; + if (o-->0) for (u < this.DB && (e = this[o] >> u) > 0 && (n = !0, s = h(e)); o >= 0;) u < i ? (e = (this[o] & (1 << u) - 1) << i - u, e |= this[--o] >> (u += this.DB - i)) : (e = this[o] >> (u -= i) & r, u <= 0 && (u += this.DB, --o)), + e > 0 && (n = !0), + n && (s += h(e)); + return n ? s: "0" + } + function v() { + var t = r(); + return e.ZERO.subTo(this, t), + t + } + function g() { + return this.s < 0 ? this.negate() : this + } + function m(t) { + var i = this.s - t.s; + if (0 != i) return i; + var e = this.t; + if (0 != (i = e - t.t)) return this.s < 0 ? -i: i; + for (; --e >= 0;) if (0 != (i = this[e] - t[e])) return i; + return 0 + } + function d(t) { + var i, e = 1; + return 0 != (i = t >>> 16) && (t = i, e += 16), + 0 != (i = t >> 8) && (t = i, e += 8), + 0 != (i = t >> 4) && (t = i, e += 4), + 0 != (i = t >> 2) && (t = i, e += 2), + 0 != (i = t >> 1) && (t = i, e += 1), + e + } + function T() { + return this.t <= 0 ? 0 : this.DB * (this.t - 1) + d(this[this.t - 1] ^ this.s & this.DM) + } + function b(t, i) { + var e; + for (e = this.t - 1; e >= 0; --e) i[e + t] = this[e]; + for (e = t - 1; e >= 0; --e) i[e] = 0; + i.t = this.t + t, + i.s = this.s + } + function F(t, i) { + for (var e = t; e < this.t; ++e) i[e - t] = this[e]; + i.t = Math.max(this.t - t, 0), + i.s = this.s + } + function B(t, i) { + var e, r = t % this.DB, + n = this.DB - r, + s = (1 << n) - 1, + o = Math.floor(t / this.DB), + h = this.s << r & this.DM; + for (e = this.t - 1; e >= 0; --e) i[e + o + 1] = this[e] >> n | h, + h = (this[e] & s) << r; + for (e = o - 1; e >= 0; --e) i[e] = 0; + i[o] = h, + i.t = this.t + o + 1, + i.s = this.s, + i.clamp() + } + function x(t, i) { + i.s = this.s; + var e = Math.floor(t / this.DB); + if (e >= this.t) return void(i.t = 0); + var r = t % this.DB, + n = this.DB - r, + s = (1 << r) - 1; + i[0] = this[e] >> r; + for (var o = e + 1; o < this.t; ++o) i[o - e - 1] |= (this[o] & s) << n, + i[o - e] = this[o] >> r; + r > 0 && (i[this.t - e - 1] |= (this.s & s) << n), + i.t = this.t - e, + i.clamp() + } + function w(t, i) { + for (var e = 0, + r = 0, + n = Math.min(t.t, this.t); e < n;) r += this[e] - t[e], + i[e++] = r & this.DM, + r >>= this.DB; + if (t.t < this.t) { + for (r -= t.s; e < this.t;) r += this[e], + i[e++] = r & this.DM, + r >>= this.DB; + r += this.s + } else { + for (r += this.s; e < t.t;) r -= t[e], + i[e++] = r & this.DM, + r >>= this.DB; + r -= t.s + } + i.s = r < 0 ? -1 : 0, + r < -1 ? i[e++] = this.DV + r: r > 0 && (i[e++] = r), + i.t = e, + i.clamp() + } + function S(t, i) { + var r = this.abs(), + n = t.abs(), + s = r.t; + for (i.t = s + n.t; --s >= 0;) i[s] = 0; + for (s = 0; s < n.t; ++s) i[s + r.t] = r.am(0, n[s], i, s, 0, r.t); + i.s = 0, + i.clamp(), + this.s != t.s && e.ZERO.subTo(i, i) + } + function k(t) { + for (var i = this.abs(), e = t.t = 2 * i.t; --e >= 0;) t[e] = 0; + for (e = 0; e < i.t - 1; ++e) { + var r = i.am(e, i[e], t, 2 * e, 0, 1); (t[e + i.t] += i.am(e + 1, 2 * i[e], t, 2 * e + 1, r, i.t - e - 1)) >= i.DV && (t[e + i.t] -= i.DV, t[e + i.t + 1] = 1) + } + t.t > 0 && (t[t.t - 1] += i.am(e, i[e], t, 2 * e, 0, 1)), + t.s = 0, + t.clamp() + } + function D(t, i, n) { + var s = t.abs(); + if (! (s.t <= 0)) { + var o = this.abs(); + if (o.t < s.t) return null != i && i.fromInt(0), + void(null != n && this.copyTo(n)); + null == n && (n = r()); + var h = r(), + u = this.s, + a = t.s, + f = this.DB - d(s[s.t - 1]); + f > 0 ? (s.lShiftTo(f, h), o.lShiftTo(f, n)) : (s.copyTo(h), o.copyTo(n)); + var l = h.t, + c = h[l - 1]; + if (0 != c) { + var p = c * (1 << this.F1) + (l > 1 ? h[l - 2] >> this.F2: 0), + y = this.FV / p, + v = (1 << this.F1) / p, + g = 1 << this.F2, + m = n.t, + T = m - l, + b = null == i ? r() : i; + for (h.dlShiftTo(T, b), n.compareTo(b) >= 0 && (n[n.t++] = 1, n.subTo(b, n)), e.ONE.dlShiftTo(l, b), b.subTo(h, h); h.t < l;) h[h.t++] = 0; + for (; --T >= 0;) { + var F = n[--m] == c ? this.DM: Math.floor(n[m] * y + (n[m - 1] + g) * v); + if ((n[m] += h.am(0, F, n, T, 0, l)) < F) for (h.dlShiftTo(T, b), n.subTo(b, n); n[m] < --F;) n.subTo(b, n) + } + null != i && (n.drShiftTo(l, i), u != a && e.ZERO.subTo(i, i)), + n.t = l, + n.clamp(), + f > 0 && n.rShiftTo(f, n), + u < 0 && e.ZERO.subTo(n, n) + } + } + } + function I(t) { + var i = r(); + return this.abs().divRemTo(t, null, i), + this.s < 0 && i.compareTo(e.ZERO) > 0 && t.subTo(i, i), + i + } + function E(t) { + this.m = t + } + function O(t) { + return t.s < 0 || t.compareTo(this.m) >= 0 ? t.mod(this.m) : t + } + function q(t) { + return t + } + function A(t) { + t.divRemTo(this.m, null, t) + } + function R(t, i, e) { + t.multiplyTo(i, e), + this.reduce(e) + } + function V(t, i) { + t.squareTo(i), + this.reduce(i) + } + function M() { + if (this.t < 1) return 0; + var t = this[0]; + if (0 == (1 & t)) return 0; + var i = 3 & t; + return i = i * (2 - (15 & t) * i) & 15, + i = i * (2 - (255 & t) * i) & 255, + i = i * (2 - ((65535 & t) * i & 65535)) & 65535, + i = i * (2 - t * i % this.DV) % this.DV, + i > 0 ? this.DV - i: -i + } + function _(t) { + this.m = t, + this.mp = t.invDigit(), + this.mpl = 32767 & this.mp, + this.mph = this.mp >> 15, + this.um = (1 << t.DB - 15) - 1, + this.mt2 = 2 * t.t + } + function C(t) { + var i = r(); + return t.abs().dlShiftTo(this.m.t, i), + i.divRemTo(this.m, null, i), + t.s < 0 && i.compareTo(e.ZERO) > 0 && this.m.subTo(i, i), + i + } + function L(t) { + var i = r(); + return t.copyTo(i), + this.reduce(i), + i + } + function P(t) { + for (; t.t <= this.mt2;) t[t.t++] = 0; + for (var i = 0; i < this.m.t; ++i) { + var e = 32767 & t[i], + r = e * this.mpl + ((e * this.mph + (t[i] >> 15) * this.mpl & this.um) << 15) & t.DM; + for (e = i + this.m.t, t[e] += this.m.am(0, r, t, i, 0, this.m.t); t[e] >= t.DV;) t[e] -= t.DV, + t[++e]++ + } + t.clamp(), + t.drShiftTo(this.m.t, t), + t.compareTo(this.m) >= 0 && t.subTo(this.m, t) + } + function H(t, i) { + t.squareTo(i), + this.reduce(i) + } + function N(t, i, e) { + t.multiplyTo(i, e), + this.reduce(e) + } + function U() { + return 0 == (this.t > 0 ? 1 & this[0] : this.s) + } + function z(t, i) { + if (t > 4294967295 || t < 1) return e.ONE; + var n = r(), + s = r(), + o = i.convert(this), + h = d(t) - 1; + for (o.copyTo(n); --h >= 0;) if (i.sqrTo(n, s), (t & 1 << h) > 0) i.mulTo(s, o, n); + else { + var u = n; + n = s, + s = u + } + return i.revert(n) + } + function j(t, i) { + var e; + return e = t < 256 || i.isEven() ? new E(i) : new _(i), + this.exp(t, e) + } + function X() { + var t = r(); + return this.copyTo(t), + t + } + function Z() { + if (this.s < 0) { + if (1 == this.t) return this[0] - this.DV; + if (0 == this.t) return - 1 + } else { + if (1 == this.t) return this[0]; + if (0 == this.t) return 0 + } + return (this[1] & (1 << 32 - this.DB) - 1) << this.DB | this[0] + } + function K() { + return 0 == this.t ? this.s: this[0] << 24 >> 24 + } + function G() { + return 0 == this.t ? this.s: this[0] << 16 >> 16 + } + function Y(t) { + return Math.floor(Math.LN2 * this.DB / Math.log(t)) + } + function W() { + return this.s < 0 ? -1 : this.t <= 0 || 1 == this.t && this[0] <= 0 ? 0 : 1 + } + function J(t) { + if (null == t && (t = 10), 0 == this.signum() || t < 2 || t > 36) return "0"; + var i = this.chunkSize(t), + e = Math.pow(t, i), + n = l(e), + s = r(), + o = r(), + h = ""; + for (this.divRemTo(n, s, o); s.signum() > 0;) h = (e + o.intValue()).toString(t).substr(1) + h, + s.divRemTo(n, s, o); + return o.intValue().toString(t) + h + } + function Q(t, i) { + this.fromInt(0), + null == i && (i = 10); + for (var r = this.chunkSize(i), n = Math.pow(i, r), s = !1, o = 0, h = 0, a = 0; a < t.length; ++a) { + var f = u(t, a); + f < 0 ? "-" == t.charAt(a) && 0 == this.signum() && (s = !0) : (h = i * h + f, ++o >= r && (this.dMultiply(n), this.dAddOffset(h, 0), o = 0, h = 0)) + } + o > 0 && (this.dMultiply(Math.pow(i, o)), this.dAddOffset(h, 0)), + s && e.ZERO.subTo(this, this) + } + function $(t, i, r) { + if ("number" == typeof i) if (t < 2) this.fromInt(1); + else for (this.fromNumber(t, r), this.testBit(t - 1) || this.bitwiseTo(e.ONE.shiftLeft(t - 1), ht, this), this.isEven() && this.dAddOffset(1, 0); ! this.isProbablePrime(i);) this.dAddOffset(2, 0), + this.bitLength() > t && this.subTo(e.ONE.shiftLeft(t - 1), this); + else { + var n = new Array, + s = 7 & t; + n.length = 1 + (t >> 3), + i.nextBytes(n), + s > 0 ? n[0] &= (1 << s) - 1 : n[0] = 0, + this.fromString(n, 256) + } + } + function tt() { + var t = this.t, + i = new Array; + i[0] = this.s; + var e, r = this.DB - t * this.DB % 8, + n = 0; + if (t-->0) for (r < this.DB && (e = this[t] >> r) != (this.s & this.DM) >> r && (i[n++] = e | this.s << this.DB - r); t >= 0;) r < 8 ? (e = (this[t] & (1 << r) - 1) << 8 - r, e |= this[--t] >> (r += this.DB - 8)) : (e = this[t] >> (r -= 8) & 255, r <= 0 && (r += this.DB, --t)), + 0 != (128 & e) && (e |= -256), + 0 == n && (128 & this.s) != (128 & e) && ++n, + (n > 0 || e != this.s) && (i[n++] = e); + return i + } + function it(t) { + return 0 == this.compareTo(t) + } + function et(t) { + return this.compareTo(t) < 0 ? this: t + } + function rt(t) { + return this.compareTo(t) > 0 ? this: t + } + function nt(t, i, e) { + var r, n, s = Math.min(t.t, this.t); + for (r = 0; r < s; ++r) e[r] = i(this[r], t[r]); + if (t.t < this.t) { + for (n = t.s & this.DM, r = s; r < this.t; ++r) e[r] = i(this[r], n); + e.t = this.t + } else { + for (n = this.s & this.DM, r = s; r < t.t; ++r) e[r] = i(n, t[r]); + e.t = t.t + } + e.s = i(this.s, t.s), + e.clamp() + } + function st(t, i) { + return t & i + } + function ot(t) { + var i = r(); + return this.bitwiseTo(t, st, i), + i + } + function ht(t, i) { + return t | i + } + function ut(t) { + var i = r(); + return this.bitwiseTo(t, ht, i), + i + } + function at(t, i) { + return t ^ i + } + function ft(t) { + var i = r(); + return this.bitwiseTo(t, at, i), + i + } + function lt(t, i) { + return t & ~i + } + function ct(t) { + var i = r(); + return this.bitwiseTo(t, lt, i), + i + } + function pt() { + for (var t = r(), i = 0; i < this.t; ++i) t[i] = this.DM & ~this[i]; + return t.t = this.t, + t.s = ~this.s, + t + } + function yt(t) { + var i = r(); + return t < 0 ? this.rShiftTo( - t, i) : this.lShiftTo(t, i), + i + } + function vt(t) { + var i = r(); + return t < 0 ? this.lShiftTo( - t, i) : this.rShiftTo(t, i), + i + } + function gt(t) { + if (0 == t) return - 1; + var i = 0; + return 0 == (65535 & t) && (t >>= 16, i += 16), + 0 == (255 & t) && (t >>= 8, i += 8), + 0 == (15 & t) && (t >>= 4, i += 4), + 0 == (3 & t) && (t >>= 2, i += 2), + 0 == (1 & t) && ++i, + i + } + function mt() { + for (var t = 0; t < this.t; ++t) if (0 != this[t]) return t * this.DB + gt(this[t]); + return this.s < 0 ? this.t * this.DB: -1 + } + function dt(t) { + for (var i = 0; 0 != t;) t &= t - 1, + ++i; + return i + } + function Tt() { + for (var t = 0, + i = this.s & this.DM, + e = 0; e < this.t; ++e) t += dt(this[e] ^ i); + return t + } + function bt(t) { + var i = Math.floor(t / this.DB); + return i >= this.t ? 0 != this.s: 0 != (this[i] & 1 << t % this.DB) + } + function Ft(t, i) { + var r = e.ONE.shiftLeft(t); + return this.bitwiseTo(r, i, r), + r + } + function Bt(t) { + return this.changeBit(t, ht) + } + function xt(t) { + return this.changeBit(t, lt) + } + function wt(t) { + return this.changeBit(t, at) + } + function St(t, i) { + for (var e = 0, + r = 0, + n = Math.min(t.t, this.t); e < n;) r += this[e] + t[e], + i[e++] = r & this.DM, + r >>= this.DB; + if (t.t < this.t) { + for (r += t.s; e < this.t;) r += this[e], + i[e++] = r & this.DM, + r >>= this.DB; + r += this.s + } else { + for (r += this.s; e < t.t;) r += t[e], + i[e++] = r & this.DM, + r >>= this.DB; + r += t.s + } + i.s = r < 0 ? -1 : 0, + r > 0 ? i[e++] = r: r < -1 && (i[e++] = this.DV + r), + i.t = e, + i.clamp() + } + function kt(t) { + var i = r(); + return this.addTo(t, i), + i + } + function Dt(t) { + var i = r(); + return this.subTo(t, i), + i + } + function It(t) { + var i = r(); + return this.multiplyTo(t, i), + i + } + function Et() { + var t = r(); + return this.squareTo(t), + t + } + function Ot(t) { + var i = r(); + return this.divRemTo(t, i, null), + i + } + function qt(t) { + var i = r(); + return this.divRemTo(t, null, i), + i + } + function At(t) { + var i = r(), + e = r(); + return this.divRemTo(t, i, e), + new Array(i, e) + } + function Rt(t) { + this[this.t] = this.am(0, t - 1, this, 0, 0, this.t), + ++this.t, + this.clamp() + } + function Vt(t, i) { + if (0 != t) { + for (; this.t <= i;) this[this.t++] = 0; + for (this[i] += t; this[i] >= this.DV;) this[i] -= this.DV, + ++i >= this.t && (this[this.t++] = 0), + ++this[i] + } + } + function Mt() {} + function _t(t) { + return t + } + function Ct(t, i, e) { + t.multiplyTo(i, e) + } + function Lt(t, i) { + t.squareTo(i) + } + function Pt(t) { + return this.exp(t, new Mt) + } + function Ht(t, i, e) { + var r = Math.min(this.t + t.t, i); + for (e.s = 0, e.t = r; r > 0;) e[--r] = 0; + var n; + for (n = e.t - this.t; r < n; ++r) e[r + this.t] = this.am(0, t[r], e, r, 0, this.t); + for (n = Math.min(t.t, i); r < n; ++r) this.am(0, t[r], e, r, 0, i - r); + e.clamp() + } + function Nt(t, i, e) {--i; + var r = e.t = this.t + t.t - i; + for (e.s = 0; --r >= 0;) e[r] = 0; + for (r = Math.max(i - this.t, 0); r < t.t; ++r) e[this.t + r - i] = this.am(i - r, t[r], e, 0, 0, this.t + r - i); + e.clamp(), + e.drShiftTo(1, e) + } + function Ut(t) { + this.r2 = r(), + this.q3 = r(), + e.ONE.dlShiftTo(2 * t.t, this.r2), + this.mu = this.r2.divide(t), + this.m = t + } + function zt(t) { + if (t.s < 0 || t.t > 2 * this.m.t) return t.mod(this.m); + if (t.compareTo(this.m) < 0) return t; + var i = r(); + return t.copyTo(i), + this.reduce(i), + i + } + function jt(t) { + return t + } + function Xt(t) { + for (t.drShiftTo(this.m.t - 1, this.r2), t.t > this.m.t + 1 && (t.t = this.m.t + 1, t.clamp()), this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3), this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); t.compareTo(this.r2) < 0;) t.dAddOffset(1, this.m.t + 1); + for (t.subTo(this.r2, t); t.compareTo(this.m) >= 0;) t.subTo(this.m, t) + } + function Zt(t, i) { + t.squareTo(i), + this.reduce(i) + } + function Kt(t, i, e) { + t.multiplyTo(i, e), + this.reduce(e) + } + function Gt(t, i) { + var e, n, s = t.bitLength(), + o = l(1); + if (s <= 0) return o; + e = s < 18 ? 1 : s < 48 ? 3 : s < 144 ? 4 : s < 768 ? 5 : 6, + n = s < 8 ? new E(i) : i.isEven() ? new Ut(i) : new _(i); + var h = new Array, + u = 3, + a = e - 1, + f = (1 << e) - 1; + if (h[1] = n.convert(this), e > 1) { + var c = r(); + for (n.sqrTo(h[1], c); u <= f;) h[u] = r(), + n.mulTo(c, h[u - 2], h[u]), + u += 2 + } + var p, y, v = t.t - 1, + g = !0, + m = r(); + for (s = d(t[v]) - 1; v >= 0;) { + for (s >= a ? p = t[v] >> s - a & f: (p = (t[v] & (1 << s + 1) - 1) << a - s, v > 0 && (p |= t[v - 1] >> this.DB + s - a)), u = e; 0 == (1 & p);) p >>= 1, + --u; + if ((s -= u) < 0 && (s += this.DB, --v), g) h[p].copyTo(o), + g = !1; + else { + for (; u > 1;) n.sqrTo(o, m), + n.sqrTo(m, o), + u -= 2; + u > 0 ? n.sqrTo(o, m) : (y = o, o = m, m = y), + n.mulTo(m, h[p], o) + } + for (; v >= 0 && 0 == (t[v] & 1 << s);) n.sqrTo(o, m), + y = o, + o = m, + m = y, + --s < 0 && (s = this.DB - 1, --v) + } + return n.revert(o) + } + function Yt(t) { + var i = this.s < 0 ? this.negate() : this.clone(), + e = t.s < 0 ? t.negate() : t.clone(); + if (i.compareTo(e) < 0) { + var r = i; + i = e, + e = r + } + var n = i.getLowestSetBit(), + s = e.getLowestSetBit(); + if (s < 0) return i; + for (n < s && (s = n), s > 0 && (i.rShiftTo(s, i), e.rShiftTo(s, e)); i.signum() > 0;)(n = i.getLowestSetBit()) > 0 && i.rShiftTo(n, i), + (n = e.getLowestSetBit()) > 0 && e.rShiftTo(n, e), + i.compareTo(e) >= 0 ? (i.subTo(e, i), i.rShiftTo(1, i)) : (e.subTo(i, e), e.rShiftTo(1, e)); + return s > 0 && e.lShiftTo(s, e), + e + } + function Wt(t) { + if (t <= 0) return 0; + var i = this.DV % t, + e = this.s < 0 ? t - 1 : 0; + if (this.t > 0) if (0 == i) e = this[0] % t; + else for (var r = this.t - 1; r >= 0; --r) e = (i * e + this[r]) % t; + return e + } + function Jt(t) { + var i = t.isEven(); + if (this.isEven() && i || 0 == t.signum()) return e.ZERO; + for (var r = t.clone(), n = this.clone(), s = l(1), o = l(0), h = l(0), u = l(1); 0 != r.signum();) { + for (; r.isEven();) r.rShiftTo(1, r), + i ? (s.isEven() && o.isEven() || (s.addTo(this, s), o.subTo(t, o)), s.rShiftTo(1, s)) : o.isEven() || o.subTo(t, o), + o.rShiftTo(1, o); + for (; n.isEven();) n.rShiftTo(1, n), + i ? (h.isEven() && u.isEven() || (h.addTo(this, h), u.subTo(t, u)), h.rShiftTo(1, h)) : u.isEven() || u.subTo(t, u), + u.rShiftTo(1, u); + r.compareTo(n) >= 0 ? (r.subTo(n, r), i && s.subTo(h, s), o.subTo(u, o)) : (n.subTo(r, n), i && h.subTo(s, h), u.subTo(o, u)) + } + return 0 != n.compareTo(e.ONE) ? e.ZERO: u.compareTo(t) >= 0 ? u.subtract(t) : u.signum() < 0 ? (u.addTo(t, u), u.signum() < 0 ? u.add(t) : u) : u + } + function Qt(t) { + var i, e = this.abs(); + if (1 == e.t && e[0] <= vi[vi.length - 1]) { + for (i = 0; i < vi.length; ++i) if (e[0] == vi[i]) return ! 0; + return ! 1 + } + if (e.isEven()) return ! 1; + for (i = 1; i < vi.length;) { + for (var r = vi[i], n = i + 1; n < vi.length && r < gi;) r *= vi[n++]; + for (r = e.modInt(r); i < n;) if (r % vi[i++] == 0) return ! 1 + } + return e.millerRabin(t) + } + function $t(t) { + var i = this.subtract(e.ONE), + n = i.getLowestSetBit(); + if (n <= 0) return ! 1; + var s = i.shiftRight(n); (t = t + 1 >> 1) > vi.length && (t = vi.length); + for (var o = r(), h = 0; h < t; ++h) { + o.fromInt(vi[Math.floor(Math.random() * vi.length)]); + var u = o.modPow(s, this); + if (0 != u.compareTo(e.ONE) && 0 != u.compareTo(i)) { + for (var a = 1; a++> 8 & 255, + di[Ti++] ^= t >> 16 & 255, + di[Ti++] ^= t >> 24 & 255, + Ti >= xi && (Ti -= xi) + } + function ii() { + ti((new Date).getTime()) + } + function ei() { + if (null == mi) { + for (ii(), mi = ui(), mi.init(di), Ti = 0; Ti < di.length; ++Ti) di[Ti] = 0; + Ti = 0 + } + return mi.next() + } + function ri(t) { + var i; + for (i = 0; i < t.length; ++i) t[i] = ei() + } + function ni() {} + function si() { + this.i = 0, + this.j = 0, + this.S = new Array + } + function oi(t) { + var i, e, r; + for (i = 0; i < 256; ++i) this.S[i] = i; + for (e = 0, i = 0; i < 256; ++i) e = e + this.S[i] + t[i % t.length] & 255, + r = this.S[i], + this.S[i] = this.S[e], + this.S[e] = r; + this.i = 0, + this.j = 0 + } + function hi() { + var t; + return this.i = this.i + 1 & 255, + this.j = this.j + this.S[this.i] & 255, + t = this.S[this.i], + this.S[this.i] = this.S[this.j], + this.S[this.j] = t, + this.S[t + this.S[this.i] & 255] + } + function ui() { + return new si + } + var ai, fi = "undefined" != typeof navigator; + fi && "Microsoft Internet Explorer" == navigator.appName ? (e.prototype.am = s, ai = 30) : fi && "Netscape" != navigator.appName ? (e.prototype.am = n, ai = 26) : (e.prototype.am = o, ai = 28), + e.prototype.DB = ai, + e.prototype.DM = (1 << ai) - 1, + e.prototype.DV = 1 << ai; + e.prototype.FV = Math.pow(2, 52), + e.prototype.F1 = 52 - ai, + e.prototype.F2 = 2 * ai - 52; + var li, ci, pi = "0123456789abcdefghijklmnopqrstuvwxyz", + yi = new Array; + for (li = "0".charCodeAt(0), ci = 0; ci <= 9; ++ci) yi[li++] = ci; + for (li = "a".charCodeAt(0), ci = 10; ci < 36; ++ci) yi[li++] = ci; + for (li = "A".charCodeAt(0), ci = 10; ci < 36; ++ci) yi[li++] = ci; + E.prototype.convert = O, + E.prototype.revert = q, + E.prototype.reduce = A, + E.prototype.mulTo = R, + E.prototype.sqrTo = V, + _.prototype.convert = C, + _.prototype.revert = L, + _.prototype.reduce = P, + _.prototype.mulTo = N, + _.prototype.sqrTo = H, + e.prototype.copyTo = a, + e.prototype.fromInt = f, + e.prototype.fromString = c, + e.prototype.clamp = p, + e.prototype.dlShiftTo = b, + e.prototype.drShiftTo = F, + e.prototype.lShiftTo = B, + e.prototype.rShiftTo = x, + e.prototype.subTo = w, + e.prototype.multiplyTo = S, + e.prototype.squareTo = k, + e.prototype.divRemTo = D, + e.prototype.invDigit = M, + e.prototype.isEven = U, + e.prototype.exp = z, + e.prototype.toString = y, + e.prototype.negate = v, + e.prototype.abs = g, + e.prototype.compareTo = m, + e.prototype.bitLength = T, + e.prototype.mod = I, + e.prototype.modPowInt = j, + e.ZERO = l(0), + e.ONE = l(1), + Mt.prototype.convert = _t, + Mt.prototype.revert = _t, + Mt.prototype.mulTo = Ct, + Mt.prototype.sqrTo = Lt, + Ut.prototype.convert = zt, + Ut.prototype.revert = jt, + Ut.prototype.reduce = Xt, + Ut.prototype.mulTo = Kt, + Ut.prototype.sqrTo = Zt; + var vi = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997], + gi = (1 << 26) / vi[vi.length - 1]; + e.prototype.chunkSize = Y, + e.prototype.toRadix = J, + e.prototype.fromRadix = Q, + e.prototype.fromNumber = $, + e.prototype.bitwiseTo = nt, + e.prototype.changeBit = Ft, + e.prototype.addTo = St, + e.prototype.dMultiply = Rt, + e.prototype.dAddOffset = Vt, + e.prototype.multiplyLowerTo = Ht, + e.prototype.multiplyUpperTo = Nt, + e.prototype.modInt = Wt, + e.prototype.millerRabin = $t, + e.prototype.clone = X, + e.prototype.intValue = Z, + e.prototype.byteValue = K, + e.prototype.shortValue = G, + e.prototype.signum = W, + e.prototype.toByteArray = tt, + e.prototype.equals = it, + e.prototype.min = et, + e.prototype.max = rt, + e.prototype.and = ot, + e.prototype.or = ut, + e.prototype.xor = ft, + e.prototype.andNot = ct, + e.prototype.not = pt, + e.prototype.shiftLeft = yt, + e.prototype.shiftRight = vt, + e.prototype.getLowestSetBit = mt, + e.prototype.bitCount = Tt, + e.prototype.testBit = bt, + e.prototype.setBit = Bt, + e.prototype.clearBit = xt, + e.prototype.flipBit = wt, + e.prototype.add = kt, + e.prototype.subtract = Dt, + e.prototype.multiply = It, + e.prototype.divide = Ot, + e.prototype.remainder = qt, + e.prototype.divideAndRemainder = At, + e.prototype.modPow = Gt, + e.prototype.modInverse = Jt, + e.prototype.pow = Pt, + e.prototype.gcd = Yt, + e.prototype.isProbablePrime = Qt, + e.prototype.square = Et, + e.prototype.Barrett = Ut; + var mi, di, Ti; + if (null == di) { + di = new Array, + Ti = 0; + var bi; + if ("undefined" != typeof window && window.crypto) if (window.crypto.getRandomValues) { + var Fi = new Uint8Array(32); + for (window.crypto.getRandomValues(Fi), bi = 0; bi < 32; ++bi) di[Ti++] = Fi[bi] + } else if ("Netscape" == navigator.appName && navigator.appVersion < "5") { + var Bi = window.crypto.random(32); + for (bi = 0; bi < Bi.length; ++bi) di[Ti++] = 255 & Bi.charCodeAt(bi) + } + for (; Ti < xi;) bi = Math.floor(65536 * Math.random()), + di[Ti++] = bi >>> 8, + di[Ti++] = 255 & bi; + Ti = 0, + ii() + } + ni.prototype.nextBytes = ri, + si.prototype.init = oi, + si.prototype.next = hi; + var xi = 256; + i = t.exports = { + default: + e, + BigInteger: e, + SecureRandom: ni + } + }).call(this) +}, +function(t, i, e) { + "use strict"; + function r() { + return T + } + function n() { + var t = new p("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF", 16), + i = new p("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC", 16), + e = new p("28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93", 16), + r = new g(t, i, e); + return { + curve: r, + G: r.decodePointHex("0432C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0"), + n: new p("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123", 16) + } + } + function s() { + var t = new p(F.bitLength(), m).mod(F.subtract(p.ONE)).add(p.ONE), + i = u(t.toString(16), 64), + e = b.multiply(t); + return { + privateKey: i, + publicKey: "04" + u(e.getX().toBigInteger().toString(16), 64) + u(e.getY().toBigInteger().toString(16), 64) + } + } + function o(t) { + t = unescape(encodeURIComponent(t)); + for (var i = t.length, + e = [], r = 0; r < i; r++) e[r >>> 2] |= (255 & t.charCodeAt(r)) << 24 - r % 4 * 8; + for (var n = [], s = 0; s < i; s++) { + var o = e[s >>> 2] >>> 24 - s % 4 * 8 & 255; + n.push((o >>> 4).toString(16)), + n.push((15 & o).toString(16)) + } + return n.join("") + } + function h(t) { + return Array.prototype.map.call(new Uint8Array(t), + function(t) { + return ("00" + t.toString(16)).slice( - 2) + }).join("") + } + function u(t, i) { + return t.length >= i ? t: new Array(i - t.length + 1).join("0") + t + } + function a(t) { + for (var i = [], e = 0, r = 0; r < 2 * t.length; r += 2) i[r >>> 3] |= parseInt(t[e], 10) << 24 - r % 8 * 4, + e++; + for (var n = [], s = 0; s < t.length; s++) { + var o = i[s >>> 2] >>> 24 - s % 4 * 8 & 255; + n.push((o >>> 4).toString(16)), + n.push((15 & o).toString(16)) + } + return n.join("") + } + function f(t) { + for (var i = [], e = 0, r = 0; r < 2 * t.length; r += 2) i[r >>> 3] |= parseInt(t[e], 10) << 24 - r % 8 * 4, + e++; + try { + for (var n = [], s = 0; s < t.length; s++) { + var o = i[s >>> 2] >>> 24 - s % 4 * 8 & 255; + n.push(String.fromCharCode(o)) + } + return decodeURIComponent(escape(n.join(""))) + } catch(t) { + throw new Error("Malformed UTF-8 data") + } + } + function l(t) { + var i = [], + e = t.length; + e % 2 != 0 && (t = u(t, e + 1)), + e = t.length; + for (var r = 0; r < e; r += 2) i.push(parseInt(t.substr(r, 2), 16)); + return i + } + var c = e(0), + p = c.BigInteger, + y = c.SecureRandom, + v = e(5), + g = v.ECCurveFp, + m = new y, + d = n(), + T = d.curve, + b = d.G, + F = d.n; + t.exports = { + getGlobalCurve: r, + generateEcparam: n, + generateKeyPairHex: s, + parseUtf8StringToHex: o, + parseArrayBufferToHex: h, + leftPad: u, + arrayToHex: a, + arrayToUtf8: f, + hexToArray: l + } +}, +function(t, i, e) { + "use strict"; + function r(t, i) { + if (! (t instanceof i)) throw new TypeError("Cannot call a class as a function") + } + var n = function() { + function t(t, i) { + for (var e = 0; e < i.length; e++) { + var r = i[e]; + r.enumerable = r.enumerable || !1, + r.configurable = !0, + "value" in r && (r.writable = !0), + Object.defineProperty(t, r.key, r) + } + } + return function(i, e, r) { + return e && t(i.prototype, e), + r && t(i, r), + i + } + } (), + s = e(0), + o = s.BigInteger, + h = e(1), + u = function(t, i, e, r, n) { + for (var s = 0; s < n; s++) e[r + s] = t[i + s] + }, + a = { + minValue: -parseInt("10000000000000000000000000000000", 2), + maxValue: parseInt("1111111111111111111111111111111", 2), + parse: function(t) { + if (t < this.minValue) { + for (var i = new Number( - t), e = i.toString(2), r = e.substr(e.length - 31, 31), n = "", s = 0; s < r.length; s++) { + n += "0" == r.substr(s, 1) ? "1": "0" + } + return parseInt(n, 2) + 1 + } + if (t > this.maxValue) { + for (var o = Number(t), h = o.toString(2), u = h.substr(h.length - 31, 31), a = "", f = 0; f < u.length; f++) { + a += "0" == u.substr(f, 1) ? "1": "0" + } + return - (parseInt(a, 2) + 1) + } + return t + }, + parseByte: function(t) { + if (t < 0) { + for (var i = new Number( - t), e = i.toString(2), r = e.substr(e.length - 8, 8), n = "", s = 0; s < r.length; s++) { + n += "0" == r.substr(s, 1) ? "1": "0" + } + return parseInt(n, 2) + 1 + } + if (t > 255) { + var o = Number(t), + h = o.toString(2); + return parseInt(h.substr(h.length - 8, 8), 2) + } + return t + } + }, + f = function() { + function t() { + r(this, t), + this.xBuf = new Array, + this.xBufOff = 0, + this.byteCount = 0, + this.DIGEST_LENGTH = 32, + this.v0 = [1937774191, 1226093241, 388252375, 3666478592, 2842636476, 372324522, 3817729613, 2969243214], + this.v0 = [1937774191, 1226093241, 388252375, -628488704, -1452330820, 372324522, -477237683, -1325724082], + this.v = new Array(8), + this.v_ = new Array(8), + this.X0 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + this.X = new Array(68), + this.xOff = 0, + this.T_00_15 = 2043430169, + this.T_16_63 = 2055708042, + arguments.length > 0 ? this.initDigest(arguments[0]) : this.init() + } + return n(t, [{ + key: "init", + value: function() { + this.xBuf = new Array(4), + this.reset() + } + }, + { + key: "initDigest", + value: function(t) { + this.xBuf = [].concat(t.xBuf), + this.xBufOff = t.xBufOff, + this.byteCount = t.byteCount, + u(t.X, 0, this.X, 0, t.X.length), + this.xOff = t.xOff, + u(t.v, 0, this.v, 0, t.v.length) + } + }, + { + key: "getDigestSize", + value: function() { + return this.DIGEST_LENGTH + } + }, + { + key: "reset", + value: function() { + this.byteCount = 0, + this.xBufOff = 0; + for (var t in this.xBuf) this.xBuf[t] = null; + u(this.v0, 0, this.v, 0, this.v0.length), + this.xOff = 0, + u(this.X0, 0, this.X, 0, this.X0.length) + } + }, + { + key: "processBlock", + value: function() { + var t = void 0, + i = this.X, + e = new Array(64); + for (t = 16; t < 68; t++) i[t] = this.p1(i[t - 16] ^ i[t - 9] ^ this.rotate(i[t - 3], 15)) ^ this.rotate(i[t - 13], 7) ^ i[t - 6]; + for (t = 0; t < 64; t++) e[t] = i[t] ^ i[t + 4]; + var r = this.v, + n = this.v_; + u(r, 0, n, 0, this.v0.length); + var s = void 0, + o = void 0, + h = void 0, + f = void 0, + l = void 0; + for (t = 0; t < 16; t++) l = this.rotate(n[0], 12), + s = a.parse(a.parse(l + n[4]) + this.rotate(this.T_00_15, t)), + s = this.rotate(s, 7), + o = s ^ l, + h = a.parse(a.parse(this.ff_00_15(n[0], n[1], n[2]) + n[3]) + o) + e[t], + f = a.parse(a.parse(this.gg_00_15(n[4], n[5], n[6]) + n[7]) + s) + i[t], + n[3] = n[2], + n[2] = this.rotate(n[1], 9), + n[1] = n[0], + n[0] = h, + n[7] = n[6], + n[6] = this.rotate(n[5], 19), + n[5] = n[4], + n[4] = this.p0(f); + for (t = 16; t < 64; t++) l = this.rotate(n[0], 12), + s = a.parse(a.parse(l + n[4]) + this.rotate(this.T_16_63, t)), + s = this.rotate(s, 7), + o = s ^ l, + h = a.parse(a.parse(this.ff_16_63(n[0], n[1], n[2]) + n[3]) + o) + e[t], + f = a.parse(a.parse(this.gg_16_63(n[4], n[5], n[6]) + n[7]) + s) + i[t], + n[3] = n[2], + n[2] = this.rotate(n[1], 9), + n[1] = n[0], + n[0] = h, + n[7] = n[6], + n[6] = this.rotate(n[5], 19), + n[5] = n[4], + n[4] = this.p0(f); + for (t = 0; t < 8; t++) r[t] ^= a.parse(n[t]); + this.xOff = 0, + u(this.X0, 0, this.X, 0, this.X0.length) + } + }, + { + key: "processWord", + value: function(t, i) { + var e = t[i] << 24; + e |= (255 & t[++i]) << 16, + e |= (255 & t[++i]) << 8, + e |= 255 & t[++i], + this.X[this.xOff] = e, + 16 == ++this.xOff && this.processBlock() + } + }, + { + key: "processLength", + value: function(t) { + this.xOff > 14 && this.processBlock(), + this.X[14] = this.urShiftLong(t, 32), + this.X[15] = 4294967295 & t + } + }, + { + key: "intToBigEndian", + value: function(t, i, e) { + i[e] = a.parseByte(this.urShift(t, 24)), + i[++e] = a.parseByte(this.urShift(t, 16)), + i[++e] = a.parseByte(this.urShift(t, 8)), + i[++e] = a.parseByte(t) + } + }, + { + key: "doFinal", + value: function(t, i) { + this.finish(); + for (var e = 0; e < 8; e++) this.intToBigEndian(this.v[e], t, i + 4 * e); + return this.reset(), + this.DIGEST_LENGTH + } + }, + { + key: "update", + value: function(t) { + this.xBuf[this.xBufOff++] = t, + this.xBufOff == this.xBuf.length && (this.processWord(this.xBuf, 0), this.xBufOff = 0), + this.byteCount++ + } + }, + { + key: "blockUpdate", + value: function(t, i, e) { + for (; 0 != this.xBufOff && e > 0;) this.update(t[i]), + i++, + e--; + for (; e > this.xBuf.length;) this.processWord(t, i), + i += this.xBuf.length, + e -= this.xBuf.length, + this.byteCount += this.xBuf.length; + for (; e > 0;) this.update(t[i]), + i++, + e-- + } + }, + { + key: "finish", + value: function() { + var t = this.byteCount << 3; + for (this.update(128); 0 != this.xBufOff;) this.update(0); + this.processLength(t), + this.processBlock() + } + }, + { + key: "rotate", + value: function(t, i) { + return t << i | this.urShift(t, 32 - i) + } + }, + { + key: "p0", + value: function(t) { + return t ^ this.rotate(t, 9) ^ this.rotate(t, 17) + } + }, + { + key: "p1", + value: function(t) { + return t ^ this.rotate(t, 15) ^ this.rotate(t, 23) + } + }, + { + key: "ff_00_15", + value: function(t, i, e) { + return t ^ i ^ e + } + }, + { + key: "ff_16_63", + value: function(t, i, e) { + return t & i | t & e | i & e + } + }, + { + key: "gg_00_15", + value: function(t, i, e) { + return t ^ i ^ e + } + }, + { + key: "gg_16_63", + value: function(t, i, e) { + return t & i | ~t & e + } + }, + { + key: "urShift", + value: function(t, i) { + return (t > a.maxValue || t < a.minValue) && (t = a.parse(t)), + t >= 0 ? t >> i: (t >> i) + (2 << ~i) + } + }, + { + key: "urShiftLong", + value: function(t, i) { + var e = void 0, + r = new o; + if (r.fromInt(t), r.signum() >= 0) e = r.shiftRight(i).intValue(); + else { + var n = new o; + n.fromInt(2); + var s = ~i, + h = ""; + if (s < 0) { + for (var u = 64 + s, + a = 0; a < u; a++) h += "0"; + var f = new o; + f.fromInt(t >> i); + var l = new o("10" + h, 2); + h = l.toRadix(10); + e = l.add(f).toRadix(10) + } else h = n.shiftLeft(~i).intValue(), + e = (t >> i) + h + } + return e + } + }, + { + key: "getZ", + value: function(t, i) { + var e = h.parseUtf8StringToHex("1234567812345678"), + r = 4 * e.length; + this.update(r >> 8 & 255), + this.update(255 & r); + var n = h.hexToArray(e); + this.blockUpdate(n, 0, n.length); + var s = h.hexToArray(t.curve.a.toBigInteger().toRadix(16)), + o = h.hexToArray(t.curve.b.toBigInteger().toRadix(16)), + u = h.hexToArray(t.getX().toBigInteger().toRadix(16)), + a = h.hexToArray(t.getY().toBigInteger().toRadix(16)), + f = h.hexToArray(i.substr(0, 64)), + l = h.hexToArray(i.substr(64, 64)); + this.blockUpdate(s, 0, s.length), + this.blockUpdate(o, 0, o.length), + this.blockUpdate(u, 0, u.length), + this.blockUpdate(a, 0, a.length), + this.blockUpdate(f, 0, f.length), + this.blockUpdate(l, 0, l.length); + var c = new Array(this.getDigestSize()); + return this.doFinal(c, 0), + c + } + }]), + t + } (); + t.exports = f +}, +function(t, i, e) { + "use strict"; + function r(t, i) { + var e = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 1, + r = new g; + t = m.hexToArray(m.parseUtf8StringToHex(t)), + i.length > 128 && (i = i.substr(i.length - 128)); + var n = i.substr(0, 64), + s = i.substr(64); + i = r.createPoint(n, s); + var o = r.initEncipher(i); + r.encryptBlock(t); + var h = m.arrayToHex(t), + u = new Array(32); + return r.doFinal(u), + u = m.arrayToHex(u), + e === B ? o + h + u: o + u + h + } + function n(t, i) { + var e = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 1, + r = new g; + i = new l(i, 16); + var n = t.substr(0, 64), + s = t.substr(0 + n.length, 64), + o = n.length + s.length, + h = t.substr(o, 64), + u = t.substr(o + 64); + e === B && (h = t.substr(t.length - 64), u = t.substr(o, t.length - o - 64)); + var a = m.hexToArray(u), + f = r.createPoint(n, s); + r.initDecipher(i, f), + r.decryptBlock(a); + var c = new Array(32); + if (r.doFinal(c), m.arrayToHex(c) === h) return m.arrayToUtf8(a); + return "" + } + function s(t, i) { + var e = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, + r = e.pointPool, + n = e.der, + s = e.hash, + o = e.publicKey, + f = "string" == typeof t ? m.parseUtf8StringToHex(t) : m.parseArrayBufferToHex(t); + s && (o = o || u(i), f = h(f, o)); + var c = new l(i, 16), + y = new l(f, 16), + v = null, + g = null, + d = null; + do { + do { + var T = void 0; + T = r && r.length ? r.pop() : a(), v = T.k, g = y.add(T.x1).mod(F) + } while ( g . equals ( l . ZERO ) || g.add(v).equals(F)); + d = c.add(l.ONE).modInverse(F).multiply(v.subtract(g.multiply(c))).mod(F) + } while ( d . equals ( l . ZERO )); + return n ? p(g, d) : m.leftPad(g.toString(16), 64) + m.leftPad(d.toString(16), 64) + } + function o(t, i, e) { + var r = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}, + n = r.der, + s = r.hash, + o = "string" == typeof t ? m.parseUtf8StringToHex(t) : m.parseArrayBufferToHex(t); + s && (o = h(o, e)); + var u = void 0, + a = void 0; + if (n) { + var f = y(i); + u = f.r, + a = f.s + } else u = new l(i.substring(0, 64), 16), + a = new l(i.substring(64), 16); + var c = b.decodePointHex(e), + p = new l(o, 16), + v = u.add(a).mod(F); + if (v.equals(l.ZERO)) return ! 1; + var g = T.multiply(a).add(c.multiply(v)), + d = p.add(g.getX().toBigInteger()).mod(F); + return u.equals(d) + } + function h(t, i) { + var e = new v, + r = (new v).getZ(T, i.substr(2, 128)), + n = m.hexToArray(m.arrayToHex(r).toString()), + s = t, + o = m.hexToArray(s), + h = new Array(e.getDigestSize()); + return e.blockUpdate(n, 0, n.length), + e.blockUpdate(o, 0, o.length), + e.doFinal(h, 0), + m.arrayToHex(h).toString() + } + function u(t) { + var i = T.multiply(new l(t, 16)); + return "04" + m.leftPad(i.getX().toBigInteger().toString(16), 64) + m.leftPad(i.getY().toBigInteger().toString(16), 64) + } + function a() { + var t = m.generateKeyPairHex(), + i = b.decodePointHex(t.publicKey); + return t.k = new l(t.privateKey, 16), + t.x1 = i.getX().toBigInteger(), + t + } + var f = e(0), + l = f.BigInteger, + c = e(4), + p = c.encodeDer, + y = c.decodeDer, + v = e(2), + g = e(6), + m = e(1), + d = m.generateEcparam(), + T = d.G, + b = d.curve, + F = d.n, + B = 0; + t.exports = { + generateKeyPairHex: m.generateKeyPairHex, + doEncrypt: r, + doDecrypt: n, + doSignature: s, + doVerifySignature: o, + getPoint: a + } +}, +function(t, i, e) { + "use strict"; + function r(t, i) { + if (!t) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return ! i || "object" != typeof i && "function" != typeof i ? t: i + } + function n(t, i) { + if ("function" != typeof i && null !== i) throw new TypeError("Super expression must either be null or a function, not " + typeof i); + t.prototype = Object.create(i && i.prototype, { + constructor: { + value: t, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), + i && (Object.setPrototypeOf ? Object.setPrototypeOf(t, i) : t.__proto__ = i) + } + function s(t, i) { + if (! (t instanceof i)) throw new TypeError("Cannot call a class as a function") + } + function o(t) { + var i = t.toString(16); + if ("-" !== i.substr(0, 1)) i.length % 2 == 1 ? i = "0" + i: i.match(/^[0-7]/) || (i = "00" + i); + else { + var e = i.substr(1), + r = e.length; + r % 2 == 1 ? r += 1 : i.match(/^[0-7]/) || (r += 2); + for (var n = "", + s = 0; s < r; s++) n += "f"; + i = new g(n, 16).xor(t).add(g.ONE).toString(16).replace(/^-/, "") + } + return i + } + function h(t, i) { + if ("8" !== t.substring(i + 2, i + 3)) return 1; + var e = parseInt(t.substring(i + 3, i + 4)); + return 0 === e ? -1 : 0 < e && e < 10 ? e + 1 : -2 + } + function u(t, i) { + var e = h(t, i); + return e < 1 ? "": t.substring(i + 2, i + 2 + 2 * e) + } + function a(t, i) { + var e = u(t, i); + if ("" === e) return - 1; + var r = void 0; + return r = parseInt(e.substring(0, 1)) < 8 ? new g(e, 16) : new g(e.substring(2), 16), + r.intValue() + } + function f(t, i) { + var e = h(t, i); + return e < 0 ? l_len: i + 2 * (e + 1) + } + function l(t, i) { + var e = f(t, i), + r = a(t, i); + return t.substring(e, e + 2 * r) + } + function c(t, i) { + return f(t, i) + 2 * a(t, i) + } + function p(t, i) { + var e = [], + r = f(t, i); + e.push(r); + for (var n = a(t, i), s = r, o = 0;;) { + var h = c(t, s); + if (null === h || h - r >= 2 * n) break; + if (o >= 200) break; + e.push(h), + s = h, + o++ + } + return e + } + var y = function() { + function t(t, i) { + for (var e = 0; e < i.length; e++) { + var r = i[e]; + r.enumerable = r.enumerable || !1, + r.configurable = !0, + "value" in r && (r.writable = !0), + Object.defineProperty(t, r.key, r) + } + } + return function(i, e, r) { + return e && t(i.prototype, e), + r && t(i, r), + i + } + } (), + v = e(0), + g = v.BigInteger, + m = function() { + function t() { + s(this, t), + this.isModified = !0, + this.hTLV = null, + this.hT = "00", + this.hL = "00", + this.hV = "" + } + return y(t, [{ + key: "getLengthHexFromValue", + value: function() { + var t = this.hV.length / 2, + i = t.toString(16); + return i.length % 2 == 1 && (i = "0" + i), + t < 128 ? i: (128 + i.length / 2).toString(16) + i + } + }, + { + key: "getEncodedHex", + value: function() { + return (null == this.hTLV || this.isModified) && (this.hV = this.getFreshValueHex(), this.hL = this.getLengthHexFromValue(), this.hTLV = this.hT + this.hL + this.hV, this.isModified = !1), + this.hTLV + } + }, + { + key: "getFreshValueHex", + value: function() { + return "" + } + }]), + t + } (), + d = function(t) { + function i(t) { + s(this, i); + var e = r(this, (i.__proto__ || Object.getPrototypeOf(i)).call(this)); + return e.hT = "02", + t && t.bigint && (e.hTLV = null, e.isModified = !0, e.hV = o(t.bigint)), + e + } + return n(i, t), + y(i, [{ + key: "getFreshValueHex", + value: function() { + return this.hV + } + }]), + i + } (m), + T = function(t) { + function i(t) { + s(this, i); + var e = r(this, (i.__proto__ || Object.getPrototypeOf(i)).call(this)); + return e.hT = "30", + e.asn1Array = [], + t && t.array && (e.asn1Array = t.array), + e + } + return n(i, t), + y(i, [{ + key: "getFreshValueHex", + value: function() { + for (var t = "", + i = 0; i < this.asn1Array.length; i++) { + t += this.asn1Array[i].getEncodedHex() + } + return this.hV = t, + this.hV + } + }]), + i + } (m); + t.exports = { + encodeDer: function(t, i) { + var e = new d({ + bigint: t + }), + r = new d({ + bigint: i + }); + return new T({ + array: [e, r] + }).getEncodedHex() + }, + decodeDer: function(t) { + var i = p(t, 0), + e = i[0], + r = i[1], + n = l(t, e), + s = l(t, r); + return { + r: new g(n, 16), + s: new g(s, 16) + } + } + } +}, +function(t, i, e) { + "use strict"; + function r(t, i) { + if (! (t instanceof i)) throw new TypeError("Cannot call a class as a function") + } + var n = function() { + function t(t, i) { + for (var e = 0; e < i.length; e++) { + var r = i[e]; + r.enumerable = r.enumerable || !1, + r.configurable = !0, + "value" in r && (r.writable = !0), + Object.defineProperty(t, r.key, r) + } + } + return function(i, e, r) { + return e && t(i.prototype, e), + r && t(i, r), + i + } + } (), + s = e(0), + o = s.BigInteger, + h = new o("3"), + u = function() { + function t(i, e) { + r(this, t), + this.x = e, + this.q = i + } + return n(t, [{ + key: "equals", + value: function(t) { + return t === this || this.q.equals(t.q) && this.x.equals(t.x) + } + }, + { + key: "toBigInteger", + value: function() { + return this.x + } + }, + { + key: "negate", + value: function() { + return new t(this.q, this.x.negate().mod(this.q)) + } + }, + { + key: "add", + value: function(i) { + return new t(this.q, this.x.add(i.toBigInteger()).mod(this.q)) + } + }, + { + key: "subtract", + value: function(i) { + return new t(this.q, this.x.subtract(i.toBigInteger()).mod(this.q)) + } + }, + { + key: "multiply", + value: function(i) { + return new t(this.q, this.x.multiply(i.toBigInteger()).mod(this.q)) + } + }, + { + key: "divide", + value: function(i) { + return new t(this.q, this.x.multiply(i.toBigInteger().modInverse(this.q)).mod(this.q)) + } + }, + { + key: "square", + value: function() { + return new t(this.q, this.x.square().mod(this.q)) + } + }]), + t + } (), + a = function() { + function t(i, e, n, s) { + r(this, t), + this.curve = i, + this.x = e, + this.y = n, + this.z = void 0 === s ? o.ONE: s, + this.zinv = null + } + return n(t, [{ + key: "getX", + value: function() { + return null === this.zinv && (this.zinv = this.z.modInverse(this.curve.q)), + this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q)) + } + }, + { + key: "getY", + value: function() { + return null === this.zinv && (this.zinv = this.z.modInverse(this.curve.q)), + this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q)) + } + }, + { + key: "equals", + value: function(t) { + return t === this || (this.isInfinity() ? t.isInfinity() : t.isInfinity() ? this.isInfinity() : !!t.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(t.z)).mod(this.curve.q).equals(o.ZERO) && t.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(t.z)).mod(this.curve.q).equals(o.ZERO)) + } + }, + { + key: "isInfinity", + value: function() { + return null === this.x && null === this.y || this.z.equals(o.ZERO) && !this.y.toBigInteger().equals(o.ZERO) + } + }, + { + key: "negate", + value: function() { + return new t(this.curve, this.x, this.y.negate(), this.z) + } + }, + { + key: "add", + value: function(i) { + if (this.isInfinity()) return i; + if (i.isInfinity()) return this; + var e = this.x.toBigInteger(), + r = this.y.toBigInteger(), + n = this.z, + s = i.x.toBigInteger(), + h = i.y.toBigInteger(), + u = i.z, + a = this.curve.q, + f = e.multiply(u).mod(a), + l = s.multiply(n).mod(a), + c = f.subtract(l), + p = r.multiply(u).mod(a), + y = h.multiply(n).mod(a), + v = p.subtract(y); + if (o.ZERO.equals(c)) return o.ZERO.equals(v) ? this.twice() : this.curve.infinity; + var g = f.add(l), + m = n.multiply(u).mod(a), + d = c.square().mod(a), + T = c.multiply(d).mod(a), + b = m.multiply(v.square()).subtract(g.multiply(d)).mod(a), + F = c.multiply(b).mod(a), + B = v.multiply(d.multiply(f).subtract(b)).subtract(p.multiply(T)).mod(a), + x = T.multiply(m).mod(a); + return new t(this.curve, this.curve.fromBigInteger(F), this.curve.fromBigInteger(B), x) + } + }, + { + key: "twice", + value: function() { + if (this.isInfinity()) return this; + if (!this.y.toBigInteger().signum()) return this.curve.infinity; + var i = this.x.toBigInteger(), + e = this.y.toBigInteger(), + r = this.z, + n = this.curve.q, + s = this.curve.a.toBigInteger(), + o = i.square().multiply(h).add(s.multiply(r.square())).mod(n), + u = e.shiftLeft(1).multiply(r).mod(n), + a = e.square().mod(n), + f = a.multiply(i).multiply(r).mod(n), + l = u.square().mod(n), + c = o.square().subtract(f.shiftLeft(3)).mod(n), + p = u.multiply(c).mod(n), + y = o.multiply(f.shiftLeft(2).subtract(c)).subtract(l.shiftLeft(1).multiply(a)).mod(n), + v = u.multiply(l).mod(n); + return new t(this.curve, this.curve.fromBigInteger(p), this.curve.fromBigInteger(y), v) + } + }, + { + key: "multiply", + value: function(t) { + if (this.isInfinity()) return this; + if (!t.signum()) return this.curve.infinity; + for (var i = t.multiply(h), e = this.negate(), r = this, n = i.bitLength() - 2; n > 0; n--) { + r = r.twice(); + var s = i.testBit(n); + s !== t.testBit(n) && (r = r.add(s ? this: e)) + } + return r + } + }]), + t + } (), + f = function() { + function t(i, e, n) { + r(this, t), + this.q = i, + this.a = this.fromBigInteger(e), + this.b = this.fromBigInteger(n), + this.infinity = new a(this, null, null) + } + return n(t, [{ + key: "equals", + value: function(t) { + return t === this || this.q.equals(t.q) && this.a.equals(t.a) && this.b.equals(t.b) + } + }, + { + key: "fromBigInteger", + value: function(t) { + return new u(this.q, t) + } + }, + { + key: "decodePointHex", + value: function(t) { + switch (parseInt(t.substr(0, 2), 16)) { + case 0: + return this.infinity; + case 2: + case 3: + return null; + case 4: + case 6: + case 7: + var i = (t.length - 2) / 2, + e = t.substr(2, i), + r = t.substr(i + 2, i); + return new a(this, this.fromBigInteger(new o(e, 16)), this.fromBigInteger(new o(r, 16))); + default: + return null + } + } + }]), + t + } (); + t.exports = { + ECPointFp: a, + ECCurveFp: f + } +}, +function(t, i, e) { + "use strict"; + function r(t, i) { + if (! (t instanceof i)) throw new TypeError("Cannot call a class as a function") + } + var n = function() { + function t(t, i) { + for (var e = 0; e < i.length; e++) { + var r = i[e]; + r.enumerable = r.enumerable || !1, + r.configurable = !0, + "value" in r && (r.writable = !0), + Object.defineProperty(t, r.key, r) + } + } + return function(i, e, r) { + return e && t(i.prototype, e), + r && t(i, r), + i + } + } (), + s = e(0), + o = s.BigInteger, + h = e(2), + u = e(1), + a = function() { + function t() { + r(this, t), + this.ct = 1, + this.p2 = null, + this.sm3keybase = null, + this.sm3c3 = null, + this.key = new Array(32), + this.keyOff = 0 + } + return n(t, [{ + key: "reset", + value: function() { + this.sm3keybase = new h, + this.sm3c3 = new h; + var t = u.hexToArray(this.p2.getX().toBigInteger().toRadix(16)), + i = u.hexToArray(this.p2.getY().toBigInteger().toRadix(16)); + this.sm3keybase.blockUpdate(t, 0, t.length), + this.sm3c3.blockUpdate(t, 0, t.length), + this.sm3keybase.blockUpdate(i, 0, i.length), + this.ct = 1, + this.nextKey() + } + }, + { + key: "nextKey", + value: function() { + var t = new h(this.sm3keybase); + t.update(this.ct >> 24 & 255), + t.update(this.ct >> 16 & 255), + t.update(this.ct >> 8 & 255), + t.update(255 & this.ct), + t.doFinal(this.key, 0), + this.keyOff = 0, + this.ct++ + } + }, + { + key: "initEncipher", + value: function(t) { + var i = u.generateKeyPairHex(), + e = new o(i.privateKey, 16), + r = i.publicKey; + return this.p2 = t.multiply(e), + this.reset(), + r.length > 128 && (r = r.substr(r.length - 128)), + r + } + }, + { + key: "encryptBlock", + value: function(t) { + this.sm3c3.blockUpdate(t, 0, t.length); + for (var i = 0; i < t.length; i++) this.keyOff === this.key.length && this.nextKey(), + t[i] ^= 255 & this.key[this.keyOff++] + } + }, + { + key: "initDecipher", + value: function(t, i) { + this.p2 = i.multiply(t), + this.reset() + } + }, + { + key: "decryptBlock", + value: function(t) { + for (var i = 0; i < t.length; i++) this.keyOff === this.key.length && this.nextKey(), + t[i] ^= 255 & this.key[this.keyOff++]; + this.sm3c3.blockUpdate(t, 0, t.length) + } + }, + { + key: "doFinal", + value: function(t) { + var i = u.hexToArray(this.p2.getY().toBigInteger().toRadix(16)); + this.sm3c3.blockUpdate(i, 0, i.length), + this.sm3c3.doFinal(t, 0), + this.reset() + } + }, + { + key: "createPoint", + value: function(t, i) { + var e = "04" + t + i; + return u.getGlobalCurve().decodePointHex(e) + } + }]), + t + } (); + t.exports = a +}]); +window.smCrypto = { sm2 } diff --git a/test/ws.html b/test/ws.html new file mode 100644 index 0000000..80f04aa --- /dev/null +++ b/test/ws.html @@ -0,0 +1,51 @@ + + + + + + + + + + + Vite App + + + diff --git a/tsconfig.build.json b/tsconfig.build.json new file mode 100644 index 0000000..4ada5ed --- /dev/null +++ b/tsconfig.build.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "declarationDir": "types", + "outDir": "dist" + }, + "exclude": ["test/**/*.ts", "test/**/*.d.ts", "rollup.config.ts"] +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..b0c8e3c --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "allowJs": true, + "target": "esnext", + "module": "esnext", + "lib": ["esnext", "dom", "dom.iterable"], + "moduleResolution": "Node", + "types": ["node"], + "strict": true, + "sourceMap": true, + "resolveJsonModule": true, + "esModuleInterop": true, + "noEmit": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true + }, + "include": [ + "src/**/*.ts", + "src/**/*.d.ts", + "test/**/*.ts", + "test/**/*.d.ts", + "rollup.config.ts" + ], + "exclude": ["src/**/*.js", "test/**/*.js"] +} diff --git a/types/crypto.d.ts b/types/crypto.d.ts new file mode 100644 index 0000000..9219cb6 --- /dev/null +++ b/types/crypto.d.ts @@ -0,0 +1,16 @@ +import type { AESKey } from '@daotl/cryptico'; +import { RSAKey } from '@daotl/cryptico'; +export declare function aesEncrypt(data: string, aesKey: AESKey): string; +export declare function rsaEncrypt(data: string, rsaKey: { + n: string; + e1: string; +}): string; +export declare function loadRSAKey(rsaKey: string): RSAKey; +export declare function encryptReq(reqContent: { + contractID: string; +}, pubKey: RSAKey): { + action: string | null; + contractID: string; + arg: string; + requester: string; +}; diff --git a/types/httpClient.d.ts b/types/httpClient.d.ts new file mode 100644 index 0000000..5e58860 --- /dev/null +++ b/types/httpClient.d.ts @@ -0,0 +1,56 @@ +import { type AxiosRequestConfig } from 'axios'; +import type { KeyPairHex } from 'sm-crypto'; +import type { ClientResponse, ConfigNodeArgs, ExecuteContractArgs, ListAllUsersResponseData, ListNodesResponse, ListProjectPermissionRequest, ListProjectPermissionResponseData, LoadNodeConfigResponseData, ExecuteContractResponse, PingResponse, SaveFileRequest, StartContractByYpkRequest } from './types'; +export * from './types'; +export declare class HttpClient { + private baseUrl; + private sm2Key; + private fetch; + constructor(baseUrl: string, sm2Key: KeyPairHex, config?: AxiosRequestConfig); + requestWithSignature(path: string, init?: Partial, sm2Key?: KeyPairHex): Promise>; + retryRequestWithSignature(retryTimes: number, path: string, init?: Partial, sm2Key?: KeyPairHex): Promise>; + sign(data: string, privateKey?: string): string; + ping(): Promise; + startContract(code: string): Promise>; + startContractByYPK(_request: StartContractByYpkRequest): Promise>; + executeContract(contractID: string, operation: string, arg: string, { method, withDynamicAnalysis, withSignature, }?: ExecuteContractArgs): Promise>>; + killContractProcess(contractID: string, requestID?: string): Promise>; + killAllContract(): Promise>; + applyNodeRole(role: string): Promise>; + authNodeRole(isAccept: boolean, authorizedPubKey: string, managerPair?: KeyPairHex): Promise>; + distributeContract(nodeIDs: string, projectName: string, isPrivate: boolean): void; + saveFile(_request: SaveFileRequest): Promise>; + listProjectPermission(_request: ListProjectPermissionRequest): Promise>; + startContractMultiPoint(peersID: string, type: number, selectUnitNum: number, projectName: string, isPrivate: boolean, sponsorPeerID: string): Promise>; + loadNodeConfig(): Promise>; + updateConfig(key: string, val: string): Promise>; + resetNodeManager(): Promise; + lockEdit(): Promise>; + unlockEdit(): Promise>; + addNode(nodePubKey: string): Promise>; + applyRole(role: string): Promise>; + authNodeManager(isAccept: boolean, authorizedPubKey: string): Promise>; + listAllUsers(): Promise>; + listNodes(): Promise; + createTrustUnit(data: { + nodeName: string; + pubkey: string; + }[], Msg: string): Promise<{ + action: string; + status: string; + }>; + listTrustUnits(): Promise>; + listContractProcess(): Promise>; + downloadContract(projectName: string, isPrivate: boolean, timestamp: number): Promise>; + configNode(args: ConfigNodeArgs): Promise; +} diff --git a/types/index.d.ts b/types/index.d.ts new file mode 100644 index 0000000..a513b55 --- /dev/null +++ b/types/index.d.ts @@ -0,0 +1,4 @@ +export * from './crypto'; +export * from './httpClient'; +export * from './wsClient'; +export * from './wssocket'; diff --git a/types/types.d.ts b/types/types.d.ts new file mode 100644 index 0000000..4ff5d40 --- /dev/null +++ b/types/types.d.ts @@ -0,0 +1,84 @@ +export type ClientResponse = Omit & { + data?: Data; +}; +export type PingResponse = ClientResponse<'pong'>; +export interface SaveFileRequest { + content: string; + isAppend: boolean; + isPrivate: boolean; + path: string; +} +export interface ListProjectPermissionRequest { + isPrivate: boolean; + path: string; +} +export interface ListProjectPermissionResponseData { + permissions: string[]; + ypk: string; +} +export interface StartContractByYpkRequest { + isPrivate: boolean; + path: string; + script: string; +} +export interface ListAllUsersResponseDataListItem { + key: string; + value: string; +} +export interface ListAllUsersResponseData { + kv: ListAllUsersResponseDataListItem[]; + time: ListAllUsersResponseDataListItem[]; +} +export interface OnlineContractsItem { + contractID: string; + contractName: string; + isMaster: boolean; + type: string; + yjsType: string; + [key: string]: unknown; +} +export interface OnlineItem { + cimanager: string; + contractVersion: number; + events: number; + ipPort: string; + masterAddress: string; + nodeName: string; + peerID: string; + pubKey: string; + contracts: OnlineContractsItem[]; +} +export interface ListNodesResponse { + action: string; + offline: string[]; + online: OnlineItem[]; +} +export interface DistributeContractResponse { + action: string; + progress: string; +} +export interface ExecuteContractArgs extends RequestInit { + method?: 'POST' | 'GET'; + withSignature?: boolean; + withDynamicAnalysis?: boolean; +} +export interface ExecuteContractResponse { + status?: boolean; + data?: Data; + executeTime?: number; + cid?: string; + isPrivate?: boolean; + [key: string]: unknown; +} +export interface ConfigNodeArgs { + nodeName?: string; + dataChain?: string; + masterAddress?: string; + nodeCenter?: string; + LHSProxyAddress?: string; + [K: string]: string | undefined; +} +export interface LoadNodeConfigResponseData { + doipConfig: string; + [K: string]: string; +} diff --git a/types/wsClient.d.ts b/types/wsClient.d.ts new file mode 100644 index 0000000..44103da --- /dev/null +++ b/types/wsClient.d.ts @@ -0,0 +1,56 @@ +import type { KeyPairHex } from 'sm-crypto'; +import type { OnOpenHandler, WsHandler } from './wssocket'; +interface ResponseData { + action: string; + responseID?: string; + status: true | false | string; + result?: unknown; + data: string; + [K: string]: unknown; +} +export declare class WsClient { + private readonly sm2Key; + private readonly wssocket; + private readonly promiseCallbackPairs; + private readonly sessionPromise; + private sessionResolve; + private readonly loginPromise; + private loginResolve; + constructor(url: string, onopen: OnOpenHandler, handler: WsHandler, sm2Key?: KeyPairHex); + status(): WebSocket['CLOSED' | 'CLOSING' | 'CONNECTING' | 'OPEN']; + sessionReceived(): Promise; + login(): Promise; + loggedIn(): Promise; + matchCID(contractID: string): Promise; + getMetabyCID(contractID: string): Promise; + getMetabyReadme(keyword: string, page?: string, pageSize?: string): Promise; + getMetabyPubkey(pubkey: string): Promise; + segmentWord(words: string): Promise; + getMetabyOwner(owner: string, page?: string, pageSize?: string): Promise; + getDependentContract(contractName: string): Promise; + queryContractLogByDate(start: number): Promise; + queryDataByHash(hash: string): Promise; + executeContract(contractID: string, method: string, arg: unknown): Promise; + getSessionID(): Promise; + listTheContractProcess(contractID: string): Promise; + getMask(contractID: string): Promise; + setMask(contractID: string, operation: string, arg: string): Promise; + getMock(contractID: string): Promise; + setMock(contractID: string, operation: string, arg: string): Promise; + queryHashByOffset(offset: number, count: number): Promise; + loadNodeConfig(): Promise; + queryUserStat(): Promise; + listNodes(): Promise; + killContractProcess(id: string): Promise; + distributeYPK(projectName: string, nodeIDs: string): Promise; + listYPKs(): Promise; + deleteFile(file: string): Promise; + startContractByYPK(project: string): Promise; + initBDServer(host: string, username: string, password: string, name: string, clusterHost: string): Promise; + initBDCluster(host: string, username: string, password: string, name: string, sm2Key: string, agents: []): Promise; + listCompiledFiles(): Promise; + getManagerPubkey(): Promise; + getClusterName(): Promise; + setClusterName(name: string): Promise; +} +export {}; diff --git a/types/wssocket.d.ts b/types/wssocket.d.ts new file mode 100644 index 0000000..671a83a --- /dev/null +++ b/types/wssocket.d.ts @@ -0,0 +1,26 @@ +export interface WsEvent { + data: string; +} +export type OnOpenHandler = (this: WebSocket, ev: Event) => void; +export type WsHandler = (ev: WsEvent, ws?: WebSocket) => void; +interface SegmentData { + action: 'sendSeg'; + cid: string; + data: string; +} +export declare class WsSocket { + private handlerList; + private toSend; + private isSending; + private sendList; + private toReceive; + private wssocket; + constructor(wsurl: string, onopen: OnOpenHandler, handler?: WsHandler); + status(): WebSocket['CLOSED' | 'CLOSING' | 'CONNECTING' | 'OPEN']; + sendNextSegment(): void; + receiveSeg(obj: SegmentData): void; + monitor(): void; + send(data: string): void; + addHandler(handler: WsHandler): void; +} +export {};