更新时间:2022-09-16 GMT+08:00
分享

链代码示例

如下是一个读写数据的链代码示例,您也可以参考Fabric官方示例中其他链代码。

新建Java项目时,您可以选择新建maven或者gradle项目,以导入依赖包。本示例以gradle项目为例。

/*  导入此段代码到项目的build.gradle前,请删除或注释build.gradle中原有内容  */
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

// 依赖包所用的代码仓库,将从所选地址搜寻并下载依赖包
repositories {
    mavenLocal()
    maven{ url "https://mirrors.huaweicloud.com/repository/maven/" }
    maven{ url "https://jitpack.io" }/* 若Json-Schema无法导入,可以尝试加入此库 */
}
 
// 引入代码所需的依赖包
dependencies {
    compile group: 'org.hyperledger.fabric-chaincode-java', name: 'fabric-chaincode-shim', version: '2.2.+'
    testCompile group: 'junit', name: 'junit', version: '4.12' // testCompile表明仅在调测时使用此包
    testCompile 'org.mockito:mockito-core:2.4.1'
}

shadowJar {
    baseName = 'chaincode'
    version = null
    classifier = null
    manifest {
        // 需要与继承ChaincodeBase类接口的类路径保持一致
        attributes 'Main-Class': 'org.hyperledger.fabric.example.SimpleChaincode'
     }
}
// 以下为SimpleChaincode类内中的内容
package org.hyperledger.fabric.example;//根据链代码文件实际位置编写,一般由系统自动生成

// 引入必要的包,系统自动操作,只要在maven或gradle中配置即可
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);
    }
}

相关文档