-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
fabric-connection-profile.ts
85 lines (69 loc) · 2.36 KB
/
fabric-connection-profile.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
* SPDX-License-Identifier: Apache-2.0
*/
import * as fs from 'fs';
import * as path from 'path';
import * as grpc from '@grpc/grpc-js';
import yaml from 'js-yaml';
const JSON_EXT = /json/gi;
const YAML_EXT = /ya?ml/gi;
export interface ConnectionProfile {
display_name: string;
id: string;
name: string;
type: string;
version: string;
//
certificateAuthorities: any;
client: any;
oprganizations: any;
peers: { [key: string]: Peer };
}
export interface Peer {
grpcOptions: grpcOptions;
url: string;
tlsCACerts: any
}
export interface grpcOptions {
'ssl-Target-Name-Override'?: string;
hostnameOverride?: string;
'grpc.ssl_target_name_override'?: string;
'grpc.default_authority'?: string;
}
export class ConnectionHelper {
/**
* Loads the profile at the given filename.
*
* File can either by yaml or json, error is thrown is the file does
* not exist at the location given.
*
* @param profilename filename of the gateway connection profile
* @return Gateway profile as an object
*/
static loadProfile(profilename: string): ConnectionProfile {
const ccpPath = path.resolve(profilename);
if (!fs.existsSync(ccpPath)) {
throw new Error(`Profile file ${ccpPath} does not exist`);
}
const type = path.extname(ccpPath);
if (JSON_EXT.exec(type)) {
return JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
} else if (YAML_EXT.exec(type)) {
return yaml.load(fs.readFileSync(ccpPath, 'utf8')) as ConnectionProfile;
} else {
throw new Error(`Extension of ${ccpPath} not recognised`);
}
}
static async newGrpcConnection(cp: ConnectionProfile, tls: boolean): Promise<grpc.Client> {
const peerEndpointURL = new URL(cp.peers[Object.keys(cp.peers)[0]].url);
const peerEndpoint = `${peerEndpointURL.hostname}:${peerEndpointURL.port}`;
if (tls){
const tlsRootCert = cp.peers[Object.keys(cp.peers)[0]].tlsCACerts.pem;
const tlsCredentials = grpc.credentials.createSsl(Buffer.from(tlsRootCert));
return new grpc.Client(peerEndpoint, tlsCredentials);
} else {
console.log(peerEndpoint);
return new grpc.Client(peerEndpoint, grpc.ChannelCredentials.createInsecure());
}
}
}