Skip to content

Commit

Permalink
use peer org cert to install on local hyperledger
Browse files Browse the repository at this point in the history
  • Loading branch information
dshuffma-ibm committed Apr 7, 2018
1 parent 7de16b8 commit 983aefd
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 59 deletions.
9 changes: 6 additions & 3 deletions config/connection_profile_local.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"client": {
"organization": "Org1MSP",
"credentialStore": {
"path": "/home/ibmadmin/fabric-samples/fabcar/hfc-key-store"
"path": "/$HOME/fabric-samples/fabcar/hfc-key-store"
}
},
"channels": {
Expand Down Expand Up @@ -38,8 +38,11 @@
"certificateAuthorities": [
"fabric-ca"
],
"x-certJson": {
"path": "/home/ibmadmin/fabric-samples/fabcar/hfc-key-store/admin"
"x-adminCert": {
"path": "/$HOME/fabric-samples/basic-network/crypto-config/peerOrganizations/org1.example.com/users/[email protected]/msp/admincerts/[email protected]"
},
"x-adminKeyStore": {
"path": "/$HOME/fabric-samples/basic-network/crypto-config/peerOrganizations/org1.example.com/users/[email protected]/msp/keystore/"
}
}
},
Expand Down
28 changes: 12 additions & 16 deletions docs/use_local_hyperledger.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ These instructions have been tested on Ubuntu 14 and OSX. It may work for Windo

* Bash - Bash scripts are needed to setup installation files
* [GoLang](https://golang.org/) - 1.7.0 or higher
* [Docker](https://www.docker.com/products/overview) - v1.13 or higher
* [Docker Compose](https://docs.docker.com/compose/overview/) - v1.8 or higher
* [Node.js](https://nodejs.org/en/download/) - node v6.2.0 - v6.11.1 **(v7+ not supported)**
* [Docker CE](https://www.docker.com/get-docker) - v1.13 or higher
* [Docker Compose](https://docs.docker.com/compose/install/) - v1.8 or higher
* [Node.js](https://nodejs.org/en/download/) - node v6.2+ or v8.1+ **(v9 is not supported, v7 support is unknown)**
* [xcode](https://developer.apple.com/xcode/) - only required for **OS X** users

## 1. Download Fabric Samples
Expand All @@ -18,7 +18,7 @@ We are going to hijack the [Hyperledger Fabric samples](http://hyperledger-fabri
Their code has the setup for a Fabric network as well as example chaincode.
We will only be using the network setup part.

Download their samples with the command:
Download their node samples with the command:

```bash
git clone https://github.com/hyperledger/fabric-samples.git
Expand All @@ -28,7 +28,7 @@ cd fabric-samples
Once you have cloned the repository start downloading the docker images of the various fabric components.

```bash
curl -sSL https://raw.githubusercontent.com/hyperledger/fabric/release/scripts/bootstrap-1.0.4.sh -o setup_script.sh
curl -sSL https://raw.githubusercontent.com/hyperledger/fabric/release-1.1/scripts/bootstrap-1.1.0-preview.sh -o setup_script.sh
sudo bash setup_script.sh
```

Expand All @@ -45,7 +45,7 @@ Run the script below to get everything going.

```bash
cd ./fabcar
./startFabric.sh
sudo ./startFabric.sh
```

After a minute or two the command prompt will return.
Expand Down Expand Up @@ -77,6 +77,8 @@ Before we run `fabcar` we need to install its npm dependencies:
sudo npm install
```

- If you get a permission error such as `Error: EACCES: permission denied` on a `pkcs11js` folder try running this command `sudo npm install pkcs11js --unsafe-perm=true --allow-root`. Then re-run `sudo npm install`.

It's important that the install returned with no errors (warnings are fine).
If you have npm installation errors you will have to decipher those on your own!
Good luck.
Expand All @@ -85,21 +87,14 @@ Good luck.
Finally lets test the network before we run marbles.
Run query via `fabcar` with the commands:

```bash
node enrollAdmin.js
node registerUser.js
node query.js
```

The correct responses will look _similar_ to:


Run the command __node enrollAdmin.js__. The response should be _similar_ to:
```
Store path:/home/ibmadmin/fabric-samples/fabcar/hfc-key-store
Successfully enrolled admin user "admin"
Assigned the admin user to the fabric client ::{"name":"admin","mspid":"Org1MSP","roles":null,"affiliation":"","enrollmentSecret":"",390e3bbbcfa819e338","identity":{"certificate":"-----BEGIN CERTIFICATE-----\nMIIB8TCCAZegAwIBAgIUENLgPE9seEysP/jBDTdmRCUyR30wCgYIKoZIzcmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMT\nE2NhLm9yZzEuZXhhbXBsZS5jb20wHhcNMTcxMjIyMTYxMDAwWhcNMTgxMjIyMTYx\nMDAwWoAFxMrB3wQ98E/bvqi3s2ilWee3p/mkyc98EtzGFDPzuw7\ne+A6kiPjkuaeeRteWqNsjaijbDBqMA4GA1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8E\nAjAAMB0GA1UdDgQWBBRrGpXNl5JfDAKBggqhkjOPQQDAgNIADBF\nAiEAkraZL5xVq/GBysqdcB+yD0T6eMWZoN/DFLbS4W5O+7gCIC675hXxxcfIe4aD\njM8ikcptiP9V4I3nE/RVB8qqtAV7\n---
```

Run the command __node registerUser.js__. The response should be _similar_ to:
```
Store path:/home/ibmadmin/fabric-samples/fabcar/hfc-key-store
Successfully loaded admin from persistence
Expand All @@ -108,6 +103,7 @@ Successfully enrolled member user "user1"
User1 was successfully registered and enrolled and is ready to intreact with the fabric network
```

Run the command __node query.js__. The response should be _similar_ to:
```
Store path:/home/ibmadmin/fabric-samples/fabcar/hfc-key-store
Successfully loaded user1 from persistence
Expand Down Expand Up @@ -164,5 +160,5 @@ Select one option below:
If you plan to run marbles on the **same** machine as the docker containers then this step is already done for you.
Choose option 1, else choose option 2.

1. **Option 1:** :lollipop: - Fabric and Marbles on same machine - [next](../README.md#installchaincode)
1. **Option 1:** :lollipop: - Fabric and Marbles on same machine - [next](../README.md#3-install-and-instantiate-chaincode)
2. **Option 2:** - Fabric and Marbles on different machines - [edit config file](./config_file.md)
12 changes: 9 additions & 3 deletions utils/connection_profile_lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
// ============================================================================================================================
var fs = require('fs');
var path = require('path');
var os = require('os');

module.exports = function (config_filename, logger) {
var cp = {};
Expand Down Expand Up @@ -104,11 +105,16 @@ module.exports = function (config_filename, logger) {
if (obj.path.indexOf('/') === 0) {
path2cert = obj.path; //its an absolute path
}
if (path2cert.indexOf('$HOME') >= 0) {
path2cert = path2cert.replace('$HOME', os.homedir()).substr(1);
}
logger.debug('loading pem from a path: ' + path2cert);
return fs.readFileSync(path2cert, 'utf8') + '\r\n'; //read from file, LOOKING IN config FOLDER
} else {
return obj.pem; //can be null if network is not using TLS
} else if (obj.pem) { // looks like field is the pem we need
logger.debug('loading pem from JSON.');
return obj.pem;
}
return null;
return null; //can be null if network is not using TLS
};

// safely retrieve marbles config file fields
Expand Down
61 changes: 24 additions & 37 deletions utils/connection_profile_lib/parts/org.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Get org fields from connection profile data
// ============================================================================================================================
var fs = require('fs');
var os = require('os');
var path = require('path');

module.exports = function (cp, logger) {
Expand Down Expand Up @@ -86,67 +87,53 @@ module.exports = function (cp, logger) {
helper.getAdminPrivateKeyPEM = function (orgName) {
if (orgName && cp.creds.organizations && cp.creds.organizations[orgName]) {
if (!cp.creds.organizations[orgName].adminPrivateKey) {
if (!cp.creds.organizations[orgName]['x-certJson'] || !cp.creds.organizations[orgName]['x-certJson'].path) {
if (!cp.creds.organizations[orgName]['x-adminKeyStore'] || !cp.creds.organizations[orgName]['x-adminKeyStore'].path) {
throw new Error('Admin private key is not found in the creds json file: ' + orgName);
} else {
const obj = getCryptoFromCertJson(cp.creds.organizations[orgName]['x-certJson'].path);
return cp.loadPem(obj.adminPrivateKey);
const path2key = getCryptoFromCP(cp.creds.organizations[orgName]['x-adminKeyStore'].path);
if (path2key) {
return cp.loadPem({ path: path2key });
}
}
} else {
return cp.loadPem(cp.creds.organizations[orgName].adminPrivateKey);
}
}
else {
throw new Error('Cannot find org.', orgName);
}
throw new Error('Cannot find org.', orgName);
};

// get an admin's signed cert PEM
helper.getAdminSignedCertPEM = function (orgName) {
if (orgName && cp.creds.organizations && cp.creds.organizations[orgName]) {
if (!cp.creds.organizations[orgName].signedCert) {
if (!cp.creds.organizations[orgName]['x-certJson'] || !cp.creds.organizations[orgName]['x-certJson'].path) {
if (!cp.creds.organizations[orgName]['x-adminCert'] || !cp.creds.organizations[orgName]['x-adminCert'].path) {
throw new Error('Admin certificate is not found in the creds json file: ' + orgName);
} else {
const obj = getCryptoFromCertJson(cp.creds.organizations[orgName]['x-certJson'].path);
return cp.loadPem(obj.signedCert);
return cp.loadPem({ path: cp.creds.organizations[orgName]['x-adminCert'].path });
}
} else {
return cp.loadPem(cp.creds.organizations[orgName].signedCert);
}
}
else {
throw new Error('Cannot find org.', orgName);
}
return null;
throw new Error('Cannot find org.', orgName);
};

// return an object with the private key and the admin cert
function getCryptoFromCertJson(file_path) {
const ret = {
adminPrivateKey: {
path: null
},
signedCert: {
pem: null
}
};
try {
const json = fs.readFileSync(file_path); //open the crypto file, fabcar generated this
const obj = JSON.parse(json);
ret.adminPrivateKey.path = path.join(strip_2_folder(file_path), obj.enrollment.signingIdentity + '-priv'); //load it via path
ret.signedCert.pem = obj.enrollment.identity.certificate; //load it directly
} catch (e) {
logger.error(e);
throw new Error('Cannot parse crypto json', file_path);
// return path to private key from kvs
function getCryptoFromCP(kvsPath, cb) {
let kvs_path = kvsPath;
if (kvsPath.indexOf('$HOME') >= 0) {
kvs_path = kvsPath.replace('$HOME', os.homedir()).substr(1);
}
return ret;

// take the filename out of the pathname, leave the path to the folder
function strip_2_folder(pathname) {
const lastPos = pathname.lastIndexOf('/');
return pathname.substring(0, lastPos);
if (fs.existsSync(kvs_path)) { // check if folder exists
const entries = fs.readdirSync(kvs_path);
for (let i in entries) {
const entry_path = path.join(kvs_path, entries[i]);
if (fs.lstatSync(entry_path).isFile()) { // found a file, hope its the key/cert we need
return entry_path;
}
}
}
return null;
}

return helper;
Expand Down
3 changes: 3 additions & 0 deletions utils/connection_profile_lib/parts/other.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ module.exports = function (cp, logger) {
if (kvs_path.indexOf('/') === 0) {
ret = kvs_path; //its an absolute path
}
if (ret.indexOf('$HOME') >= 0) {
ret = ret.replace('$HOME', os.homedir()).substr(1);
}
return ret; //use the kvs provided in the json
} else {
return default_path; //make a new kvs folder in the home dir
Expand Down

0 comments on commit 983aefd

Please sign in to comment.