forked from olegabu/fabric-starter-rest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fabric-cli.js
209 lines (156 loc) · 9.16 KB
/
fabric-cli.js
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
const fs = require('fs'),
path = require('path'),
_ = require('lodash'),
envsub = require('envsub'),
shell = require('shelljs'),
Enum = require('enumify').Enum;
const cfg = require('./config.js');
const logger = cfg.log4js.getLogger('FabricCLI');
const CERT_FOLDERS_PREFIXES = {
'admincerts': {certFileNamePart: 'Admin@', envVar: 'ORG_ADMIN_CERT'},
'cacerts': {certFileNamePart: 'ca.', envVar: 'ORG_ROOT_CERT'},
'tlscacerts': {certFileNamePart: 'tlsca.', envVar: 'ORG_TLS_ROOT_CERT'}
};
const WGET_OPTS = process.env.WGET_OPTS || '-N';
class TRANSLATE_OP extends Enum {}
TRANSLATE_OP.initEnum(['proto_encode', 'proto_decode', 'compute_update']);
class CONFIG_TYPE extends Enum {}
CONFIG_TYPE.initEnum(['common.Config', 'common.Block', 'common.ConfigUpdate', 'common.Envelope']);
class FabricCLI {
downloadCerts(orgDomain, org) {
_.forEach(_.keys(CERT_FOLDERS_PREFIXES), certFolder => {
let certPrefix=CERT_FOLDERS_PREFIXES[certFolder];
let directoryPrefix = this.getCertFileDir(certFolder, org ? cfg.orgCryptoConfigPath(org) : cfg.ORDERER_CRYPTO_DIR);
let certFileName = this.getCertFileName(certPrefix, org);
shell.exec(`/usr/bin/wget ${WGET_OPTS} --directory-prefix ${directoryPrefix} http://www.${orgDomain}/msp/${certFolder}/${certFileName}`);
});
}
downloadOrdererMSP() {
this.downloadCerts(cfg.ORDERER_DOMAIN);
}
downloadOrgMSP(org) {
this.downloadCerts(`${org}.${cfg.domain}`, org);
}
execShellCommand(cmd) {
logger.debug(cmd);
shell.exec(`${cmd} &2>1`);
}
async envSubst(templateFile, outputFile, env) {
let envs = _.map(_.keys(env), k => new Object({name: k, value: env[k]}));
logger.debug(`Envsubst: ${templateFile} to ${outputFile}`);
logger.debug(envs);
return envsub({templateFile, outputFile, options: Object.assign({diff: false}, {envs: envs})});
}
generateConfigTxForChannel(channelName, configDir, profile, outputTxFile) {
this.execShellCommand(`configtxgen -channelID ${channelName} -configPath ${configDir} -profile ${profile} -outputCreateChannelTx ${outputTxFile}`)
}
execPeerCommand(command, paramsStr) {
this.execShellCommand(`peer ${command} -o ${cfg.ORDERER_ADDR} --tls --cafile ${cfg.ORDERER_TLS_CERT} ${paramsStr}`);
}
async generateChannelConfigTx(channelId) {
await this.envSubst(`${cfg.TEMPLATES_DIR}/configtx-template.yaml`, `${cfg.CRYPTO_CONFIG_DIR}/configtx.yaml`, {DOMAIN: cfg.ORDERER_DOMAIN, ORG: cfg.org});
let outputTxFile = `${cfg.CRYPTO_CONFIG_DIR}/configtx/channel_${channelId}.tx`;
this.generateConfigTxForChannel(channelId, cfg.CRYPTO_CONFIG_DIR, "CHANNEL", outputTxFile);
return outputTxFile;
}
async generateChannelConfigTxContent(channelId) {
let channelTxFile = await this.generateChannelConfigTx(channelId);
return this.loadFileContent(channelTxFile);
}
async fetchChannelConfigToFile(channelId) {
const filePath = this.fetchChannelConfig(channelId);
return this.loadFileContent(filePath);
}
fetchChannelConfig(channelId) {
const channelConfigFile = `${channelId}_config.pb`;
const outputFilePath = `${cfg.CRYPTO_CONFIG_DIR}/${channelConfigFile}`;
this.execPeerCommand(`channel fetch config ${outputFilePath}`, `-c ${channelId}`);
return outputFilePath;
}
computeConfigUpdate(channelId, originalFileName, updatedFileName, outputFileName) {
this.execShellCommand(`configtxlator compute_update --channel_id=${channelId} --original=${originalFileName} --updated=${updatedFileName} --output=${outputFileName}`);
}
translateProtobufConfig(translateOp, configType, inputFilename, outputFileName) {
this.execShellCommand(`configtxlator ${translateOp.name} --type ${configType.name} --input=${inputFilename} --output=${outputFileName}`);
}
translateChannelConfig(configFileName) {
const outputFileName = `${path.dirname(configFileName)}/${path.basename(configFileName, ".pb")}.json`;
this.translateProtobufConfig(TRANSLATE_OP.proto_decode, CONFIG_TYPE['common.Block'], configFileName, outputFileName);
return this.loadFileContentSync(outputFileName);
}
computeChannelConfigUpdate(channelId, originalConfig, configWithChangesJson) {
const originalConfigJsonFile = `${cfg.CRYPTO_CONFIG_DIR}/${channelId}_originalConfig.json`;
const originalConfigPbFile = `${cfg.CRYPTO_CONFIG_DIR}/${channelId}_originalConfig.pb`;
const updatedConfigWithJsonFile = `${cfg.CRYPTO_CONFIG_DIR}/${channelId}_configUpdate.json`;
const updatedConfigPbFile = `${cfg.CRYPTO_CONFIG_DIR}/${channelId}_configUpdate.pb`;
const computedUpdatePbFileName= `${cfg.CRYPTO_CONFIG_DIR}/${channelId}_update.pb`;
fs.writeFileSync(originalConfigJsonFile, JSON.stringify(originalConfig));
this.translateProtobufConfig(TRANSLATE_OP.proto_encode, CONFIG_TYPE["common.Config"], originalConfigJsonFile, originalConfigPbFile);
fs.writeFileSync(updatedConfigWithJsonFile, JSON.stringify(configWithChangesJson));
this.translateProtobufConfig(TRANSLATE_OP.proto_encode, CONFIG_TYPE['common.Config'], updatedConfigWithJsonFile, updatedConfigPbFile);
this.computeConfigUpdate(channelId, originalConfigPbFile, updatedConfigPbFile, computedUpdatePbFileName);
return this.loadFileContentSync(computedUpdatePbFileName);
}
async prepareComputeUpdateEnvelope(channelId, originalConfig, configWithChangesJson) { //todo: for future reuse
await this.computeChannelConfigUpdate(channelId, originalConfig, configWithChangesJson);
const computedUpdatePbFileName= `${cfg.CRYPTO_CONFIG_DIR}/${channelId}_update.pb`;
const computedUpdateJsonFile= `${cfg.CRYPTO_CONFIG_DIR}/${channelId}_update.json`;
const updateEnvelopeJsonFile= `${cfg.CRYPTO_CONFIG_DIR}/${channelId}_update_envelope.json`;
const updateEnvelopePbFile= `${cfg.CRYPTO_CONFIG_DIR}/${channelId}_update_envelope.pb`;
this.translateProtobufConfig(TRANSLATE_OP.proto_decode, CONFIG_TYPE["common.ConfigUpdate"], computedUpdatePbFileName, computedUpdateJsonFile);
let computedUpdate = this.loadFileContentSync(computedUpdateJsonFile);
computedUpdate=JSON.parse(_.toString(computedUpdate));
let envelope = JSON.stringify({payload: {header: {channel_header: {channel_id: channelId, type: 2}},data: {config_update: computedUpdate}}});
fs.writeFileSync(updateEnvelopeJsonFile, envelope);
this.translateProtobufConfig(TRANSLATE_OP.proto_encode, CONFIG_TYPE['common.Envelope'], updateEnvelopeJsonFile, updateEnvelopePbFile);
return this.loadFileContentSync(updateEnvelopePbFile);
}
async prepareNewOrgConfig(newOrg) {
this.downloadOrgMSP(newOrg);
let env = {NEWORG: newOrg, DOMAIN:cfg.domain};
_.forEach(_.keys(CERT_FOLDERS_PREFIXES), certFolder => {
let certPrefix=CERT_FOLDERS_PREFIXES[certFolder];
let certFilePath = path.join(this.getCertFileDir(certFolder, cfg.orgCryptoConfigPath(newOrg)), this.getCertFileName(certPrefix, newOrg));
let certContent = this.loadFileContentSync(certFilePath);
env[certPrefix.envVar]=Buffer.from(certContent).toString('base64');
});
const outputFile = `crypto-config/${newOrg}_NewOrg.json`;
let newOrgSubstitution = await this.envSubst(`${cfg.TEMPLATES_DIR}//NewOrg.json`, outputFile, env);
return {outputFile, outputJson: JSON.parse(newOrgSubstitution.outputContents)};
}
async prepareNewConsortiumConfig(newOrg) {
this.downloadOrgMSP(newOrg);
let env = {NEWORG: newOrg, DOMAIN:cfg.domain, CONSORTIUM_NAME: 'SampleConsortium'};
_.forEach(_.keys(CERT_FOLDERS_PREFIXES), certFolder => {
let certPrefix=CERT_FOLDERS_PREFIXES[certFolder];
let certFilePath = path.join(this.getCertFileDir(certFolder, cfg.orgCryptoConfigPath(newOrg)), this.getCertFileName(certPrefix, newOrg));
let certContent = this.loadFileContentSync(certFilePath);
env[certPrefix.envVar]=Buffer.from(certContent).toString('base64');
});
const outputFile = `crypto-config/${newOrg}_Consortium.json`;
let newOrgSubstitution = await this.envSubst(`${cfg.TEMPLATES_DIR}/Consortium.json`, outputFile, env);
return {outputFile, outputJson: JSON.parse(newOrgSubstitution.outputContents)};
}
getCertFileDir(certFolder, domainCertPath) {
return `${domainCertPath}/msp/${certFolder}`;
}
getCertFileName(certPrefix, org) {
let domainCertPath = org ? `${org}.${cfg.domain}` : cfg.domain;
let certFileName = `${certPrefix.certFileNamePart}${domainCertPath}-cert.pem`;
return certFileName;
}
loadFileContent(fileName) {
return new Promise((resolve, reject) => {
fs.readFile(fileName, (err, data) => {
!err ? resolve(data) : reject(err);
})
}).catch(err => {
logger.error(err);
throw new Error(err);
})
}
loadFileContentSync(fileName) {
return fs.readFileSync(fileName);
}
}
module.exports = new FabricCLI();