-
Notifications
You must be signed in to change notification settings - Fork 6
/
extension.js
805 lines (713 loc) · 24.9 KB
/
extension.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
/**
* @param {vscode.ExtensionContext} context
*/
const vscode = require("vscode");
const fs = require("fs");
const { TreeViewProvider } = require("./src/admin/treeview");
const { createConnectionProfileWebview } = require("./src/admin/webview");
const simpleGit = require('simple-git');
const { exec } = require('child_process');
const path = require('path');
const os = require('os');
const {
saveConnectionProfileToStorage,
loadConnectionProfilesFromStorage,
} = require("./src/admin/storageUtility");
const {
getLatestBlockNumber,
connectToFabric,
} = require("./src/blockReader/blockQueries");
let loadedConnectionProfile = null;
const fabricsamples = require("./src/fabricsamples");
function activate(context) {
const fabricDebuggerPath = 'C:\\Users\\Public\\fabric-debugger';
function runupBashScript() {
const platform = process.platform;
const changeDirCommand = `cd "${fabricDebuggerPath}"`;
let runScriptCommand;
if (platform === 'win32') {
runScriptCommand = `wsl bash local-networkup.sh`;
} else {
runScriptCommand = `bash local-networkup.sh`;
}
const fullCommand = `${changeDirCommand} && ${runScriptCommand}`;
exec(fullCommand, (err, stdout, stderr) => {
if (err) {
vscode.window.showErrorMessage(`Error: ${stderr}`);
console.error(`Error: ${stderr}`);
return;
}
vscode.window.showInformationMessage(`Output: ${stdout}`);
console.log(`Output: ${stdout}`);
});
}
let greenButton = vscode.commands.registerCommand('myview.button1', () => {
runupBashScript();
});
context.subscriptions.push(greenButton);
function rundownBashScript() {
const platform = process.platform;
const changeDirCommand = `cd "${fabricDebuggerPath}"`;
let runScriptCommand;
if (platform === 'win32') {
runScriptCommand = `wsl bash local-networkdown.sh`;
} else {
runScriptCommand = `bash local-networkdown.sh`;
}
const fullCommand = `${changeDirCommand} && ${runScriptCommand}`;
exec(fullCommand, (err, stdout, stderr) => {
if (err) {
vscode.window.showErrorMessage(`Error: ${stderr}`);
console.error(`Error: ${stderr}`);
return;
}
vscode.window.showInformationMessage(`Output: ${stdout}`);
console.log(`Output: ${stdout}`);
});
}
let redButton = vscode.commands.registerCommand('myview.button2', () => {
rundownBashScript();
});
context.subscriptions.push(redButton);
const hyperledgerProvider = new fabricsamples();
vscode.window.registerTreeDataProvider(
"start-local-network",
hyperledgerProvider
);
const treeViewProviderFabric = new TreeViewProvider(
"fabric-network",
context
);
const treeViewProviderDesc = new TreeViewProvider("network-desc", context);
const treeViewProviderWallet = new TreeViewProvider("wallets", context);
vscode.window.createTreeView("fabric-network", {
treeDataProvider: treeViewProviderFabric,
});
vscode.window.createTreeView("network-desc", {
treeDataProvider: treeViewProviderDesc,
});
vscode.window.createTreeView("wallets", {
treeDataProvider: treeViewProviderWallet,
});
const loadProfilesAndWallets = async () => {
try {
const savedProfiles = await loadConnectionProfilesFromStorage(context);
if (savedProfiles.length > 0) {
loadedConnectionProfile = savedProfiles[0];
console.log("Loaded connection profile:", loadedConnectionProfile);
} else {
console.warn("No combined profiles found in storage.");
}
savedProfiles.forEach((profile) => {
console.log("Processing profile:", profile);
const networkDetails = extractNetworkDetails(profile);
console.log("Extracted network details:", networkDetails);
const networkData = {
channelName: profile.name,
networkDetails,
walletDetails: profile.wallets || [],
};
treeViewProviderFabric.addNetwork(networkData);
treeViewProviderDesc.addNetwork(networkData);
if (profile.wallets && profile.wallets.length > 0) {
treeViewProviderWallet.networkWalletMap.set(
profile.name,
profile.wallets
);
profile.wallets.forEach((wallet) => {
console.log("Adding wallet:", wallet);
treeViewProviderWallet.addWallet(wallet);
});
}
});
} catch (error) {
vscode.window.showErrorMessage(
"Error loading profiles with wallets from storage."
);
console.error("Error loading profiles and wallets from storage:", error);
}
};
loadProfilesAndWallets().catch((error) => {
console.error("Error loading profiles and wallets:", error);
});
context.subscriptions.push(
vscode.commands.registerCommand(
"fabric-network.uploadNetwork",
async () => {
const fileUri = await vscode.window.showOpenDialog({
canSelectFiles: true,
canSelectMany: false,
filters: {
"JSON files": ["json"],
"All files": ["*"],
},
});
if (fileUri && fileUri[0]) {
const filePath = fileUri[0].fsPath;
fs.readFile(filePath, "utf8", async (err, fileContents) => {
if (err) {
vscode.window.showErrorMessage("Error reading the file");
console.error(err);
return;
}
try {
const parsedData = JSON.parse(fileContents);
loadedConnectionProfile = parsedData;
if (loadedConnectionProfile) {
await saveConnectionProfileToStorage(
context,
loadedConnectionProfile
);
const wallets = extractWalletsFromProfile(
loadedConnectionProfile
);
if (!wallets || wallets.length === 0) {
vscode.window.showWarningMessage(
"Wallet files or embedded data are missing. Please upload the wallet."
);
} else {
for (const wallet of wallets) {
treeViewProviderWallet.addWallet(wallet);
}
if (
!treeViewProviderWallet.networkWalletMap.has(
loadedConnectionProfile.name
)
) {
treeViewProviderWallet.networkWalletMap.set(
loadedConnectionProfile.name,
[]
);
}
wallets.forEach((wallet) => {
if (wallet && typeof wallet === "object") {
treeViewProviderWallet.networkWalletMap
.get(loadedConnectionProfile.name)
.push(wallet);
treeViewProviderWallet.addWallet(wallet);
} else {
console.warn("Invalid wallet structure:", wallet);
}
});
}
const networkDetails = extractNetworkDetails(
loadedConnectionProfile
);
const networkData = {
channelName: loadedConnectionProfile.name,
networkDetails,
walletDetails: wallets,
};
treeViewProviderDesc.addNetwork(networkData);
treeViewProviderFabric.addNetwork(networkData);
vscode.window.showInformationMessage(
"Network loaded successfully"
);
} else {
console.warn("Connection profile is not valid.");
}
} catch (parseError) {
vscode.window.showErrorMessage("Error parsing JSON file");
console.error(parseError);
}
});
} else {
vscode.window.showErrorMessage("No file selected");
}
}
)
);
context.subscriptions.push(
vscode.commands.registerCommand(
"fabric-network.switchNetwork",
async (treeItem) => {
const descItem = treeViewProviderDesc.getNetworkByLabel(treeItem.label);
const fabricItem = treeViewProviderFabric.getNetworkByLabel(
treeItem.label
);
if (descItem) {
treeViewProviderDesc.setActiveNetwork(descItem);
}
if (fabricItem) {
treeViewProviderFabric.setActiveNetwork(fabricItem);
}
const activeNetwork = fabricItem || descItem;
if (!activeNetwork) {
vscode.window.showErrorMessage(
`Network not found for: ${treeItem.label}`
);
return;
}
const connectionProfileName = activeNetwork.label;
let walletDetails =
treeViewProviderWallet.networkWalletMap.get(connectionProfileName) ||
[];
if (walletDetails.length === 0) {
vscode.window.showErrorMessage(
`No wallets associated with network ${connectionProfileName}. Please upload the wallets.`
);
return;
}
const walletItem = treeViewProviderWallet.getWalletByLabel(
walletDetails[0].name
);
if (walletItem) {
vscode.window.showInformationMessage(
`Switched to wallet: ${walletDetails[0].name}`
);
} else {
vscode.window.showErrorMessage(
`Wallet not found for network ${connectionProfileName}`
);
}
}
)
);
context.subscriptions.push(
vscode.commands.registerCommand(
"fabric-network.deleteNetwork",
async (treeItem) => {
if (!treeItem || !treeItem.label) {
vscode.window.showErrorMessage("No channel selected for deletion.");
return;
}
async (treeItem) => {
if (!treeItem || !treeItem.label) {
vscode.window.showErrorMessage("No channel selected for deletion.");
return;
}
const channelName = treeItem.label;
const storagePath = context.globalStorageUri.fsPath;
const profilePath = path.join(
storagePath,
`${channelName}-connection.json`
);
const confirmation = await vscode.window.showWarningMessage(
`Are you sure you want to delete the channel "${channelName}"? This action cannot be undone.`,
{ modal: true },
"Delete"
);
if (confirmation === "Delete") {
const wallets =
treeViewProviderWallet.networkWalletMap.get(channelName) || [];
if (wallets.length === 0) {
vscode.window.showErrorMessage(
`No wallets found for channel: ${channelName}`
);
return;
}
for (const wallet of wallets) {
const walletId = wallet.name;
if (walletId) {
await treeViewProviderWallet.deleteWallet(walletId, context);
const walletPath = path.join(
storagePath,
`${walletId}-connection.json`
);
try {
if (fs.existsSync(walletPath)) {
await fs.promises.unlink(walletPath);
}
} catch (error) {
console.error(
`Failed to delete wallet "${walletId}":`,
error
);
}
} else {
console.warn(
`Skipping wallet deletion due to undefined wallet ID for wallet:`,
wallet
);
}
}
if (fs.existsSync(profilePath)) {
try {
await fs.promises.unlink(profilePath);
} catch (error) {
console.error(
`Failed to delete connection profile "${channelName}":`,
error
);
}
} else {
console.warn(
`Connection profile "${channelName}" not found in storage.`
);
}
treeViewProviderFabric.deleteNetwork(channelName);
treeViewProviderDesc.deleteNetwork(channelName);
treeViewProviderWallet.networkWalletMap.delete(channelName);
vscode.window.showInformationMessage(
`Channel "${channelName}" has been deleted.`
);
}
vscode.window.showInformationMessage(
`Channel "${channelName}" has been deleted.`
);
};
}
)
);
context.subscriptions.push(
vscode.commands.registerCommand("wallets.uploadWallet", async () => {
try {
const fileUri = await vscode.window.showOpenDialog({
canSelectFiles: true,
canSelectMany: false,
filters: {
"JSON files": ["json"],
"All files": ["*"],
},
});
if (!fileUri || !fileUri[0]) {
vscode.window.showErrorMessage("No file selected");
return;
}
const fileContents = await fs.promises.readFile(
fileUri[0].fsPath,
"utf8"
);
const walletData = JSON.parse(fileContents);
const walletDetails = extractWalletDetails(walletData);
if (!walletDetails) {
vscode.window.showErrorMessage("Invalid wallet data");
return;
}
const connectionProfiles = Array.from(
treeViewProviderFabric.networks.keys()
);
const selectedProfile = await vscode.window.showQuickPick(
connectionProfiles,
{
placeHolder:
"Select a connection profile to associate with the wallet",
}
);
if (!selectedProfile) {
vscode.window.showWarningMessage(
"Wallet upload cancelled; no connection profile selected."
);
return;
}
walletDetails.connectionProfileName = selectedProfile;
const connectionProfile =
treeViewProviderFabric.networks.get(selectedProfile);
if (!connectionProfile) {
vscode.window.showErrorMessage("Connection profile not found.");
console.warn("Connection profile not found.");
return;
}
if (!connectionProfile.wallets) {
connectionProfile.wallets = [];
}
const existingWallet = connectionProfile.wallets.find(
(w) => w.name === walletDetails.name
);
if (existingWallet) {
console.warn("Wallet already exists.");
return;
} else {
connectionProfile.wallets.push({
name: walletDetails.name,
mspId: walletDetails.mspId,
certificate: walletDetails.certificate,
privateKey: walletDetails.privateKey,
type: walletDetails.type,
});
}
treeViewProviderWallet.addWallet(walletDetails);
await associateWalletToConnectionProfile(context, walletDetails);
loadedConnectionProfile = connectionProfile;
treeViewProviderFabric.networks.set(selectedProfile, connectionProfile);
vscode.window.showInformationMessage(
`Wallet ${walletDetails.name} uploaded and associated with ${selectedProfile} successfully`
);
} catch (error) {
vscode.window.showErrorMessage(
`Error uploading wallet: ${error.message}`
);
console.error("Error uploading wallet:", error);
}
})
);
context.subscriptions.push(
vscode.commands.registerCommand("wallets.switchWallet", (walletItems) => {
if (!Array.isArray(walletItems) || walletItems.length === 0) {
vscode.window.showErrorMessage("No wallets available for selection.");
return;
}
if (walletItems.length === 1) {
const walletItem = walletItems[0];
//treeViewProviderWallet.setActiveWallet(walletItem);
vscode.window.showInformationMessage(
`Switched to wallet for organization: ${walletItem.label}`
);
} else {
vscode.window
.showQuickPick(
walletItems.map((w) => w.label),
{ placeHolder: "Select a wallet to switch to" }
)
.then((selectedOrg) => {
const selectedWallet = walletItems.find(
(w) => w.label === selectedOrg
);
if (selectedWallet) {
//treeViewProviderWallet.setActiveWallet(selectedWallet);
vscode.window.showInformationMessage(
`Switched to wallet for organization: ${selectedOrg}`
);
} else {
vscode.window.showWarningMessage(
`Wallet for organization ${selectedOrg} not found.`
);
}
});
}
})
);
context.subscriptions.push(
vscode.commands.registerCommand(
"wallets.deleteWallet",
async (walletItem) => {
const walletId = walletItem.label.split(" (")[0];
let connectionProfileName = walletItem.connectionProfileName;
if (!connectionProfileName) {
const profiles = Array.from(treeViewProviderFabric.networks.keys());
connectionProfileName = await vscode.window.showQuickPick(profiles, {
placeHolder: `Select the network for wallet "${walletId}"`,
});
if (!connectionProfileName) {
vscode.window.showErrorMessage(
"No network selected; deletion canceled."
);
return;
}
}
const confirmation = await vscode.window.showWarningMessage(
`Are you sure you want to delete the wallet "${walletId}"?`,
{ modal: true },
"Delete"
);
if (confirmation === "Delete") {
const profilePath = path.join(
context.globalStorageUri.fsPath,
`${connectionProfileName}-connection.json`
);
try {
const profileData = JSON.parse(
await fs.promises.readFile(profilePath, "utf8")
);
profileData.wallets = profileData.wallets.filter(
(wallet) => wallet.name !== walletId
);
await fs.promises.writeFile(
profilePath,
JSON.stringify(profileData, null, 2),
"utf8"
);
treeViewProviderWallet.deleteWallet(walletId, context);
vscode.window.showInformationMessage(
`Wallet "${walletId}" deleted.`
);
} catch (error) {
console.error(`Failed to delete wallet "${walletId}":`, error);
vscode.window.showErrorMessage(
`Failed to delete wallet "${walletId}".`
);
}
}
}
)
);
context.subscriptions.push(
vscode.commands.registerCommand("fabric-network.queryBlocks", async () => {
if (!loadedConnectionProfile || !loadedConnectionProfile.name) {
console.error(
"Connection profile not loaded. Unable to query latest blocks."
);
vscode.window.showErrorMessage("Connection profile not loaded.");
return;
}
const connectionProfileName = loadedConnectionProfile.name;
const walletDetails =
treeViewProviderWallet.networkWalletMap.get(connectionProfileName) ||
[];
//console.log("Wallet structure:", walletDetails);
if (!walletDetails || walletDetails.length === 0) {
console.error(
`No wallets associated with network ${connectionProfileName}.`
);
vscode.window.showErrorMessage(
"No wallets found. Please upload the wallets."
);
return;
}
const invalidWallets = walletDetails.filter(
(wallet) => !wallet.name || !wallet.certificate || !wallet.privateKey
);
if (invalidWallets.length > 0) {
console.error(
"Invalid wallet item(s) provided for activation:",
invalidWallets
);
vscode.window.showErrorMessage(
"Invalid wallet data found. Please check wallet structure."
);
return;
}
try {
const latestBlockNumber = await getLatestBlockNumber(
loadedConnectionProfile
);
if (!latestBlockNumber) {
vscode.window.showErrorMessage(
"Failed to retrieve latest block number."
);
return;
}
console.log(`Latest block number: ${latestBlockNumber}`);
const numOfBlocksInput = await vscode.window.showInputBox({
prompt: `Enter the number of latest blocks to query (up to ${latestBlockNumber}):`,
});
const numOfBlocks = parseInt(numOfBlocksInput, 10);
console.log(`User input for number of blocks: ${numOfBlocks}`);
if (
isNaN(numOfBlocks) ||
numOfBlocks <= 0 ||
numOfBlocks > latestBlockNumber
) {
vscode.window.showErrorMessage(
"Invalid number of blocks. Please enter a valid number."
);
return;
}
for (let i = 0; i < numOfBlocks; i++) {
const blockNumber = latestBlockNumber - i;
console.log(`Querying block number: ${blockNumber}`);
vscode.window.showInformationMessage(
`Querying block number: ${blockNumber}`
);
const block = await connectToFabric(
loadedConnectionProfile,
blockNumber
);
if (block) {
console.log("Block data:", block);
vscode.window.showInformationMessage(
`Successfully queried block ${blockNumber}. Block Hash: ${block.header.data_hash}`
);
} else {
vscode.window.showErrorMessage(`Block ${blockNumber} not found.`);
}
}
} catch (error) {
vscode.window.showErrorMessage(`Error: ${error.message}`);
console.error("Error during block query:", error);
}
})
);
async function associateWalletToConnectionProfile(context, wallet) {
if (!loadedConnectionProfile) {
vscode.window.showErrorMessage("No connection profile loaded.");
return;
}
if (!loadedConnectionProfile.wallets) {
loadedConnectionProfile.wallets = [];
}
const existingWallet = loadedConnectionProfile.wallets.find(
(w) => w.name === wallet.name
);
if (!existingWallet) {
loadedConnectionProfile.wallets.push(wallet);
try {
await saveConnectionProfileToStorage(context, loadedConnectionProfile);
} catch (error) {
vscode.window.showErrorMessage(
"Failed to save the updated connection profile."
);
}
} else {
vscode.window.showErrorMessage(
`Wallet "${wallet.name}" is already associated.`
);
}
}
function extractNetworkDetails(profile) {
const organizations = Object.keys(profile.organizations || {});
const peers = Object.values(profile.peers || {}).map((peer) => peer.url);
const orderers = Object.values(profile.orderers || {}).map(
(orderer) => orderer.url
);
const cas = Object.values(profile.certificateAuthorities || {}).map(
(ca) => ca.url
);
return { organizations, peers, orderers, cas };
}
}
function extractWalletsFromProfile(profile) {
const wallets = [];
if (profile.organizations) {
Object.keys(profile.organizations).forEach((orgKey) => {
const orgData = profile.organizations[orgKey];
const keyPath = orgData.adminPrivateKey?.path;
const certPath = orgData.signedCert?.path;
const privateKey = orgData.adminPrivateKey?.privateKey;
const certificate = orgData.signedCert?.certificate;
if (
keyPath &&
certPath &&
fs.existsSync(keyPath) &&
fs.existsSync(certPath)
) {
const wallet = {
connectionProfileName: profile.name,
name: orgKey,
mspId: orgData.mspid,
certPath: certPath,
keyPath: keyPath,
type: "X.509",
credentials: {
certificate: fs.readFileSync(certPath).toString(),
privateKey: fs.readFileSync(keyPath).toString(),
},
};
wallets.push(wallet);
} else if (privateKey && certificate) {
const wallet = {
connectionProfileName: profile.name,
name: orgKey,
mspId: orgData.mspid,
type: "X.509",
credentials: {
certificate: certificate,
privateKey: privateKey,
},
};
wallets.push(wallet);
}
});
}
return wallets;
}
function extractWalletDetails(walletData) {
if (
walletData &&
(walletData.credentials ||
walletData.signedCert ||
walletData.adminPrivateKey)
) {
const {
name = walletData.name || "Unknown Wallet",
mspId = walletData.mspId || "Unknown MSP",
type = walletData.type || "Unknown Type",
credentials = {},
} = walletData;
}
}
function deactivate() {}
module.exports = {
activate,
deactivate,
};