@hashgraph/sdk
Version:
3 lines (2 loc) • 2.2 kB
JavaScript
import e from"tls";import{credentials as t,Client as r,Metadata as s}from"@grpc/grpc-js";import i 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 i{constructor(e,t){super(t),this._client=null,this.address=e;const{ip:r,port:s}=this.parseAddress(e);this.nodeIp=r,this.nodePort=s}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 s=e.connect({host:this.nodeIp,port:Number(this.nodePort),rejectUnauthorized:!1},()=>{try{const e=s.getPeerCertificate();e&&e.raw?t(this.bytesToPem(e.raw)):r(new Error("No certificate retrieved."))}catch(e){r(e)}finally{s.end()}});s.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,i)=>{this._initializeClient().then(()=>{const d=new Date,p=this.grpcDeadline;d.setMilliseconds(d.getMilliseconds()+p),this._client?.waitForReady(d,d=>{if(d)i(new n(o.Timeout,c[`${this.nodeIp}:`]));else{const n=new s;n.set("x-user-agent",`${a}/${l}`),this._client?.makeUnaryRequest(`/proto.${e}/${t.name}`,e=>e,e=>e,Buffer.from(r),n,(e,t)=>{i(e,t)})}})}).catch(e=>{e instanceof Error?i(e):i(new Error("An unexpected error occurred"))})}}}export{p as default};
//# sourceMappingURL=NodeChannel.js.map