-
Notifications
You must be signed in to change notification settings - Fork 0
/
helloblockchain.js
248 lines (217 loc) · 8.7 KB
/
helloblockchain.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
var hfc = require('hfc');
var util = require('util');
var fs = require('fs');
const https = require('https');
// Create a client blockchin.
var chain = hfc.newChain("targetChain");
// Configure the KeyValStore which is used to store sensitive keys.
// This data needs to be located or accessible any time the users enrollmentID
// perform any functions on the blockchain. The users are not usable without
// This data.
// Please ensure you have a /tmp directory prior to placing the keys there.
// If running on windows or mac please review the path setting.
chain.setKeyValStore(hfc.newFileKeyValStore('/tmp/keyValStore'));
// Creating an environment variable for ciphersuites
process.env['GRPC_SSL_CIPHER_SUITES'] = 'ECDHE-RSA-AES128-GCM-SHA256:' +
'ECDHE-RSA-AES128-SHA256:' +
'ECDHE-RSA-AES256-SHA384:' +
'ECDHE-RSA-AES256-GCM-SHA384:' +
'ECDHE-ECDSA-AES128-GCM-SHA256:' +
'ECDHE-ECDSA-AES128-SHA256:' +
'ECDHE-ECDSA-AES256-SHA384:' +
'ECDHE-ECDSA-AES256-GCM-SHA384';
var ccPath;
if (process.argv.length != 4) {
console.log("Invalid arguments");
console.log("USAGE: node helloblockachain.js -c <path-to-chaincode>");
console.log("ex: ");
console.log("node helloblockachain.js -c $GOPATH/src/github.com/chaincode_example02");
process.exit();
}
process.argv.forEach(function(val, index, array) {
if (index == 2 && (!val || val != "-c")) {
console.log("Invalid arguments")
process.exit();
} else if (index == 3) {
if (!val) {
console.log("Invalid arguments")
process.exit();
} else {
ccPath = val;
}
}
});
// Read and process the credentials.json
var network;
try {
network = JSON.parse(fs.readFileSync('ServiceCredentials.json', 'utf8'));
} catch (err) {
console.log("ServiceCredentials.json is missing, Rerun once the file is available")
process.exit();
}
var peers = network.credentials.peers;
var users = network.credentials.users;
// Determining if we are running on a startup or HSBN network based on the url
// of the discovery host name. The HSBN will contain the string zone.
var isHSBN = peers[0].discovery_host.indexOf('zone') >= 0 ? true : false;
var peerAddress = [];
var network_id = Object.keys(network.credentials.ca);
var ca_url = "grpcs://" + network.credentials.ca[network_id].discovery_host + ":" + network.credentials.ca[network_id].discovery_port;
var certFile = 'certificate.pem';
var certUrl = network.credentials.cert;
fs.access(certFile, (err) => {
if (!err) {
console.log("\nDeleting existing certificate ", certFile);
fs.unlinkSync(certFile);
}
downloadCertificate();
});
function downloadCertificate() {
var file = fs.createWriteStream(certFile);
https.get(certUrl, (res) => {
console.log('\nDownloading %s from %s', certFile, certUrl);
if (res.statusCode !== 200) {
console.log('\nDownload certificate failed, error code = %d', certFile, res.statusCode);
process.exit();
}
res.pipe(file);
// event received when certificate download is completed
file.on('finish', function() {
if (process.platform == "win32") {
copyCertificate();
} else {
// Adding a new line character to the certificates
fs.appendFile(certFile, "\n", (err) => {
if (err) throw err;
copyCertificate();
});
}
});
}).on('error', (e) => {
console.error(e);
process.exit();
});
}
function copyCertificate() {
//fs.createReadStream('certificate.pem').pipe(fs.createWriteStream(ccPath+'/certificate.pem'));
fs.writeFileSync(ccPath + '/certificate.pem', fs.readFileSync('certificate.pem'));
setTimeout(function() {
enrollAndRegisterUsers();
}, 1000);
}
function enrollAndRegisterUsers() {
var cert = fs.readFileSync(certFile);
chain.setMemberServicesUrl(ca_url, {
pem: cert
});
// Adding all the peers to blockchain
// this adds high availability for the client
for (var i = 0; i < peers.length; i++) {
chain.addPeer("grpcs://" + peers[i].discovery_host + ":" + peers[i].discovery_port, {
pem: cert
});
}
console.log("\n\n------------- peers and caserver information: -------------");
console.log(chain.getPeers());
console.log(chain.getMemberServices());
console.log('-----------------------------------------------------------\n\n');
var testChaincodeID;
// Enroll a 'admin' who is already registered because it is
// listed in fabric/membersrvc/membersrvc.yaml with it's one time password.
chain.enroll(users[0].username, users[0].secret, function(err, admin) {
if (err) throw Error("\nERROR: failed to enroll admin : %s", err);
console.log("\nEnrolled admin sucecssfully");
// Set this user as the chain's registrar which is authorized to register other users.
chain.setRegistrar(admin);
var enrollName = "JohnDoe"; //creating a new user
var registrationRequest = {
enrollmentID: enrollName,
account: "group1",
affiliation: "00001"
};
chain.registerAndEnroll(registrationRequest, function(err, user) {
if (err) throw Error(" Failed to register and enroll " + enrollName + ": " + err);
console.log("\nEnrolled and registered " + enrollName + " successfully");
//setting timers for fabric waits
chain.setDeployWaitTime(60);
chain.setInvokeWaitTime(20);
console.log("\nDeploying chaincode ...")
deployChaincode(user);
});
});
}
function deployChaincode(user) {
// Construct the deploy request
var deployRequest = {
// Function to trigger
fcn: "init",
// Arguments to the initializing function
args: ["a", "100", "b", "200"],
// the location where the startup and HSBN store the certificates
certificatePath: isHSBN ? "/root/" : "/certs/blockchain-cert.pem"
};
deployRequest.chaincodePath = "github.com/chaincode_example02/";
// Trigger the deploy transaction
var deployTx = user.deploy(deployRequest);
// Print the deploy results
deployTx.on('complete', function(results) {
// Deploy request completed successfully
testChaincodeID = results.chaincodeID;
console.log("\nChaincode ID : " + testChaincodeID);
console.log(util.format("\nSuccessfully deployed chaincode: request=%j, response=%j", deployRequest, results));
invokeOnUser(user);
});
deployTx.on('error', function(err) {
// Deploy request failed
console.log(util.format("\nFailed to deploy chaincode: request=%j, error=%j", deployRequest, err));
});
}
function invokeOnUser(user) {
// Construct the invoke request
var invokeRequest = {
// Name (hash) required for invoke
chaincodeID: testChaincodeID,
// Function to trigger
fcn: "invoke",
// Parameters for the invoke function
args: ["a", "b", "1"]
};
// Trigger the invoke transaction
var invokeTx = user.invoke(invokeRequest);
// Print the invoke results
invokeTx.on('submitted', function(results) {
// Invoke transaction submitted successfully
console.log(util.format("\nSuccessfully submitted chaincode invoke transaction: request=%j, response=%j", invokeRequest, results));
});
invokeTx.on('complete', function(results) {
// Invoke transaction completed successfully
console.log(util.format("\nSuccessfully completed chaincode invoke transaction: request=%j, response=%j", invokeRequest, results));
queryUser(user);
});
invokeTx.on('error', function(err) {
// Invoke transaction submission failed
console.log(util.format("\nFailed to submit chaincode invoke transaction: request=%j, error=%j", invokeRequest, err));
});
}
function queryUser(user) {
// Construct the query request
var queryRequest = {
// Name (hash) required for query
chaincodeID: testChaincodeID,
// Function to trigger
fcn: "query",
// Existing state variable to retrieve
args: ["a"]
};
// Trigger the query transaction
var queryTx = user.query(queryRequest);
// Print the query results
queryTx.on('complete', function(results) {
// Query completed successfully
console.log("\nSuccessfully queried chaincode function: request=%j, value=%s", queryRequest, results.result.toString());
});
queryTx.on('error', function(err) {
// Query failed
console.log("\nFailed to query chaincode, function: request=%j, error=%j", queryRequest, err);
});
}