FISCO BCOS 的Java-Sdk使用入门
使用SpringBoot在FISCO BCOS部署合约、调用合约。项目结构如下:
准备solidity合约
编写好的合约在项目solidity目录下
代码如下:
pragma solidity ^0.5.1;
contract UserManage {
struct User {
uint256 id;
string name;
string sex;
}
mapping(uint256 => User) users;
uint256[] ids;
modifier notExist(){
bool exist = isExist(uint256(msg.sender));
require(!exist, "User already exist");
_;
}
/**
* 新增user
*/
function add(string memory name, string memory sex) public notExist returns(uint256, string memory, string memory) {
uint256 id = uint256(msg.sender);
User memory user = User(id, name, sex);
ids.push(id);
users[id] = user;
return (users[id].id, users[id].name, users[id].sex);
}
/**
* 更新User
*
*/
function update(string memory name, string memory sex) public returns(uint256, string memory, string memory) {
bool exist = isExist(uint256(msg.sender));
require(exist, "User not exist");
uint256 id = uint256(msg.sender);
User memory user = User(id, name, sex);
users[id] = user;
return (users[id].id, users[id].name, users[id].sex);
}
/**
* 删除User
*
*/
function del(uint256 id) public {
uint8 index = 0;
bool exist = false;
for (uint8 i = 0; i < ids.length; i++){
if (uint256(msg.sender) == ids[i]){
exist = true;
index = i;
break;
}
}
require(exist, "User not exist");
delete ids[index];
delete users[id];
}
/**
* 查询User
*
*/
function get(uint256 id) public view returns(uint256, string memory, string memory){
return (users[id].id, users[id].name, users[id].sex);
}
/**
* 用户是否存在
*
*/
function isExist(uint256 id) private view returns(bool){
bool exist = false;
for (uint8 i = 0; i < ids.length; i++){
if (uint256(id) == ids[i]){
exist = true;
break;
}
}
return exist;
}
function test() public pure returns(string memory){
return "hello world";
}
}
编译solidity合约,并生成调用合约的Java类,本项目中生成的合约调用类是solidity包下的UseManage类
编写配置文件
-
复制证书和密钥
在程序resource目录下新建conf文件夹,并将FISCO BCOS链中./fisco/nodes/127.0.0.1/sdk/路径下的证书和密钥文件复制到conf文件夹下
-
在application.yml中编写连接FISCO BCOS的配置:
fisco:
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:
- "106.12.*.*:20201"
- "106.12.*.*:20200"
amop:
# - publicKeys: [ "conf/amop/consumer_public_key_1.pem" ]
# topicName: "PrivateTopic1"
# - password: "123456"
# privateKey: "conf/amop/consumer_private_key.p12"
# topicName: "PrivateTo