4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Amazon Managed Blockchainで作成したブロックチェーンネットワークにHyperledger Fabric SDK for Node.jsでアクセスしてみる

Last updated at Posted at 2019-05-28

Amazon Managed Blockchainを利用したアプリケーションを作成するのにHyperledger Fabric SDK for Node.jsを利用したかったのでお試ししてみました。

Amazon Managed BlockchainやHyperLedger Fabricってなんぞ?という方はこちらをご参考ください。

Amazon Managed BlockchainがリリースされたのでHyperledger Fabricも合わせて情報をまとめてみた - Qiita
https://qiita.com/kai_kou/items/5a968f42c5f96296f6fe

前提

下記記事でブロックチェーンネットワークを構築している前提となります。
またSDKを利用したプログラムの実行はEC2インスタンス上で行います。

Amazon Managed BlockchainでHyperledger Fabricのブロックチェーンネットワークを構築してみた - Qiita
https://qiita.com/kai_kou/items/e02e34dd9abb26219a7e

利用手順

上記記事で利用しているサンプルにあるfabcar でお試しします。

GitHub - hyperledger/fabric-samples: Read-only mirror of
https://gerrit.hyperledger.org/r/#/admin/projects/fabric-samples

Node.jsのインストール

Amazon Linnux2でNode.jsが利用できるようにします。Hyperledger Fabric for Node.jsはNode.jsのバージョン8.x系での利用となります。

GitHub - hyperledger/fabric-sdk-node: Read-only mirror of
https://gerrit.hyperledger.org/r/#/admin/projects/fabric-sdk-node

  • node runtime LTS version 8.9.0 or higher, up to 9.0 ( Node v9.0+ is not supported )

こちらを参考にNode.js 8.x系をインストールします。

distributions/README.md at master · nodesource/distributions
https://github.com/nodesource/distributions/blob/master/README.md

# EC2インスタンスにログイン
> ssh -i mb-test-ec2-key.pem ec2-user@xxx.xxx.xxx.xxx

$ curl -sL https://rpm.nodesource.com/setup_8.x | sudo bash -
$ sudo yum install -y gcc-c++ make nodejs

$ node -v
v8.16.0
$ npm -v
6.4.1

サンプルアプリの利用準備

fabcar用のアプリが利用できるようにパッケージをインストールします。

$ cd ~/fabric-samples/fabcar/
$ npm install

node-pre-gyp WARN Using request for node-pre-gyp https download
[grpc] Success: "/home/ec2-user/fabric-samples/fabcar/node_modules/grpc/src/node/extension_binary/node-v57-linux-x64-glibc/grpc_node.node" is installed via remote
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN fabcar@1.0.0 No repository field.

added 380 packages from 330 contributors and audited 939 packages in 40.137s
found 9 vulnerabilities (1 low, 1 moderate, 7 high)
  run `npm audit fix` to fix them, or `npm audit` for details

fabcarで利用するチェーンコードをデプロイする

fabcarで利用するチェーンコードをデプロイして初期設定まで行います。
今回チェーンコードはGoのを利用していますがNode.jsのでもOKです。

# Dockerコンテナの起動
$ docker-compose -f ~/docker-compose-cli.yaml up -d

# Dockerサービスが起動していなかったら
$ sudo service docker start

# チェーンコードのインストール
$ docker exec \
  -e "CORE_PEER_TLS_ENABLED=true" \
  -e "CORE_PEER_TLS_ROOTCERT_FILE=/opt/home/managedblockchain-tls-chain.pem" \
  -e "CORE_PEER_LOCALMSPID=$MSP" \
  -e "CORE_PEER_MSPCONFIGPATH=$MSP_PATH" \
  -e "CORE_PEER_ADDRESS=$PEER" \
  cli peer chaincode install \
    -n fabcar \
    -v v1.0 \
    -p github.com/fabcar/go

2019-05-27 02:03:14.242 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 001 Using default escc
2019-05-27 02:03:14.242 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 002 Using default vscc
2019-05-27 02:03:14.419 UTC [chaincodeCmd] install -> INFO 003 Installed remotely response:<status:200 payload:"OK" >


# チェーンコードのデプロイ
$ docker exec \
  -e "CORE_PEER_TLS_ENABLED=true" \
  -e "CORE_PEER_TLS_ROOTCERT_FILE=/opt/home/managedblockchain-tls-chain.pem" \
  -e "CORE_PEER_LOCALMSPID=$MSP" \
  -e "CORE_PEER_MSPCONFIGPATH=$MSP_PATH" \
  -e "CORE_PEER_ADDRESS=$PEER" \
  cli peer chaincode instantiate \
    -o $ORDERER -C mychannel \
    -n fabcar \
    -v v1.0 \
    -c '{"Args":[""]}' \
    --cafile /opt/home/managedblockchain-tls-chain.pem --tls

2019-05-27 02:07:10.893 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 001 Using default escc
2019-05-27 02:07:10.893 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 002 Using default vscc


# invokeで初期化
$ docker exec \
  -e "CORE_PEER_TLS_ENABLED=true" \
  -e "CORE_PEER_TLS_ROOTCERT_FILE=/opt/home/managedblockchain-tls-chain.pem" \
  -e "CORE_PEER_LOCALMSPID=$MSP" \
  -e "CORE_PEER_MSPCONFIGPATH=$MSP_PATH" \
  -e "CORE_PEER_ADDRESS=$PEER" \
  cli peer chaincode invoke \
    -o $ORDERER -C mychannel \
    -n fabcar \
    -c '{"function":"initLedger","Args":[""]}' \
    --cafile /opt/home/managedblockchain-tls-chain.pem --tls

2019-05-27 02:38:27.195 UTC [chaincodeCmd] chaincodeInvokeOrQuery -> INFO 001 Chaincode invoke successful. result: status:200

fabcarの実装を手直し

実行するjsファイルをAmazon Managed Blockchainで作成したブロックチェーンネットワークにアクセスできるように手直しします。

$ ls
enrollAdmin.js  invoke.js  node_modules  package-lock.json  package.json  query.js  registerUser.js  startFabric.sh

実装のポイント

Amazon Managed Blockchainでブロックチェーンネットワークを構築するとCA、Orderer、PeerノードへはTLSを用いてアクセスするように実装を変更する必要があります。

下記記事が参考になりました。

Fabric SDK を使用したアプリケーションの開発
https://cloud.ibm.com/docs/services/blockchain?topic=blockchain-dev-app&locale=ja

エンドポイント接続時にtrustedRoots で証明書情報を指定する

CLIでも利用したmanagedblockchain-tls-chain.pem ファイルの内容をfs.readFileSync で読み込み文字列として指定します。
合わせてverifytrue とします。

MSPIDにはMemberIDを指定する

Fabric_CA_ClientcreateUser メソッドで指定するMSPID にはMemberIDを指定します。

Peer、Ordererへの接続はgrpcs:// でする

CA接続時と同じくPeer、Ordererへの接続にも証明書情報を指定します。

invoke.js_一部抜粋
var channel = fabric_client.newChannel('mychannel');
var peer = fabric_client.newPeer('grpcs://nd-xxxxxxxxxxxxxxxxxxxxxxxxxx.m-xxxxxxxxxxxxxxxxxxxxxxxxxx.n-xxxxxxxxxxxxxxxxxxxxxxxxxx.managedblockchain.us-east-1.amazonaws.com:30003',
	{ pem: fs.readFileSync('/home/ec2-user/managedblockchain-tls-chain.pem').toString(), 'ssl-target-name-override': null});
channel.addPeer(peer);
var order = fabric_client.newOrderer('grpcs://orderer.n-xxxxxxxxxxxxxxxxxxxxxxxxxx.managedblockchain.us-east-1.amazonaws.com:30001',
	{ pem: fs.readFileSync('/home/ec2-user/managedblockchain-tls-chain.pem').toString(), 'ssl-target-name-override': null});
channel.addOrderer(order);

以下、上記を反映したソースとなります。

enrollAdmin.js
'use strict';
/*
* Copyright IBM Corp All Rights Reserved
*
* SPDX-License-Identifier: Apache-2.0
*/
/*
 * Enroll the AdminUser user
 */

var Fabric_Client = require('fabric-client');
var Fabric_CA_Client = require('fabric-ca-client');

var path = require('path');
var util = require('util');
var os = require('os');
var fs = require('fs');

//
var fabric_client = new Fabric_Client();
var fabric_ca_client = null;
var admin_user = null;
var member_user = null;
var store_path = path.join(__dirname, 'hfc-key-store');
console.log(' Store path:'+store_path);

// create the key value store as defined in the fabric-client/config/default.json 'key-value-store' setting
Fabric_Client.newDefaultKeyValueStore({ path: store_path
}).then((state_store) => {
    // assign the store to the fabric client
    fabric_client.setStateStore(state_store);
    var crypto_suite = Fabric_Client.newCryptoSuite();
    // use the same location for the state store (where the users' certificate are kept)
    // and the crypto store (where the users' keys are kept)
    var crypto_store = Fabric_Client.newCryptoKeyStore({path: store_path});
    crypto_suite.setCryptoKeyStore(crypto_store);
    fabric_client.setCryptoSuite(crypto_suite);
    var	tlsOptions = {
    	trustedRoots: [fs.readFileSync('/home/ec2-user/managedblockchain-tls-chain.pem')],
    	verify: true
    };
    // be sure to change the http to https when the CA is running TLS enabled
    fabric_ca_client = new Fabric_CA_Client(
        'https://ca.m-xxxxxxxxxxxxxxxxxxxxxxxxxx.n-xxxxxxxxxxxxxxxxxxxxxxxxxx.managedblockchain.us-east-1.amazonaws.com:30002',
        tlsOptions, 'm-xxxxxxxxxxxxxxxxxxxxxxxxxx', crypto_suite);

    // first check to see if the AdminUser is already enrolled
    return fabric_client.getUserContext('AdminUser', true);
}).then((user_from_store) => {
    if (user_from_store && user_from_store.isEnrolled()) {
        console.log('Successfully loaded AdminUser from persistence');
        admin_user = user_from_store;
        return null;
    } else {
        // need to enroll it with CA server
        return fabric_ca_client.enroll({
          enrollmentID: 'AdminUser',
          enrollmentSecret: 'Password123'
        }).then((enrollment) => {
          console.log('Successfully enrolled AdminUser user "AdminUser"');
          return fabric_client.createUser(
              {username: 'AdminUser',
                  mspid: 'm-xxxxxxxxxxxxxxxxxxxxxxxxxx',
                  cryptoContent: { privateKeyPEM: enrollment.key.toBytes(),
                                   signedCertPEM: enrollment.certificate }
              });
        }).then((user) => {
          admin_user = user;
          return fabric_client.setUserContext(admin_user);
        }).catch((err) => {
          console.error('Failed to enroll and persist AdminUser. Error: ' + err.stack ? err.stack : err);
          throw new Error('Failed to enroll AdminUser');
        });
    }
}).then(() => {
    console.log('Assigned the AdminUser user to the fabric client ::' + admin_user.toString());
}).catch((err) => {
    console.error('Failed to enroll AdminUser: ' + err);
});
registerUser.js
'use strict';
/*
* Copyright IBM Corp All Rights Reserved
*
* SPDX-License-Identifier: Apache-2.0
*/
/*
 * Register and Enroll a user
 */

var Fabric_Client = require('fabric-client');
var Fabric_CA_Client = require('fabric-ca-client');

var path = require('path');
var util = require('util');
var os = require('os');
var fs = require('fs');

//
var fabric_client = new Fabric_Client();
var fabric_ca_client = null;
var admin_user = null;
var member_user = null;
var store_path = path.join(__dirname, 'hfc-key-store');
console.log(' Store path:'+store_path);

// create the key value store as defined in the fabric-client/config/default.json 'key-value-store' setting
Fabric_Client.newDefaultKeyValueStore({ path: store_path
}).then((state_store) => {
    // assign the store to the fabric client
    fabric_client.setStateStore(state_store);
    var crypto_suite = Fabric_Client.newCryptoSuite();
    // use the same location for the state store (where the users' certificate are kept)
    // and the crypto store (where the users' keys are kept)
    var crypto_store = Fabric_Client.newCryptoKeyStore({path: store_path});
    crypto_suite.setCryptoKeyStore(crypto_store);
    fabric_client.setCryptoSuite(crypto_suite);
    var	tlsOptions = {
    	trustedRoots: [fs.readFileSync('/home/ec2-user/managedblockchain-tls-chain.pem')],
    	verify: true
    };
    // be sure to change the http to https when the CA is running TLS enabled
    fabric_ca_client = new Fabric_CA_Client(
        'https://ca.m-xxxxxxxxxxxxxxxxxxxxxxxxxx.n-xxxxxxxxxxxxxxxxxxxxxxxxxx.managedblockchain.us-east-1.amazonaws.com:30002',
        tlsOptions, 'm-xxxxxxxxxxxxxxxxxxxxxxxxxx', crypto_suite);

    // first check to see if the AdminUser is already enrolled
    return fabric_client.getUserContext('AdminUser', true);
}).then((user_from_store) => {
    if (user_from_store && user_from_store.isEnrolled()) {
        console.log('Successfully loaded AdminUser from persistence');
        admin_user = user_from_store;
    } else {
        throw new Error('Failed to get AdminUser.... run enrolladmin.js');
    }

    // at this point we should have the AdminUser user
    // first need to register the user with the CA server
    return fabric_ca_client.register({
        enrollmentID: 'user1',
        affiliation: 'org1', role: 'client'}, admin_user);
}).then((secret) => {
    // next we need to enroll the user with CA server
    console.log('Successfully registered user1 - secret:'+ secret);

    return fabric_ca_client.enroll({enrollmentID: 'user1', enrollmentSecret: secret});
}).then((enrollment) => {
  console.log('Successfully enrolled member user "user1" ');
  return fabric_client.createUser(
     {username: 'user1',
     mspid: 'm-xxxxxxxxxxxxxxxxxxxxxxxxxx',
     cryptoContent: { privateKeyPEM: enrollment.key.toBytes(), signedCertPEM: enrollment.certificate }
     });
}).then((user) => {
     member_user = user;

     return fabric_client.setUserContext(member_user);
}).then(()=>{
     console.log('User1 was successfully registered and enrolled and is ready to interact with the fabric network');

}).catch((err) => {
    console.error('Failed to register: ' + err);
	if(err.toString().indexOf('Authorization') > -1) {
		console.error('Authorization failures may be caused by having AdminUser credentials from a previous CA instance.\n' +
		'Try again after deleting the contents of the store directory '+store_path);
	}
});
query.js
'use strict';
/*
* Copyright IBM Corp All Rights Reserved
*
* SPDX-License-Identifier: Apache-2.0
*/
/*
 * Chaincode query
 */

var Fabric_Client = require('fabric-client');
var path = require('path');
var util = require('util');
var os = require('os');
var fs = require('fs');

//
var fabric_client = new Fabric_Client();

// setup the fabric network
var channel = fabric_client.newChannel('mychannel');
var peer = fabric_client.newPeer('grpcs://nd-xxxxxxxxxxxxxxxxxxxxxxxxxx.m-xxxxxxxxxxxxxxxxxxxxxxxxxx.n-xxxxxxxxxxxxxxxxxxxxxxxxxx.managedblockchain.us-east-1.amazonaws.com:30003',
	{ pem: fs.readFileSync('/home/ec2-user/managedblockchain-tls-chain.pem').toString(), 'ssl-target-name-override': null});
channel.addPeer(peer);

//
var member_user = null;
var store_path = path.join(__dirname, 'hfc-key-store');
console.log('Store path:'+store_path);
var tx_id = null;

// create the key value store as defined in the fabric-client/config/default.json 'key-value-store' setting
Fabric_Client.newDefaultKeyValueStore({ path: store_path
}).then((state_store) => {
	// assign the store to the fabric client
	fabric_client.setStateStore(state_store);
	var crypto_suite = Fabric_Client.newCryptoSuite();
	// use the same location for the state store (where the users' certificate are kept)
	// and the crypto store (where the users' keys are kept)
	var crypto_store = Fabric_Client.newCryptoKeyStore({path: store_path});
	crypto_suite.setCryptoKeyStore(crypto_store);
	fabric_client.setCryptoSuite(crypto_suite);

	// get the enrolled user from persistence, this user will sign all requests
	return fabric_client.getUserContext('user1', true);
}).then((user_from_store) => {
	if (user_from_store && user_from_store.isEnrolled()) {
		console.log('Successfully loaded user1 from persistence');
		member_user = user_from_store;
	} else {
		throw new Error('Failed to get user1.... run registerUser.js');
	}

	// queryCar chaincode function - requires 1 argument, ex: args: ['CAR4'],
	// queryAllCars chaincode function - requires no arguments , ex: args: [''],
	const request = {
		//targets : --- letting this default to the peers assigned to the channel
		chaincodeId: 'fabcar',
		fcn: 'queryAllCars',
		args: ['']
	};

	// send the query proposal to the peer
	return channel.queryByChaincode(request);
}).then((query_responses) => {
	console.log("Query has completed, checking results");
	// query_responses could have more than one  results if there multiple peers were used as targets
	if (query_responses && query_responses.length == 1) {
		if (query_responses[0] instanceof Error) {
			console.error("error from query = ", query_responses[0]);
		} else {
			console.log("Response is ", query_responses[0].toString());
		}
	} else {
		console.log("No payloads were returned from query");
	}
}).catch((err) => {
	console.error('Failed to query successfully :: ' + err);
});
invoke.js
'use strict';
/*
* Copyright IBM Corp All Rights Reserved
*
* SPDX-License-Identifier: Apache-2.0
*/
/*
 * Chaincode Invoke
 */

var Fabric_Client = require('fabric-client');
var path = require('path');
var util = require('util');
var os = require('os');
var fs = require('fs');

//
var fabric_client = new Fabric_Client();

// setup the fabric network
var channel = fabric_client.newChannel('mychannel');
var peer = fabric_client.newPeer('grpcs://nd-xxxxxxxxxxxxxxxxxxxxxxxxxx.m-xxxxxxxxxxxxxxxxxxxxxxxxxx.n-xxxxxxxxxxxxxxxxxxxxxxxxxx.managedblockchain.us-east-1.amazonaws.com:30003',
	{ pem: fs.readFileSync('/home/ec2-user/managedblockchain-tls-chain.pem').toString(), 'ssl-target-name-override': null});
channel.addPeer(peer);
var order = fabric_client.newOrderer('grpcs://orderer.n-xxxxxxxxxxxxxxxxxxxxxxxxxx.managedblockchain.us-east-1.amazonaws.com:30001',
	{ pem: fs.readFileSync('/home/ec2-user/managedblockchain-tls-chain.pem').toString(), 'ssl-target-name-override': null});
channel.addOrderer(order);

//
var member_user = null;
var store_path = path.join(__dirname, 'hfc-key-store');
console.log('Store path:'+store_path);
var tx_id = null;

// create the key value store as defined in the fabric-client/config/default.json 'key-value-store' setting
Fabric_Client.newDefaultKeyValueStore({ path: store_path
}).then((state_store) => {
	// assign the store to the fabric client
	fabric_client.setStateStore(state_store);
	var crypto_suite = Fabric_Client.newCryptoSuite();
	// use the same location for the state store (where the users' certificate are kept)
	// and the crypto store (where the users' keys are kept)
	var crypto_store = Fabric_Client.newCryptoKeyStore({path: store_path});
	crypto_suite.setCryptoKeyStore(crypto_store);
	fabric_client.setCryptoSuite(crypto_suite);

	// get the enrolled user from persistence, this user will sign all requests
	return fabric_client.getUserContext('user1', true);
}).then((user_from_store) => {
	if (user_from_store && user_from_store.isEnrolled()) {
		console.log('Successfully loaded user1 from persistence');
		member_user = user_from_store;
	} else {
		throw new Error('Failed to get user1.... run registerUser.js');
	}

	// get a transaction id object based on the current user assigned to fabric client
	tx_id = fabric_client.newTransactionID();
	console.log("Assigning transaction_id: ", tx_id._transaction_id);

	// createCar chaincode function - requires 5 args, ex: args: ['CAR12', 'Honda', 'Accord', 'Black', 'Tom'],
	// changeCarOwner chaincode function - requires 2 args , ex: args: ['CAR10', 'Dave'],
	// must send the proposal to endorsing peers
	var request = {
		//targets: let default to the peer assigned to the client
		chaincodeId: 'fabcar',
		fcn: 'createCar',
		args: ['CAR10', 'Chevy', 'Volt', 'Red', 'Nick'],
		chainId: 'mychannel',
		txId: tx_id
	};

	// send the transaction proposal to the peers
	return channel.sendTransactionProposal(request);
}).then((results) => {
	var proposalResponses = results[0];
	var proposal = results[1];
	let isProposalGood = false;
	if (proposalResponses && proposalResponses[0].response &&
		proposalResponses[0].response.status === 200) {
			isProposalGood = true;
			console.log('Transaction proposal was good');
		} else {
			console.error('Transaction proposal was bad');
		}
	if (isProposalGood) {
		console.log(util.format(
			'Successfully sent Proposal and received ProposalResponse: Status - %s, message - "%s"',
			proposalResponses[0].response.status, proposalResponses[0].response.message));

		// build up the request for the orderer to have the transaction committed
		var request = {
			proposalResponses: proposalResponses,
			proposal: proposal
		};

		// set the transaction listener and set a timeout of 30 sec
		// if the transaction did not get committed within the timeout period,
		// report a TIMEOUT status
		var transaction_id_string = tx_id.getTransactionID(); //Get the transaction ID string to be used by the event processing
		var promises = [];

		var sendPromise = channel.sendTransaction(request);
		promises.push(sendPromise); //we want the send transaction first, so that we know where to check status

		// get an eventhub once the fabric client has a user assigned. The user
		// is required bacause the event registration must be signed
		let event_hub = channel.newChannelEventHub(peer);

		// using resolve the promise so that result status may be processed
		// under the then clause rather than having the catch clause process
		// the status
		let txPromise = new Promise((resolve, reject) => {
			let handle = setTimeout(() => {
				event_hub.unregisterTxEvent(transaction_id_string);
				event_hub.disconnect();
				resolve({event_status : 'TIMEOUT'}); //we could use reject(new Error('Trnasaction did not complete within 30 seconds'));
			}, 3000);
			event_hub.registerTxEvent(transaction_id_string, (tx, code) => {
				// this is the callback for transaction event status
				// first some clean up of event listener
				clearTimeout(handle);

				// now let the application know what happened
				var return_status = {event_status : code, tx_id : transaction_id_string};
				if (code !== 'VALID') {
					console.error('The transaction was invalid, code = ' + code);
					resolve(return_status); // we could use reject(new Error('Problem with the tranaction, event status ::'+code));
				} else {
					console.log('The transaction has been committed on peer ' + event_hub.getPeerAddr());
					resolve(return_status);
				}
			}, (err) => {
				//this is the callback if something goes wrong with the event registration or processing
				reject(new Error('There was a problem with the eventhub ::'+err));
			},
				{disconnect: true} //disconnect when complete
			);
			event_hub.connect();

		});
		promises.push(txPromise);

		return Promise.all(promises);
	} else {
		console.error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...');
		throw new Error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...');
	}
}).then((results) => {
	console.log('Send transaction promise and event listener promise have completed');
	// check the results in the order the promises were added to the promise all list
	if (results && results[0] && results[0].status === 'SUCCESS') {
		console.log('Successfully sent transaction to the orderer.');
	} else {
		console.error('Failed to order the transaction. Error code: ' + results[0].status);
	}

	if(results && results[1] && results[1].event_status === 'VALID') {
		console.log('Successfully committed the change to the ledger by the peer');
	} else {
		console.log('Transaction failed to be committed to the ledger due to ::'+results[1].event_status);
	}
}).catch((err) => {
	console.error('Failed to invoke successfully :: ' + err);
});

実行する

実装の手直しが終わったら実行してみます。

# エンロール
$ node enrollAdmin.js

 Store path:/home/ec2-user/fabric-samples/fabcar/hfc-key-store
Successfully enrolled AdminUser user "AdminUser"
Assigned the AdminUser user to the fabric client ::{"name":"AdminUser","mspid":"m-RV5JEFL66JBNDKPM6CQOBBQHEQ","roles":null,"affiliation":"","enrollmentSecret":"","enrollment":{"signingIdentity":"xxxxxxxxxxx","identity":{"certificate":"-----BEGIN CERTIFICATE-----xxxxxxxxx-----END CERTIFICATE-----\n"}}}


# ユーザー登録
$ node registerUser.js

 Store path:/home/ec2-user/fabric-samples/fabcar/hfc-key-store
Successfully loaded AdminUser from persistence
Successfully registered user1 - secret:xxxxxxxxxx
Successfully enrolled member user "user1"
User1 was successfully registered and enrolled and is ready to interact with the fabric network


# ステートDBの参照
$ node query.js

Store path:/home/ec2-user/fabric-samples/fabcar/hfc-key-store
Successfully loaded user1 from persistence
Query has completed, checking results
Response is  [{"Key":"CAR0", "Record":{"make":"Toyota","model":"Prius","colour":"blue","owner":"Tomoko"}},{"Key":"CAR1", "Record":{"make":"Ford","model":"Mustang","colour":"red","owner":"Brad"}},{"Key":"CAR2", "Record":{"make":"Hyundai","model":"Tucson","colour":"green","owner":"Jin Soo"}},{"Key":"CAR3", "Record":{"make":"Volkswagen","model":"Passat","colour":"yellow","owner":"Max"}},{"Key":"CAR4", "Record":{"make":"Tesla","model":"S","colour":"black","owner":"Adriana"}},{"Key":"CAR5", "Record":{"make":"Peugeot","model":"205","colour":"purple","owner":"Michel"}},{"Key":"CAR6", "Record":{"make":"Chery","model":"S22L","colour":"white","owner":"Aarav"}},{"Key":"CAR7", "Record":{"make":"Fiat","model":"Punto","colour":"violet","owner":"Pari"}},{"Key":"CAR8", "Record":{"make":"Tata","model":"Nano","colour":"indigo","owner":"Valeria"}},{"Key":"CAR9", "Record":{"make":"Holden","model":"Barina","colour":"brown","owner":"Shotaro"}}]


# ステートDBの更新
$ node invoke.js

Store path:/home/ec2-user/fabric-samples/fabcar/hfc-key-store
Successfully loaded user1 from persistence
Assigning transaction_id:  3dfaa8cdadef54f61bc4d3664feff54c2f6e06582fa313c900514543dfbab949
Transaction proposal was good
Successfully sent Proposal and received ProposalResponse: Status - 200, message - ""


# ステートDBの参照
$ node query.js

Store path:/home/ec2-user/fabric-samples/fabcar/hfc-key-store
Successfully loaded user1 from persistence
Query has completed, checking results
Response is  [{"Key":"CAR0", "Record":{"make":"Toyota","model":"Prius","colour":"blue","owner":"Tomoko"}},{"Key":"CAR1", "Record":{"make":"Ford","model":"Mustang","colour":"red","owner":"Brad"}},{"Key":"CAR10", "Record":{"make":"Chevy","model":"Volt","colour":"Red","owner":"Nick"}},{"Key":"CAR2", "Record":{"make":"Hyundai","model":"Tucson","colour":"green","owner":"Jin Soo"}},{"Key":"CAR3", "Record":{"make":"Volkswagen","model":"Passat","colour":"yellow","owner":"Max"}},{"Key":"CAR4", "Record":{"make":"Tesla","model":"S","colour":"black","owner":"Adriana"}},{"Key":"CAR5", "Record":{"make":"Peugeot","model":"205","colour":"purple","owner":"Michel"}},{"Key":"CAR6", "Record":{"make":"Chery","model":"S22L","colour":"white","owner":"Aarav"}},{"Key":"CAR7", "Record":{"make":"Fiat","model":"Punto","colour":"violet","owner":"Pari"}},{"Key":"CAR8", "Record":{"make":"Tata","model":"Nano","colour":"indigo","owner":"Valeria"}},{"Key":"CAR9", "Record":{"make":"Holden","model":"Barina","colour":"brown","owner":"Shotaro"}}]

無事にAmazon Managed Blockchainで構築したブロックチェーンネットワークにHyperledger Fabric for Node.jsを利用してアクセスすることができました。

キーストアにある証明書ファイルがないとアクセスできなくなってしまうので、ファイルをどこに永続化させておくかなどの課題はありますが、うまく活用すればいい感じにアプリが作成できそうです。

参考

Amazon Managed BlockchainでHyperledger Fabricのブロックチェーンネットワークを構築してみた - Qiita
https://qiita.com/kai_kou/items/e02e34dd9abb26219a7e

GitHub - hyperledger/fabric-samples: Read-only mirror of
https://gerrit.hyperledger.org/r/#/admin/projects/fabric-samples

GitHub - hyperledger/fabric-sdk-node: Read-only mirror of
https://gerrit.hyperledger.org/r/#/admin/projects/fabric-sdk-node

distributions/README.md at master · nodesource/distributions
https://github.com/nodesource/distributions/blob/master/README.md

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?