Uso de NodeJS para desarrollar Hyperledger Fabric Note 3: interacción del contrato

Una vez que se crea la red Fabric y se implementa el contrato, el siguiente paso es interactuar con el contrato.

En el capítulo anterior, implementamos el proyecto de contrato oficial de fabcar. Aquí usaremos este contrato como ejemplo para dar una introducción interactiva simple.

Primero, la dirección del código de cadena de fabcar: https://github.com/hyperledger/fabric-samples/tree/main/chaincode/fabcar/javascript

El método de implementación se presentó en el capítulo anterior, deployCCsimplemente utilícelo.

Aquí asumimos que se ha implementado el contrato fabcar.

A continuación, comenzamos directamente a operar el contrato, es decir, llamamos al método en el contrato.

Nuevo proyecto

Primero, usamos npm para crear un proyecto de nodo npm inity package.jsonagregamos 3 paquetes:

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

Explique que fabric-networkse utiliza para la interacción del contrato y que contiene contractobjetos muy importantes que pueden operar el contrato. fabric-ca-clientSe utiliza para algunas interacciones a nivel de red fabric, como el registro de usuarios, etc.

Registrar usuario administrador

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

Aquí notamos que es necesario hacer referencia a algunos archivos externos. Primero, cree un walletdirectorio debajo del directorio del proyecto para almacenar la billetera del usuario, es decir, la clave privada, que se usa para firmar los derechos durante las interacciones posteriores. La otra es introducir el archivo de configuración del nodo de conexión, este archivo está bajo la organización, debemos cryptogencopiar todo el directorio de la organización generado en el primer capítulo, tenga en cuenta que es todo, de lo contrario se informará un error y puede haber algunas referencias relacionadas.

Regístrate como usuario normal

El usuario administrador se ha registrado anteriormente, por lo que puede utilizar el usuario administrador para registrar usuarios normales, de la siguiente manera:

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

Lectura y redacción de contratos.

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

Resultado de salida correspondiente:
inserte la descripción de la imagen aquí

Supongo que te gusta

Origin blog.csdn.net/u014466109/article/details/119802765
Recomendado
Clasificación