matiru
Blockchain-Based Supply Chain Transparency for Agricultural Producegit clone https://github.com/maydayv7/matiru
backend/initWallet.js (2143B)
1"use strict";
2const fs = require("fs");
3const path = require("path");
4const { Wallets } = require("fabric-network");
5
6async function main() {
7 try {
8 const args = process.argv.slice(2);
9 if (args.length < 4) {
10 console.log(
11 "Usage: node addToWallet.js org<num> <userFolder> <walletDir> <identityLabel>"
12 );
13 process.exit(1);
14 }
15 const [org, userFolder, walletDir, identityLabel] = args;
16
17 // Determine MSP ID
18 const orgMatch = org.match(/^org(\d+)$/i);
19 if (!orgMatch) {
20 console.error(
21 `Invalid org argument: ${org}. Must be like "org1", "org2", etc.`
22 );
23 process.exit(1);
24 }
25 const orgNum = orgMatch[1];
26 const mspId = `Org${orgNum}MSP`;
27
28 const userMspPath = path.resolve(userFolder);
29 if (!fs.existsSync(userMspPath)) {
30 console.error("User MSP folder not found:", userMspPath);
31 process.exit(1);
32 }
33
34 // Read certificate file
35 const certPath = path.join(userMspPath, "signcerts");
36 const certFiles = fs.readdirSync(certPath);
37 if (certFiles.length === 0) {
38 console.error("No cert files found in", certPath);
39 process.exit(1);
40 }
41 const cert = fs.readFileSync(path.join(certPath, certFiles[0])).toString();
42
43 // Read private key file
44 const keyPath = path.join(userMspPath, "keystore");
45 const keyFiles = fs.readdirSync(keyPath);
46 if (keyFiles.length === 0) {
47 console.error("No key files found in", keyPath);
48 process.exit(1);
49 }
50 const key = fs.readFileSync(path.join(keyPath, keyFiles[0])).toString();
51
52 // Create wallet
53 const walletPath = path.resolve(walletDir);
54 const wallet = await Wallets.newFileSystemWallet(walletPath);
55
56 const identity = {
57 credentials: {
58 certificate: cert,
59 privateKey: key,
60 },
61 mspId: mspId,
62 type: "X.509",
63 };
64
65 await wallet.put(identityLabel, identity);
66 console.log(
67 `Successfully added identity ${identityLabel} to wallet at ${walletPath}`
68 );
69 process.exit(0);
70 } catch (err) {
71 console.error("Error importing identity to wallet:", err);
72 process.exit(1);
73 }
74}
75
76main();