UNPKG

@hashgraph/sdk

Version:
3 lines (2 loc) 2.27 kB
import e from"tls";import{credentials as t,Client as r,Metadata as i}from"@grpc/grpc-js";import s from"./Channel.js";import n from"../grpc/GrpcServiceError.js";import o from"../grpc/GrpcStatus.js";import{ALL_NETWORK_IPS as c}from"../constants/ClientConstants.js";import{SDK_NAME as a,SDK_VERSION as l}from"../version.js";const d={};class p extends s{constructor(e,t){super(),this._client=null,this.address=e,this.maxExecutionTime=t;const{ip:r,port:i}=this.parseAddress(e);this.nodeIp=r,this.nodePort=i}bytesToPem(e){const t=e.toString("base64");return`-----BEGIN CERTIFICATE-----\n${t.match(/.{1,64}/g)?.join("\n")||""}\n-----END CERTIFICATE-----`}parseAddress(e){const[t,r]=e.split(":");if(!t||!r)throw new Error("Invalid address format. Expected format: 'IP:Port'");return{ip:t,port:r}}async _retrieveCertificate(){return new Promise(((t,r)=>{const i=e.connect({host:this.nodeIp,port:Number(this.nodePort),rejectUnauthorized:!1},(()=>{try{const e=i.getPeerCertificate();e&&e.raw?t(this.bytesToPem(e.raw)):r(new Error("No certificate retrieved."))}catch(e){r(e)}finally{i.end()}}));i.on("error",r)}))}async _initializeClient(){if(d[this.address])return void(this._client=d[this.address]);let e;if("50212"===this.nodePort){const r=Buffer.from(await this._retrieveCertificate());e=t.createSsl(r)}else e=t.createInsecure();this._client=new r(this.address,e,{"grpc.ssl_target_name_override":"127.0.0.1","grpc.default_authority":"127.0.0.1","grpc.http_connect_creds":"0","grpc.keepalive_time_ms":1e5,"grpc.keepalive_timeout_ms":1e4,"grpc.keepalive_permit_without_calls":1,"grpc.enable_retries":1}),d[this.address]=this._client}close(){this._client&&(this._client.close(),delete d[this.address])}_createUnaryClient(e){return(t,r,s)=>{this._initializeClient().then((()=>{const d=new Date,p=this.maxExecutionTime?this.maxExecutionTime:1e4;d.setMilliseconds(d.getMilliseconds()+p),this._client?.waitForReady(d,(d=>{if(d)s(new n(o.Timeout,c[`${this.nodeIp}:`]));else{const n=new i;n.set("x-user-agent",`${a}/${l}`),this._client?.makeUnaryRequest(`/proto.${e}/${t.name}`,(e=>e),(e=>e),Buffer.from(r),n,((e,t)=>{s(e,t)}))}}))})).catch((e=>{e instanceof Error?s(e):s(new Error("An unexpected error occurred"))}))}}}export{p as default}; //# sourceMappingURL=NodeChannel.js.map