هذه الصفحة غير متوفرة حاليًا بلغتك المحلية. نحن نعمل جاهدين على إضافة المزيد من اللغات. شاكرين تفهمك ودعمك المستمر لنا.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
On this page

Show all

Sample Chaincode

Updated on 2022-09-08 GMT+08:00

The following is an example chaincode for reading and writing data. You can also refer to other chaincodes in the official examples provided by Fabric.

NOTE:

When creating a Java project, you can create a Maven or Gradle project to import the dependency package. A Gradle project is used in the following example.

/* Before importing the following code to the build.gradle file of the project, delete or comment out the original content in this file.*/
buildscript {
    repositories {
        mavenLocal()        
        maven{ url "https://mirrors.huaweicloud.com/repository/maven/" }
    }
    dependencies {
        classpath 'com.github.jengelman.gradle.plugins:shadow:2.0.4'    }
}

apply plugin: 'com.github.johnrengelman.shadow'
apply plugin: 'java'

sourceCompatibility = 1.8

//Code repository where the dependency package is searched and downloaded.
repositories {
    mavenLocal()
    maven{ url "https://mirrors.huaweicloud.com/repository/maven/" }
    maven{ url "https://jitpack.io" }/* If JSON Schema cannot be imported, try to add it to this repository.*/
}
 
//Import the dependency package required by the code.
dependencies {
    compile group: 'org.hyperledger.fabric-chaincode-java', name: 'fabric-chaincode-shim', version: '2.2.+'
     testCompile group: 'junit', name: 'junit', version: '4.12' //testCompile indicates that this package is used only for debugging.
    testCompile 'org.mockito:mockito-core:2.4.1'
}

shadowJar {
    baseName = 'chaincode'
    version = null
    classifier = null
    manifest {
        //The path must be the same as that of the class that extends ChaincodeBase.
        attributes 'Main-Class': 'org.hyperledger.fabric.example.SimpleChaincode'
     }
}
//The following is the content in the SimpleChaincode class.
package org.hyperledger.fabric.example;//The actual location of the chaincode file, which is usually automatically generated.

//You only need to configure the required packages in Maven or Gradle. The packages are imported automatically.
import java.util.List;

import com.google.protobuf.ByteString;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hyperledger.fabric.shim.ChaincodeBase;
import org.hyperledger.fabric.shim.ChaincodeStub;

import static java.nio.charset.StandardCharsets.UTF_8;

// SimpleChaincode example simple Chaincode implementation
public class SimpleChaincode extends ChaincodeBase {

    private static Log logger = LogFactory.getLog(SimpleChaincode.class);

    @Override
    public Response init(ChaincodeStub stub) {
        logger.info("Init");
        return newSuccessResponse();
    }

    @Override
    public Response invoke(ChaincodeStub stub) {
        try {
            logger.info("Invoke java simple chaincode");
            String func = stub.getFunction();
            List<String> params = stub.getParameters();
            if (func.equals("insert")) {
                return insert(stub, params);
            }
            if (func.equals("query")) {
                return query(stub, params);
            }
            return newErrorResponse("Invalid invoke function name. Expecting one of: [\"insert\", \"query\"]");
        } catch (Throwable e) {
            return newErrorResponse(e);
        }
    }

    // The Insert method implements the data storage function and stores the key-value on the chain
    private Response insert(ChaincodeStub stub, List<String> args) {
        if (args.size() != 2) {
            return newErrorResponse("Incorrect number of arguments. Expecting 2");
        }
        String key = args.get(0);
        String val = args.get(1);

        stub.putState(key, ByteString.copyFrom(val, UTF_8).toByteArray());
        return newSuccessResponse();
    }

    // The Query method implements the data query function by invoking the API to query the value of the key
    // API to query the value corresponding to a key
    private Response query(ChaincodeStub stub, List<String> args) {
        if (args.size() != 1) {
            return newErrorResponse("Incorrect number of arguments. Expecting name of the person to query");
        }
        String key = args.get(0);
        // Get the value of key
        String val = stub.getStringState(key);
        if (val == null) {
            String jsonResp = "{\"Error\":\"Null val for " + key + "\"}";
            return newErrorResponse(jsonResp);
        }
        logger.info(String.format("Query Response:\nkey: %s, val: %s\n", key, val));
        return newSuccessResponse(val, ByteString.copyFrom(val, UTF_8).toByteArray());
    }

    public static void main(String[] args) {
        new SimpleChaincode().start(args);
    }
}

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback