3 lines
19 KiB
JavaScript
3 lines
19 KiB
JavaScript
!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;a<e;a++)try{return await this.requestWithSignature(t,s,i)}catch(t){if(a<e){console.log("1");continue}r=t}throw r}sign(e,t){return r.sm2.doSignature(e,t??this.sm2Key.privateKey,{hash:!0,der:!0})}ping(){return this.requestWithSignature("/SCManager?action=ping")}startContract(e){const t={action:"startContract",script:e};return this.requestWithSignature(`/SCManager?${c(t)}`)}startContractByYPK(e){return this.requestWithSignature(`/SCManager?${c({action:"startContractByYPK",...e,owner:this.sm2Key.publicKey,aim:"onStartContract",signature:r.sm2.doSignature(`Fixed|${e.path}|${this.sm2Key.publicKey}`,this.sm2Key.privateKey,{hash:!0,der:!0})})}`)}executeContract(e,t,s,{method:i="POST",withDynamicAnalysis:r=!1,withSignature:a=!1}={}){let n={};return n=void 0===r?{action:"executeContract",contractID:e,operation:t,arg:s}:{action:"executeContract",contractID:e,operation:t,withDynamicAnalysis:r,arg:s},a&&(n={...n,pubkey:this.sm2Key.publicKey,signature:this.sign(`${e}|${t}|${s??""}|${this.sm2Key.publicKey}`)}),this.retryRequestWithSignature(3,"/SCManager"+("GET"===i?`?${c(n)}`:""),{method:i,..."POST"===i?{body:n}:{}})}killContractProcess(e,t){const s={action:"killContractProcess",id:e};return t&&(s.requestID=t),this.requestWithSignature(`/SCManager?${c(s)}`)}killAllContract(){return this.requestWithSignature("/SCManager?action=killAllContract")}applyNodeRole(e){const t={action:"applyNodeRole",role:e};return this.requestWithSignature(`/SCManager?${c(t)}`)}authNodeRole(e,t,s){const i={action:"authNodeRole",isAccept:e,authorizedPubKey:t};return this.requestWithSignature(`/SCManager?${c(i)}`,void 0,s)}distributeContract(e,t,s){const i=r.sm2.doSignature(`DistributeContract|${t}|${this.sm2Key.publicKey}`,this.sm2Key.privateKey,{hash:!0,der:!0}),a=`/SCManager?${c({action:"distributeContract",nodeIDs:e,projectName:t,isPrivate:s,signature:i})}`,n=`${this.baseUrl+a}${a.includes("?")?"&":"?"}pubKey=${this.sm2Key.publicKey}`,o=r.sm2.doSignature(n.substring(n.indexOf("?")+1),this.sm2Key.privateKey,{hash:!0,der:!0});new EventSource(`${this.baseUrl}${a}&pubKey=${this.sm2Key.publicKey}&sign=${o}`).addEventListener("message",(function(e){}),!1)}saveFile(e){return this.requestWithSignature(`/SCManager?${c({action:"saveFile",...e})}`)}listProjectPermission(e){return this.requestWithSignature(`/SCManager?${c({action:"listProjectPermission",...e})}`)}startContractMultiPoint(e,t,s,i,r,a){const n={peersID:e,type:t,selectUnitNum:s,projectName:i,isPrivate:r,sponsorPeerID:a};return this.requestWithSignature(`/SCManager?${c({action:"startContractMultiPoint",...n})}`)}async loadNodeConfig(){const e=await this.requestWithSignature(`/SCManager?${c({action:"loadNodeConfig"})}`);return{...e,data:200===e.status&&e.data?JSON.parse(e.data).data:{}}}async updateConfig(e,t){return this.requestWithSignature(`/SCManager?${c({action:"updateConfig",key:e,val:t})}`)}async resetNodeManager(){const e=await this.requestWithSignature(`/SCManager?${c({action:"resetNodeManager"})}`);if(!e.data)return!1;return"success"===JSON.parse(e.data).data}lockEdit(){return this.requestWithSignature(`/SCManager?${c({action:"lockEdit"})}`)}unlockEdit(){return this.requestWithSignature(`/SCManager?${c({action:"unlockEdit"})}`)}addNode(e){return this.requestWithSignature(`?${c({action:"addNode",nodePubKey:e})}`)}applyRole(e){return this.requestWithSignature(`?${c({action:"applyRole",role:e})}`)}authNodeManager(e,t){return this.requestWithSignature(`?${c({action:"authNodeManager",isAccept:e,authorizedPubKey:t})}`)}listAllUsers(){return this.requestWithSignature(`?${c({action:"listAllUsers"})}`)}listNodes(){return this.requestWithSignature(`?${c({action:"listNodes"})}`)}async createTrustUnit(e,t){const s=`action=createTrustUnit&data=${JSON.stringify(e)}&msg=${t}&pubKey=04303718771b9323c204e607639f14469f9a94e55b0964a408ad3b3864b0493b645d7070da0d550f0c54b934275a8e88dedc3024467b0566db5c1108b1baeaae27`,i={action:"createTrustUnit",data:e,msg:t,pubKey:"04303718771b9323c204e607639f14469f9a94e55b0964a408ad3b3864b0493b645d7070da0d550f0c54b934275a8e88dedc3024467b0566db5c1108b1baeaae27",sign:r.sm2.doSignature(s,this.sm2Key.privateKey,{hash:!0,der:!0})};return await this.requestWithSignature("",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}listTrustUnits(){return this.requestWithSignature(`?${c({action:"listTrustUnits"})}`)}listContractProcess(){return this.requestWithSignature(`/SCManager?${c({action:"listContractProcess"})}`)}downloadContract(e,t,s){const i={action:"downloadContract",projectName:e,isPrivate:t,timestamp:s};return this.requestWithSignature(`/CMManager?${c(i)}`)}async configNode(e){if(!await this.resetNodeManager())return!1;const t=Object.entries(e).filter((([e,t])=>t));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
|