ファブリック ネットワークが構築され、コントラクトが展開されたら、次のステップはコントラクトを操作することです。
前の章では、公式の fabcar コントラクト プロジェクトをデプロイしましたが、ここではこのコントラクトを例として使用して、簡単なインタラクティブな紹介を行います。
まず、fabcar のチェーンコード アドレス: https://github.com/hyperledger/fabric-samples/tree/main/chaincode/fabcar/javascript
導入方法は前の章で紹介したので、deployCC
そのまま使用してください。
ここでは、fabcar コントラクトがデプロイされていることを前提としています。
次に、コントラクトの操作を直接開始します。つまり、コントラクト内のメソッドを呼び出します。
新しいプロジェクト
まず、npm を使用してノード プロジェクトを作成し、npm init
3package.json
つのパッケージを追加します。
{
"name": "fabcar",
"version": "1.0.0",
"description": "FabCar application implemented in JavaScript",
"engineStrict": true,
"author": "Hyperledger",
"license": "Apache-2.0",
"dependencies": {
"app-root-path": "^3.0.0",
"fabric-ca-client": "^2.2.4",
"fabric-network": "^2.2.4"
}
}
fabric-network
これは契約のやり取りに使用され、contract
その中には契約を操作できる非常に重要なオブジェクトが含まれていることを説明します。fabric-ca-client
これは、ユーザーの登録など、ファブリック ネットワーク レベルでの一部の対話に使用されます。
管理者ユーザーの登録
const FabricCAServices = require('fabric-ca-client');
const {
Wallets } = require('fabric-network');
const ROOT = require('app-root-path');
const ccp = require(`${
ROOT}/organizations/peerOrganizations/org1.example.com/connection-org1.json`);
const walletPath = `${
ROOT}/wallet`;
async function main() {
try {
// Create a new CA client for interacting with the CA.
const caInfo = ccp.certificateAuthorities['ca.org1.example.com'];
const caTLSCACerts = caInfo.tlsCACerts.pem;
const ca = new FabricCAServices(
caInfo.url,
{
trustedRoots: caTLSCACerts, verify: false },
caInfo.caName
);
// Create a new file system based wallet for managing identities.
const wallet = await Wallets.newFileSystemWallet(walletPath);
// Enroll the admin user, and import the new identity into the wallet.
const enrollment = await ca.enroll({
enrollmentID: 'admin',
enrollmentSecret: 'adminpw',
});
const x509Identity = {
credentials: {
certificate: enrollment.certificate,
privateKey: enrollment.key.toBytes(),
},
mspId: 'Org1MSP',
type: 'X.509',
};
await wallet.put('admin', x509Identity);
console.log('Successfully enrolled admin user');
} catch (e) {
console.error(e);
}
}
main();
ここで、いくつかの外部ファイルを参照する必要があることに気付きました。まず、wallet
プロジェクト ディレクトリの下に、ユーザー ウォレット、つまり後続の対話中に権限の署名に使用される秘密キーを保存するディレクトリを作成します。もう 1 つは、接続ノードの構成ファイルを導入することです。このファイルは組織の下にあります。cryptogen
最初の章で生成された組織ディレクトリをすべてコピーする必要があります。すべてであることに注意してください。そうしないと、エラーが報告されます。いくつかの関連参考文献。
一般ユーザーとして登録する
上記で管理者ユーザーが登録されているので、次のように管理者ユーザーを使用して一般ユーザーを登録できます。
const {
Wallets } = require('fabric-network');
const FabricCAServices = require('fabric-ca-client');
const ROOT = require('app-root-path');
const ccp = require(`${
ROOT}/organizations/peerOrganizations/org1.example.com/connection-org1.json`);
const walletPath = `${
ROOT}/wallet`;
async function main() {
try {
// Create a new CA client for interacting with the CA.
const caURL = ccp.certificateAuthorities['ca.org1.example.com'].url;
const ca = new FabricCAServices(caURL);
const wallet = await Wallets.newFileSystemWallet(walletPath);
const adminIdentity = await wallet.get('admin');
const provider = wallet
.getProviderRegistry()
.getProvider(adminIdentity.type);
const adminUser = await provider.getUserContext(adminIdentity, 'admin');
// Register the user, enroll the user, and import the new identity into the wallet.
const secret = await ca.register(
{
affiliation: 'org1.department1',
enrollmentID: 'appUser',
role: 'client',
},
adminUser
);
const enrollment = await ca.enroll({
enrollmentID: 'appUser',
enrollmentSecret: secret,
});
const x509Identity = {
credentials: {
certificate: enrollment.certificate,
privateKey: enrollment.key.toBytes(),
},
mspId: 'Org1MSP',
type: 'X.509',
};
await wallet.put('appUser', x509Identity);
console.log('Successfully registeredd');
} catch (error) {
console.error(error);
}
}
main();
契約書の読み書き
const {
Gateway, Wallets } = require('fabric-network');
const ROOT = require('app-root-path');
const walletPath = `${
ROOT}/wallet`;
const ccp = require(`${
ROOT}/organizations/peerOrganizations/org1.example.com/connection-org1.json`);
let conf = null;
let contract = null;
async function query() {
const res = await contract.evaluateTransaction('queryCar', 'CAR1');
console.log(JSON.parse(res.toString()));
}
async function change(name) {
await contract.submitTransaction('changeCarOwner', 'CAR1', name);
}
async function main() {
try {
// load the network configuration
const wallet = await Wallets.newFileSystemWallet(walletPath);
conf = {
wallet,
identity: 'appUser',
discovery: {
enabled: true, asLocalhost: true },
};
const gateway = new Gateway();
await gateway.connect(ccp, conf);
const network = await gateway.getNetwork('mychannel');
contract = network.getContract('fabcar');
await query();
await change('devil');
await query();
await gateway.disconnect();
} catch (error) {
console.error(error);
}
}
main();
対応する出力結果: