FAB-17456 fabric-samples read ccp (#117)

Have the application read the common connection profile to
build a JSON object used for the gateway connect and for
a fabric-ca client instance.

Signed-off-by: Bret Harrison <beharrison@nc.rr.com>
This commit is contained in:
harrisob 2020-02-18 09:05:50 -05:00 committed by GitHub
parent 965ed1fa84
commit 3dbe116a30
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
19 changed files with 141 additions and 4995 deletions

View file

@ -6,7 +6,9 @@ steps:
- script: bash startFabric.sh javascript - script: bash startFabric.sh javascript
workingDirectory: fabcar workingDirectory: fabcar
displayName: Start Fabric displayName: Start Fabric
- script: retry -- npm install - script: |
retry -- npm install
npm ls
workingDirectory: fabcar/javascript workingDirectory: fabcar/javascript
displayName: Install FabCar application dependencies displayName: Install FabCar application dependencies
- script: | - script: |

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -9,12 +9,11 @@ const { Wallets } = require('fabric-network');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const ccpPath = path.resolve(__dirname, '..', '..', 'first-network', 'connection-org1.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);
async function main() { async function main() {
try { try {
// load the network configuration
const ccpPath = path.resolve(__dirname, '..', '..', 'first-network', 'connection-org1.json');
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
// Create a new CA client for interacting with the CA. // Create a new CA client for interacting with the CA.
const caInfo = ccp.certificateAuthorities['ca.org1.example.com']; const caInfo = ccp.certificateAuthorities['ca.org1.example.com'];

View file

@ -5,12 +5,14 @@
'use strict'; 'use strict';
const { Gateway, Wallets } = require('fabric-network'); const { Gateway, Wallets } = require('fabric-network');
const fs = require('fs');
const path = require('path'); const path = require('path');
const ccpPath = path.resolve(__dirname, '..', '..', 'first-network', 'connection-org1.json');
async function main() { async function main() {
try { try {
// load the network configuration
const ccpPath = path.resolve(__dirname, '..', '..', 'first-network', 'connection-org1.json');
let ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
// Create a new file system based wallet for managing identities. // Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet'); const walletPath = path.join(process.cwd(), 'wallet');
@ -27,7 +29,7 @@ async function main() {
// Create a new gateway for connecting to our peer node. // Create a new gateway for connecting to our peer node.
const gateway = new Gateway(); const gateway = new Gateway();
await gateway.connect(ccpPath, { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: true } }); await gateway.connect(ccp, { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: true } });
// Get the network (channel) our contract is deployed to. // Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('mychannel'); const network = await gateway.getNetwork('mychannel');

View file

@ -15,7 +15,6 @@
"author": "Hyperledger", "author": "Hyperledger",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"fabric-client": "beta",
"fabric-ca-client": "beta", "fabric-ca-client": "beta",
"fabric-network": "beta" "fabric-network": "beta"
}, },

View file

@ -6,11 +6,14 @@
const { Gateway, Wallets } = require('fabric-network'); const { Gateway, Wallets } = require('fabric-network');
const path = require('path'); const path = require('path');
const fs = require('fs');
const ccpPath = path.resolve(__dirname, '..', '..', 'first-network', 'connection-org1.json');
async function main() { async function main() {
try { try {
// load the network configuration
const ccpPath = path.resolve(__dirname, '..', '..', 'first-network', 'connection-org1.json');
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
// Create a new file system based wallet for managing identities. // Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet'); const walletPath = path.join(process.cwd(), 'wallet');
@ -27,7 +30,7 @@ async function main() {
// Create a new gateway for connecting to our peer node. // Create a new gateway for connecting to our peer node.
const gateway = new Gateway(); const gateway = new Gateway();
await gateway.connect(ccpPath, { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: true } }); await gateway.connect(ccp, { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: true } });
// Get the network (channel) our contract is deployed to. // Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('mychannel'); const network = await gateway.getNetwork('mychannel');

View file

@ -4,13 +4,20 @@
'use strict'; 'use strict';
const { Gateway, Wallets } = require('fabric-network'); const { Wallets } = require('fabric-network');
const FabricCAServices = require('fabric-ca-client');
const fs = require('fs');
const path = require('path'); const path = require('path');
const ccpPath = path.resolve(__dirname, '..', '..', 'first-network', 'connection-org1.json');
async function main() { async function main() {
try { try {
// load the network configuration
const ccpPath = path.resolve(__dirname, '..', '..', 'first-network', 'connection-org1.json');
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
// Create a new CA client for interacting with the CA.
const caURL = ccp.certificateAuthorities['ca.org1.example.com'].url;
const ca = new FabricCAServices(caURL);
// Create a new file system based wallet for managing identities. // Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet'); const walletPath = path.join(process.cwd(), 'wallet');
@ -32,18 +39,20 @@ async function main() {
return; return;
} }
// Create a new gateway for connecting to our peer node. // build a user object for authenticating with the CA
const gateway = new Gateway(); const provider = wallet.getProviderRegistry().getProvider(adminIdentity.type);
await gateway.connect(ccpPath, { wallet, identity: 'admin', discovery: { enabled: true, asLocalhost: true } }); const adminUser = await provider.getUserContext(adminIdentity, 'admin');
// Get the CA client object from the gateway for interacting with the CA.
const client = gateway.getClient();
const ca = client.getCertificateAuthority();
const adminUser = await client.getUserContext('admin', false);
// Register the user, enroll the user, and import the new identity into the wallet. // Register the user, enroll the user, and import the new identity into the wallet.
const secret = await ca.register({ affiliation: 'org1.department1', enrollmentID: 'user1', role: 'client' }, adminUser); const secret = await ca.register({
const enrollment = await ca.enroll({ enrollmentID: 'user1', enrollmentSecret: secret }); affiliation: 'org1.department1',
enrollmentID: 'user1',
role: 'client'
}, adminUser);
const enrollment = await ca.enroll({
enrollmentID: 'user1',
enrollmentSecret: secret
});
const x509Identity = { const x509Identity = {
credentials: { credentials: {
certificate: enrollment.certificate, certificate: enrollment.certificate,

View file

@ -7,12 +7,11 @@ import { Wallets, X509Identity } from 'fabric-network';
import * as fs from 'fs'; import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';
const ccpPath = path.resolve(__dirname, '..', '..', '..', 'first-network', 'connection-org1.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);
async function main() { async function main() {
try { try {
// load the network configuration
const ccpPath = path.resolve(__dirname, '..', '..', '..', 'first-network', 'connection-org1.json');
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
// Create a new CA client for interacting with the CA. // Create a new CA client for interacting with the CA.
const caInfo = ccp.certificateAuthorities['ca.org1.example.com']; const caInfo = ccp.certificateAuthorities['ca.org1.example.com'];

View file

@ -4,11 +4,13 @@
import { Gateway, Wallets } from 'fabric-network'; import { Gateway, Wallets } from 'fabric-network';
import * as path from 'path'; import * as path from 'path';
import * as fs from 'fs';
const ccpPath = path.resolve(__dirname, '..', '..', '..', 'first-network', 'connection-org1.json');
async function main() { async function main() {
try { try {
// load the network configuration
const ccpPath = path.resolve(__dirname, '..', '..', '..', 'first-network', 'connection-org1.json');
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
// Create a new file system based wallet for managing identities. // Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet'); const walletPath = path.join(process.cwd(), 'wallet');
@ -25,7 +27,7 @@ async function main() {
// Create a new gateway for connecting to our peer node. // Create a new gateway for connecting to our peer node.
const gateway = new Gateway(); const gateway = new Gateway();
await gateway.connect(ccpPath, { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: true } }); await gateway.connect(ccp, { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: true } });
// Get the network (channel) our contract is deployed to. // Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('mychannel'); const network = await gateway.getNetwork('mychannel');

View file

@ -4,11 +4,14 @@
import { Gateway, Wallets } from 'fabric-network'; import { Gateway, Wallets } from 'fabric-network';
import * as path from 'path'; import * as path from 'path';
import * as fs from 'fs';
const ccpPath = path.resolve(__dirname, '..', '..', '..', 'first-network', 'connection-org1.json');
async function main() { async function main() {
try { try {
// load the network configuration
const ccpPath = path.resolve(__dirname, '..', '..', '..', 'first-network', 'connection-org1.json');
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
// Create a new file system based wallet for managing identities. // Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet'); const walletPath = path.join(process.cwd(), 'wallet');
@ -25,7 +28,7 @@ async function main() {
// Create a new gateway for connecting to our peer node. // Create a new gateway for connecting to our peer node.
const gateway = new Gateway(); const gateway = new Gateway();
await gateway.connect(ccpPath, { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: true } }); await gateway.connect(ccp, { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: true } });
// Get the network (channel) our contract is deployed to. // Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('mychannel'); const network = await gateway.getNetwork('mychannel');

View file

@ -2,13 +2,20 @@
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
*/ */
import { Gateway, Wallets, X509Identity } from 'fabric-network'; import { Wallets, X509Identity } from 'fabric-network';
import * as FabricCAServices from 'fabric-ca-client';
import * as path from 'path'; import * as path from 'path';
import * as fs from 'fs';
const ccpPath = path.resolve(__dirname, '..', '..', '..', 'first-network', 'connection-org1.json');
async function main() { async function main() {
try { try {
// load the network configuration
const ccpPath = path.resolve(__dirname, '..', '..', '..', 'first-network', 'connection-org1.json');
let ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
// Create a new CA client for interacting with the CA.
const caURL = ccp.certificateAuthorities['ca.org1.example.com'].url;
const ca = new FabricCAServices(caURL);
// Create a new file system based wallet for managing identities. // Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet'); const walletPath = path.join(process.cwd(), 'wallet');
@ -30,14 +37,9 @@ async function main() {
return; return;
} }
// Create a new gateway for connecting to our peer node. // build a user object for authenticating with the CA
const gateway = new Gateway(); const provider = wallet.getProviderRegistry().getProvider(adminIdentity.type);
await gateway.connect(ccpPath, { wallet, identity: 'admin', discovery: { enabled: true, asLocalhost: true } }); const adminUser = await provider.getUserContext(adminIdentity, 'admin');
// Get the CA client object from the gateway for interacting with the CA.
const client = gateway.getClient();
const ca = client.getCertificateAuthority();
const adminUser = await client.getUserContext('admin', false);
// Register the user, enroll the user, and import the new identity into the wallet. // Register the user, enroll the user, and import the new identity into the wallet.
const secret = await ca.register({ affiliation: 'org1.department1', enrollmentID: 'user1', role: 'client' }, adminUser); const secret = await ca.register({ affiliation: 'org1.department1', enrollmentID: 'user1', role: 'client' }, adminUser);

View file

@ -2,7 +2,7 @@
* Copyright IBM Corp. All Rights Reserved. * Copyright IBM Corp. All Rights Reserved.
* *
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
* *
*/ */
/* /*
@ -28,7 +28,7 @@
'use strict'; 'use strict';
const { FileSystemWallet, Gateway } = require('fabric-network'); const { Wallets, Gateway } = require('fabric-network');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
@ -75,12 +75,12 @@ async function main() {
// Configure a wallet. This wallet must already be primed with an identity that // Configure a wallet. This wallet must already be primed with an identity that
// the application can use to interact with the peer node. // the application can use to interact with the peer node.
const walletPath = path.resolve(__dirname, 'wallet'); const walletPath = path.resolve(__dirname, 'wallet');
const wallet = new FileSystemWallet(walletPath); const wallet = await Wallets.newFileSystemWallet(walletPath);
// Create a new gateway, and connect to the gateway peer node(s). The identity // Create a new gateway, and connect to the gateway peer node(s). The identity
// specified must already exist in the specified wallet. // specified must already exist in the specified wallet.
const gateway = new Gateway(); const gateway = new Gateway();
await gateway.connect(ccpPath, { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: true } }); await gateway.connect(ccp, { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: true } });
// Get the network channel that the smart contract is deployed to. // Get the network channel that the smart contract is deployed to.
const network = await gateway.getNetwork(channelid); const network = await gateway.getNetwork(channelid);

View file

@ -2,7 +2,7 @@
* Copyright IBM Corp. All Rights Reserved. * Copyright IBM Corp. All Rights Reserved.
* *
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
* *
*/ */
/* /*
@ -40,17 +40,13 @@ is automatically created and initialized to zero if it does not exist.
'use strict'; 'use strict';
const { FileSystemWallet, Gateway } = require('fabric-network'); const { Wallets, Gateway } = require('fabric-network');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const couchdbutil = require('./couchdbutil.js'); const couchdbutil = require('./couchdbutil.js');
const blockProcessing = require('./blockProcessing.js'); const blockProcessing = require('./blockProcessing.js');
const ccpPath = path.resolve(__dirname, '..', 'first-network', 'connection-org1.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);
const config = require('./config.json'); const config = require('./config.json');
const channelid = config.channelid; const channelid = config.channelid;
const peer_name = config.peer_name; const peer_name = config.peer_name;
@ -98,26 +94,30 @@ async function main() {
// Create a new file system based wallet for managing identities. // Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet'); const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath); const wallet = await Wallets.newFileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`); console.log(`Wallet path: ${walletPath}`);
// Check to see if we've already enrolled the user. // Check to see if we've already enrolled the user.
const userExists = await wallet.exists('user1'); const userExists = await wallet.get('user1');
if (!userExists) { if (!userExists) {
console.log('An identity for the user "user1" does not exist in the wallet'); console.log('An identity for the user "user1" does not exist in the wallet');
console.log('Run the enrollUser.js application before retrying'); console.log('Run the enrollUser.js application before retrying');
return; return;
} }
// Parse the connection profile. This would be the path to the file downloaded
// from the IBM Blockchain Platform operational console.
const ccpPath = path.resolve(__dirname, '..', 'first-network', 'connection-org1.json');
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
// Create a new gateway for connecting to our peer node. // Create a new gateway for connecting to our peer node.
const gateway = new Gateway(); const gateway = new Gateway();
await gateway.connect(ccpPath, { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: true } }); await gateway.connect(ccp, { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: true } });
// Get the network (channel) our contract is deployed to. // Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('mychannel'); const network = await gateway.getNetwork('mychannel');
const listener = await network.addBlockListener('offchain-listener', const listener = await network.addBlockListener(
async (err, block) => { async (err, blockNum, block) => {
if (err) { if (err) {
console.error(err); console.error(err);
return; return;
@ -125,10 +125,10 @@ async function main() {
// Add the block to the processing map by block number // Add the block to the processing map by block number
await ProcessingMap.set(block.header.number, block); await ProcessingMap.set(block.header.number, block);
console.log(`Added block ${block.header.number} to ProcessingMap`) console.log(`Added block ${blockNum} to ProcessingMap`)
}, },
// set the starting block for the listener // set the starting block for the listener
{ startBlock: parseInt(nextBlock, 10) } { filtered: false, startBlock: parseInt(nextBlock, 10) }
); );
console.log(`Listening for block events, nextblock: ${nextBlock}`); console.log(`Listening for block events, nextblock: ${nextBlock}`);

View file

@ -50,14 +50,14 @@ exports.processBlockEvent = async function (channelname, block, use_couchdb, nan
// filter through valid tx, refer below for list of error codes // filter through valid tx, refer below for list of error codes
// https://github.com/hyperledger/fabric-sdk-node/blob/release-1.4/fabric-client/lib/protos/peer/transaction.proto // https://github.com/hyperledger/fabric-sdk-node/blob/release-1.4/fabric-client/lib/protos/peer/transaction.proto
if (txSuccess[dataItem] !== 0) { if (txSuccess[dataItem] !== 0) {
continue(); continue;
} }
const timestamp = dataArray[dataItem].payload.header.channel_header.timestamp; const timestamp = dataArray[dataItem].payload.header.channel_header.timestamp;
// continue to next tx if no actions are set // continue to next tx if no actions are set
if (dataArray[dataItem].payload.data.actions == undefined) { if (dataArray[dataItem].payload.data.actions == undefined) {
continue(); continue;
} }
// actions are stored as an array. In Fabric 1.4.3 only one // actions are stored as an array. In Fabric 1.4.3 only one

View file

@ -2,7 +2,7 @@
* Copyright IBM Corp. All Rights Reserved. * Copyright IBM Corp. All Rights Reserved.
* *
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
* *
*/ */
/* /*
@ -16,7 +16,7 @@
'use strict'; 'use strict';
const { FileSystemWallet, Gateway } = require('fabric-network'); const { Wallets, Gateway } = require('fabric-network');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
@ -42,12 +42,12 @@ async function main() {
// Configure a wallet. This wallet must already be primed with an identity that // Configure a wallet. This wallet must already be primed with an identity that
// the application can use to interact with the peer node. // the application can use to interact with the peer node.
const walletPath = path.resolve(__dirname, 'wallet'); const walletPath = path.resolve(__dirname, 'wallet');
const wallet = new FileSystemWallet(walletPath); const wallet = await Wallets.newFileSystemWallet(walletPath);
// Create a new gateway, and connect to the gateway peer node(s). The identity // Create a new gateway, and connect to the gateway peer node(s). The identity
// specified must already exist in the specified wallet. // specified must already exist in the specified wallet.
const gateway = new Gateway(); const gateway = new Gateway();
await gateway.connect(ccpPath, { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: true } }); await gateway.connect(ccp, { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: true } });
// Get the network channel that the smart contract is deployed to. // Get the network channel that the smart contract is deployed to.
const network = await gateway.getNetwork(channelid); const network = await gateway.getNetwork(channelid);

View file

@ -2,22 +2,21 @@
* Copyright IBM Corp. All Rights Reserved. * Copyright IBM Corp. All Rights Reserved.
* *
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
* *
*/ */
'use strict'; 'use strict';
const FabricCAServices = require('fabric-ca-client'); const FabricCAServices = require('fabric-ca-client');
const { FileSystemWallet, X509WalletMixin } = require('fabric-network'); const { Wallets, X509WalletMixin } = require('fabric-network');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const ccpPath = path.resolve(__dirname, '..', 'first-network', 'connection-org1.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);
async function main() { async function main() {
try { try {
// load the network configuration
const ccpPath = path.resolve(__dirname, '..', 'first-network', 'connection-org1.json');
let ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
// Create a new CA client for interacting with the CA. // Create a new CA client for interacting with the CA.
const caURL = ccp.certificateAuthorities['ca.org1.example.com'].url; const caURL = ccp.certificateAuthorities['ca.org1.example.com'].url;
@ -25,11 +24,11 @@ async function main() {
// Create a new file system based wallet for managing identities. // Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet'); const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath); const wallet = await Wallets.newFileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`); console.log(`Wallet path: ${walletPath}`);
// Check to see if we've already enrolled the admin user. // Check to see if we've already enrolled the admin user.
const adminExists = await wallet.exists('admin'); const adminExists = await wallet.get('admin');
if (adminExists) { if (adminExists) {
console.log('An identity for the admin user "admin" already exists in the wallet'); console.log('An identity for the admin user "admin" already exists in the wallet');
return; return;
@ -37,8 +36,15 @@ async function main() {
// Enroll the admin user, and import the new identity into the wallet. // Enroll the admin user, and import the new identity into the wallet.
const enrollment = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'adminpw' }); const enrollment = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'adminpw' });
const identity = X509WalletMixin.createIdentity('Org1MSP', enrollment.certificate, enrollment.key.toBytes()); const x509Identity = {
wallet.import('admin', identity); credentials: {
certificate: enrollment.certificate,
privateKey: enrollment.key.toBytes(),
},
mspId: 'Org1MSP',
type: 'X.509',
};
await wallet.put('admin', x509Identity);
console.log('Successfully enrolled admin user "admin" and imported it into the wallet'); console.log('Successfully enrolled admin user "admin" and imported it into the wallet');
} catch (error) { } catch (error) {

View file

@ -2,55 +2,69 @@
* Copyright IBM Corp. All Rights Reserved. * Copyright IBM Corp. All Rights Reserved.
* *
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
* *
*/ */
'use strict'; 'use strict';
const { FileSystemWallet, Gateway, X509WalletMixin } = require('fabric-network'); const { Wallets, Gateway, X509WalletMixin } = require('fabric-network');
const FabricCAServices = require('fabric-ca-client');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const ccpPath = path.resolve(__dirname, '..', 'first-network', 'connection-org1.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);
async function main() { async function main() {
try { try {
// load the network configuration
const ccpPath = path.resolve(__dirname, '..', 'first-network', 'connection-org1.json');
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
// Create a new CA client for interacting with the CA.
const caURL = ccp.certificateAuthorities['ca.org1.example.com'].url;
const ca = new FabricCAServices(caURL);
// Create a new file system based wallet for managing identities. // Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet'); const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath); const wallet = await Wallets.newFileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`); console.log(`Wallet path: ${walletPath}`);
// Check to see if we've already enrolled the user. // Check to see if we've already enrolled the user.
const userExists = await wallet.exists('user1'); const userExists = await wallet.get('user1');
if (userExists) { if (userExists) {
console.log('An identity for the user "user1" already exists in the wallet'); console.log('An identity for the user "user1" already exists in the wallet');
return; return;
} }
// Check to see if we've already enrolled the admin user. // Check to see if we've already enrolled the admin user.
const adminExists = await wallet.exists('admin'); const adminIdentity = await wallet.get('admin');
if (!adminExists) { if (!adminIdentity) {
console.log('An identity for the admin user "admin" does not exist in the wallet'); console.log('An identity for the admin user "admin" does not exist in the wallet');
console.log('Run the enrollAdmin.js application before retrying'); console.log('Run the enrollAdmin.js application before retrying');
return; return;
} }
// Create a new gateway for connecting to our peer node. // build a user object for authenticating with the CA
const gateway = new Gateway(); const provider = wallet.getProviderRegistry().getProvider(adminIdentity.type);
await gateway.connect(ccp, { wallet, identity: 'admin', discovery: { enabled: false } }); const adminUser = await provider.getUserContext(adminIdentity, 'admin');
// Get the CA client object from the gateway for interacting with the CA.
const ca = gateway.getClient().getCertificateAuthority();
const adminIdentity = gateway.getCurrentIdentity();
// Register the user, enroll the user, and import the new identity into the wallet. // Register the user, enroll the user, and import the new identity into the wallet.
const secret = await ca.register({ affiliation: 'org1.department1', enrollmentID: 'user1', role: 'client' }, adminIdentity); const secret = await ca.register({
const enrollment = await ca.enroll({ enrollmentID: 'user1', enrollmentSecret: secret }); affiliation: 'org1.department1',
const userIdentity = X509WalletMixin.createIdentity('Org1MSP', enrollment.certificate, enrollment.key.toBytes()); enrollmentID: 'user1',
wallet.import('user1', userIdentity); role: 'client'
}, adminUser);
const enrollment = await ca.enroll({
enrollmentID: 'user1',
enrollmentSecret: secret
});
const x509Identity = {
credentials: {
certificate: enrollment.certificate,
privateKey: enrollment.key.toBytes(),
},
mspId: 'Org1MSP',
type: 'X.509',
};
await wallet.put('user1', x509Identity);
console.log('Successfully registered and enrolled admin user "user1" and imported it into the wallet'); console.log('Successfully registered and enrolled admin user "user1" and imported it into the wallet');
} catch (error) { } catch (error) {

View file

@ -15,7 +15,7 @@
'use strict'; 'use strict';
const { FileSystemWallet, Gateway } = require('fabric-network'); const { Wallets, Gateway } = require('fabric-network');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
@ -42,12 +42,12 @@ async function main() {
// Configure a wallet. This wallet must already be primed with an identity that // Configure a wallet. This wallet must already be primed with an identity that
// the application can use to interact with the peer node. // the application can use to interact with the peer node.
const walletPath = path.resolve(__dirname, 'wallet'); const walletPath = path.resolve(__dirname, 'wallet');
const wallet = new FileSystemWallet(walletPath); const wallet = await Wallets.newFileSystemWallet(walletPath);
// Create a new gateway, and connect to the gateway peer node(s). The identity // Create a new gateway, and connect to the gateway peer node(s). The identity
// specified must already exist in the specified wallet. // specified must already exist in the specified wallet.
const gateway = new Gateway(); const gateway = new Gateway();
await gateway.connect(ccpPath, { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: true } }); await gateway.connect(ccp, { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: true } });
// Get the network channel that the smart contract is deployed to. // Get the network channel that the smart contract is deployed to.
const network = await gateway.getNetwork(channelid); const network = await gateway.getNetwork(channelid);