Using NodeJS to develop Hyperledger Fabric Note 3 - contract interaction

After the Fabric network is built and the contract is deployed, the next step is to interact with the contract.

In the previous chapter, we deployed the official fabcar contract project. Here we will use this contract as an example to give a simple interactive introduction.

First, the chaincode address of fabcar: https://github.com/hyperledger/fabric-samples/tree/main/chaincode/fabcar/javascript

The deployment method was introduced in the previous chapter, deployCCjust use it.

Here we assume that the fabcar contract has been deployed.

Next, we directly start to operate the contract, that is, call the method in the contract.

New Project

First, we use npm to create a node project, npm initand package.jsonadd 3 packages:

{
    
    
  "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"
  }
}

Explain that fabric-networkit is used for contract interaction, and there are very important contractobjects in it that can operate the contract. fabric-ca-clientIt is used for some interactions at the fabric network level, such as registering users, etc.

Register Admin user

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();

Here we noticed that some external files need to be referenced. First, create a walletdirectory under the project directory to store the user wallet, that is, the private key, which is used for signing rights during subsequent interactions. The other is to introduce the configuration file of the connection node. This file is under the organization. We must cryptogencopy all the organization directory generated in the first chapter. Note that it is all, otherwise an error will be reported , and there may be some related references.

Register as a normal user

The admin user has been registered above, so you can use the admin user to register ordinary users, as follows:

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();

Contract reading and writing

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();

Corresponding output result:
insert image description here

Guess you like

Origin blog.csdn.net/u014466109/article/details/119802765