FiscoBcos-javasdk实现
项目结构
基于spring-boot的mvn项目
- conf 链证书、机构证书、机构私钥、账户
- contract 应用合约,sol文件
- application-dev.yml
channel-service:
group-id: 1 # sdk实际连接的群组
config-toml:
config-path: classpath:config.toml #区块链集群的配置文件
contract-address:
kVPerson: "0x3cc40ecd5000f58c3458fef29b91114bd5e18da3" #合约地址
- config.toml
[cryptoMaterial]
certPath = "conf"
caCert = "conf/ca.crt" #链证书
sslCert = "conf/sdk.crt" #机构证书
sslKey = "conf/sdk.key" #机构私钥
#enSslCert = "conf/gm/gmensdk.crt" #集群为国密版,则需要配置
#enSslKey = "conf/gm/gmensdk.key"
[network]
peers=["192.168.160.135:20200", "192.168.160.135:20201"] #节点ip:port
[account]
keyStoreDir = "account"
accountFilePath = "conf/0x9ff96dcf17f27ddd643c23bc1236733aa92a1f20.pem"
accountFileFormat = "pem"
accountAddress = "0x9ff96dcf17f27ddd643c23bc1236733aa92a1f20" #账户
- pom.xml
引用fisco-bcos-java-sdk的2.7.1版本
拷贝证书
集群的链证书、机构证书、机构私钥复制项目conf文件下
控制台下账户复制项目conf文件下
控制台部署合约
deploy KVPerson
transaction hash: 0x72908963644b7e897bf03d0a9ddb9f76428f5b1684aee89eb251d0adf15bdb75
contract address: 0x3cc40ecd5000f58c3458fef29b91114bd5e18da3
拷贝合约地址
把合约地址复制到项目的application-dev.yml配置文件里,通过合约地址来加载合约,获取合约对象。
生成java文件
- 合约转换成java文件
./sol2java.sh com.fish1208.contract ~/console-all/console-A/contracts/solidity/KVPerson.sol ~/console-all/console-A/contracts/console/
- 将转换后的java文件复制到项目com.fish1208.contract包里
代码开发
BcosSDKConfig.java
通过config-toml.toml配置文件获取BcosSDK对象
package com.fish1208.bcos.config;
import org.apache.commons.io.FileUtils;
import org.fisco.bcos.sdk.BcosSDK;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import java.io.File;
import java.io.InputStream;
@Configuration
@ConfigurationProperties(prefix = "config-toml")
public class BcosSDKConfig {
private Resource configPath;
@Bean
public BcosSDK getBcosSDK() throws Exception{
return BcosSDK.build(getFilePath(configPath));
}
/**
* 在jar包情况下无法读取配置文件config.toml,需要将配置文件config.toml先放到临时文件夹tmp下
* @param resource
* @return
* @throws Exception
*/
private String getFilePath(Resource resource) throws Exception{
File tempFile = File.createTempFile(resource.getFilename().split("\\.")[0], "." + resource.getFilename().split("\\.")[1]);
InputStream in = resource.getInputStream();
try{
FileUtils.copyInputStreamToFile(in, tempFile);
}finally {
in.close();
}
return tempFile.getPath();
}
public Resource getConfigPath() {
return configPath;
}
public void setConfigPath(Resource configPath) {
this.configPath = configPath;
}
}
ClientConfig.java
通过application-dev.yml配置文件的channel-service得到群组,获取Client连接
package com.fish1208.bcos.config;
import org.fisco.bcos.sdk.BcosSDK;
import org.fisco.bcos.sdk.client.Client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "channel-service")
public class ClientConfig {
private Integer groupId;
@Autowired
private BcosSDK sdk;
@Bean
public Client getClient() {
return sdk.getClient(groupId);
}
public Integer getGroupId() {
return groupId;
}
public void setGroupId(Integer groupId) {
this.groupId = groupId;
}
}
ContractConfig.java
通过application-dev.yml配置文件的contract-address得到合约地址,用来加载合约,获取合约对象
package com.fish1208.bcos.config;
import com.fish1208.bcos.ContractAddress;
import com.fish1208.contract.KVPerson;
import lombok.extern.slf4j.Slf4j;
import org.fisco.bcos.sdk.client.Client;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "contract-address")
public class ContractConfig {
private String kVPerson;
@Bean
public KVPerson loadImage(Client client){
return KVPerson.load(kVPerson, client, client.getCryptoSuite().getCryptoKeyPair());
}
@Bean
public ContractAddress setAddress(){
log.info("kVPerson={}", kVPerson);
ContractAddress contractAddress = new ContractAddress();
contractAddress.setKVPerson(kVPerson);
return contractAddress;
}
public String getkVPerson() {
return kVPerson;
}
public void setkVPerson(String kVPerson) {
this.kVPerson = kVPerson;
}
}
PersonController.java
调用合约的set、get方法,进行数据上链、链上数据查询。
package com.fish1208.controller;
import com.alibaba.fastjson.JSON;
import com.fish1208.common.response.Result;
import com.fish1208.contract.KVPerson;
import lombok.extern.slf4j.Slf4j;
import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple4;
import org.fisco.bcos.sdk.model.TransactionReceipt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.math.BigInteger;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/contract/person")
public class PersonController {
@Autowired
private KVPerson person;
/**
*
* @param id
* @return
* @throws Exception
*/
@RequestMapping(value = "/get", method = RequestMethod.GET)
public Result<?> get(@RequestParam String id) throws Exception {
if (person != null) {
log.info("KVPerson address is: {}", person.getContractAddress());
Tuple4<Boolean, String, BigInteger, String> tuple = person.get(id);
return Result.data(tuple);
}
return Result.fail("执行KVPerson合约失败");
}
@RequestMapping(value = "/set", method = RequestMethod.POST)
public Result<?> set(@RequestBody Map<String,Object> param) throws Exception {
if (person != null) {
log.info("KVPerson address is: {}", person.getContractAddress());
String id = (String)param.get("id");
String name = (String) param.get("name");
BigInteger age = BigInteger.valueOf((Integer) param.get("age"));
String sex = (String) param.get("sex");
TransactionReceipt receipt = person.set(id, name, age, sex);
log.info("KVPerson receipt = {}", JSON.toJSONString(receipt));
return Result.data(receipt);
}
return Result.fail("执行KVPerson合约失败");
}
}
项目启动
调用接口
执行KVPerson合约set方法
http://127.0.0.1:7022/contract/person/set
请求
POST /contract/person/set HTTP/1.1
Content-Type: application/json
{
"id":"1",
"name":"袁洪相",
"age":100,
"sex":"男"
}
执行KVPerson合约get方法
http://127.0.0.1:7022/contract/person/get?id=1
请求
GET /contract/person/get HTTP/1.1
id=1
Github地址
https://github.com/hongfish/fish1208-fiscobcos-javasdk