本节介绍如何使用Java语言进行智能合约的开发。
链码结构
在Java语言的链码主要由以下方法组成:
/**
* Defines methods that all chaincodes must implement.
*/
publicinterfaceChaincode{
/**
*Called during an instantiate transaction after the container has been
*established, allowing the chaincode to initialize its internal data
*/
publicResponseinit(ChaincodeStubstub);
/**
*Called for every Invoke transaction. The chaincode may change its state
*variables.
*/
publicResponseinvoke(ChaincodeStubstub);
}
init: 链码在初始化和升级时调用此接口,初始化相关的数据。
invoke:主要用于实现链码的内部业务逻辑,您可以在该方法中实现相关的业务。
链码示例
Hyperledger Fabric 提供了很多官方链码样例,具体请参考fabric 官方示例。 我们以 Hyperledger Fabric 官方提供的 example02 样例为例,为大家介绍链码的开发规范。
简单示例
首先,我们看一个空链码结构的示例代码
importjava.util.List;
importcom.google.protobuf.ByteString;
importio.netty.handler.ssl.OpenSsl;
importorg.apache.commons.logging.Log;
importorg.apache.commons.logging.LogFactory;
importorg.hyperledger.fabric.shim.ChaincodeBase;
importorg.hyperledger.fabric.shim.ChaincodeStub;
importstaticjava.nio.charset.StandardCharsets.UTF_8;
/*
* 一个管理资产的简单链码
*/
publicclassSimpleAssetDemoextendsChaincodeBase{
/*
* 在链码实例化期时调用Init初始化数据
*/
@Override
publicResponseinit(ChaincodeStubstub){