当前位置: 首页 > news >正文

Fisco-Bcos-java-SDK 利用java与fisco-Bcos区块链上的智能合约交互(以HelloWorld为例)

Fisco-Bcos-java-SDK 利用java与fisco-Bcos区块链上的智能合约交互(以HelloWorld为例)

一、部署智能合约

1、编写智能合约

此处用最简单的HelloWorld合约作为例子 包含两个方法和一个构造函数

  • 构造函数:当合约部署的时候 执行构造函数 将name赋值为Hello, World!
  • get()方法:获取当前name的值
  • set()方法:设置当前name的值 参数类型为string
pragma solidity >=0.4.25 <0.6.11;contract HelloWorld {string name;constructor() public{name = "Hello, World!";}function get() public view returns (string memory){return name;}function set(string memory n) public {name = n;}
}
2、通过WeBASE-Front平台将合约进行部署

将写好的合约复制到WeBASE-Front节点控制台中

在这里插入图片描述

  • 将合约进行编译后 创建测试用户进行部署 可以生成出当前合约的合约地址 这个很重要

  • 可以在这里进行图形化的合约调用进行测试

    调用get方法 可以看到我们部署合约后执行的构造函数所赋的值

在这里插入图片描述

在这里插入图片描述

同样调用set方法进行赋值,再调用get方法 ,可以看到我们所赋的值

在这里插入图片描述
返回交易回执

{
transactionHash: "0x488efbe3507e36c703575ebf678d05664e7ad2d0529e463f1ba2ec7606cb5828"
transactionIndex: "0x0"
root: "0xd318298686d387c9f6e3122e836b3c4ab2c0b093fc701c083a263e60d696b821"
blockNumber: "33"
blockHash: "0xbcc1f9f372849b0f7a78fed8c612032605f0a8696d7aea654fa330d909c290f8"
from: "0x96bf2ac80e9428068db9a544ff974bc32a1a2e4f"
to: "0x8002b168b1f81d6c6d1148f579370648cd28dde8"
gasUsed: "29813"
remainGas: "0x0"
contractAddress: "0x0000000000000000000000000000000000000000"
logs: []
logsBloom: "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
status: 0x0
statusMsg: "None"
input: 
function set( string n)
data: 
n
stringhello,Fisco-Bcos!
output: "0x"
txProof: null
receiptProof: null
message: "Success"
statusOK: true
}

可以看到 交易成功 并且 值赋值为hello,Fisco-Bcos!

再次调用get方法获取当前合约name的值

在这里插入图片描述

发现name的值已经发生了变化

那我如何利用java语言来进行这样的操作呢?接着往下看

二、导出HelloWorld合约的java文件和SDK证书文件

Fisco-Bcos提供了合约转义JAVA的功能 我们可以直接通过下载

**同样提供了SDK证书文件的下载 **

在这里插入图片描述
在这里插入图片描述
这里可以随便填写 我们到idea用的时候 进行修改就行
下载完成后是一个java文件和一个zip文件
在这里插入图片描述
包含生成的转义后的java文件和SDK证书

三、Springboot集成HelloWorld.sol–java文件

1、添加Fisco-Bcos依赖

在这里插入图片描述

<dependency><groupId>org.fisco-bcos.java-sdk</groupId><artifactId>fisco-bcos-java-sdk</artifactId><version>2.9.1</version></dependency>

在这里插入图片描述

这里直接用2.9.1版本的就行 反正博主用了很好用[doge]

2、对Fisco-Bcos-java-sdk进行配置;将生成的文件放入项目中
1.导入文件

在这里插入图片描述

resources目录下创建conf目录 将我们前面下载好的那个压缩包中的三个证书文件放到这个目录下

再将生成的HelloWorld.java放入自己的包下

这里我的包名是com.webase 再将java文件中的包名进行修改就行 修改成自己的包名

在这里插入图片描述

2.配置证书

同样在resources目录下创建config-example.toml文件

修改的内容为

在这里插入图片描述

文件内容如下:

[cryptoMaterial]certPath = "conf"                           # The certification path# The following configurations take the certPath by default if commented
# caCert = "conf/ca.crt"                    # CA cert file path
# If connect to the GM node, default CA cert path is ${certPath}/gm/gmca.crt# sslCert = "conf/sdk.crt"                  # SSL cert file path
# If connect to the GM node, the default SDK cert path is ${certPath}/gm/gmsdk.crt# sslKey = "conf/sdk.key"                   # SSL key file path
# If connect to the GM node, the default SDK privateKey path is ${certPath}/gm/gmsdk.key# enSslCert = "conf/gm/gmensdk.crt"         # GM encryption cert file path
# default load the GM SSL encryption cert from ${certPath}/gm/gmensdk.crt# enSslKey = "conf/gm/gmensdk.key"          # GM ssl cert file path
# default load the GM SSL encryption privateKey from ${certPath}/gm/gmensdk.key[network]
#peers=["127.0.0.1:20200", "127.0.0.1:20201"]    # The peer list to connect
#修改为服务器IP地址
peers=["这里是你的区块链服务器的ip地址:20200", "这里是你的区块链服务器的ip地址:20201"]    # The peer list to connect
# Configure a private topic as a topic message sender.
# [[amop]]
# topicName = "PrivateTopic1"
# publicKeys = [ "conf/amop/consumer_public_key_1.pem" ]    # Public keys of the nodes that you want to send AMOP message of this topic to.# Configure a private topic as a topic subscriber.
# [[amop]]
# topicName = "PrivateTopic2"
# privateKey = "conf/amop/consumer_private_key.p12"         # Your private key that used to subscriber verification.
# password = "123456"[account]
keyStoreDir = "account"         # The directory to load/store the account file, default is "account"
# accountFilePath = ""          # The account file path (default load from the path specified by the keyStoreDir)
accountFileFormat = "pem"       # The storage format of account file (Default is "pem", "p12" as an option)# accountAddress = ""           # The transactions sending account address
# Default is a randomly generated account
# The randomly generated account is stored in the path specified by the keyStoreDir# password = ""                 # The password used to load the account file[threadPool]
# channelProcessorThreadSize = "16"         # The size of the thread pool to process channel callback
# Default is the number of cpu cores# receiptProcessorThreadSize = "16"         # The size of the thread pool to process transaction receipt notification
# Default is the number of cpu coresmaxBlockingQueueSize = "102400"             # The max blocking queue size of the thread pool

这是利用toml文件的配置形式进行配置 官网提供了其他的配置文件格式 如果有修改 跳转官网文档查看

Fisco-Bcos配置文件详解

3、编写测试方法和读取配置文件
1.编写SpringBoot配置类

在这里插入图片描述

代码如下:

package com.webase.config;import org.fisco.bcos.sdk.BcosSDK;
import org.fisco.bcos.sdk.client.Client;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** @Project: emr* @Package: com.webase.config* @Description:* @author: xiaoMa* @Email:17320080198@163.com* @date: 2024年10月25日 16:30*/
@Configuration
public class BcosClientConfig {@Beanpublic Client client() throws Exception {String path = getClass().getClassLoader().getResource("config-example.toml").getPath();if (path == null) {throw new IllegalArgumentException("找不到配置文件。");}BcosSDK bcosSDK = BcosSDK.build(path);// groupId 设为 1return bcosSDK.getClient(1);}
}

这里是一个Spring配置类,用于配置BcosSDK客户端。这个类通过读取config-example.toml配置文件来初始化BcosSDK,并返回一个Client实例。后面我们测试类会用到

2.编写测试方法 测试合约方法

在这里插入图片描述
在test下创建测试类 注意包名 这里的测试集成了springboot测试

代码如下:

package com.webase;import com.webase.config.BcosClientConfig;
import org.fisco.bcos.sdk.client.Client;
import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;/*** @Project: emr* @Package: com.webase* @Description:* @author: xiaoMa* @Email:17320080198@163.com* @date: 2024年10月25日 16:09*/@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = BcosClientConfig.class)
public class HelloWorldDemoTest {@Autowiredprivate Client client1;@Testpublic void testHello() throws Exception {// 合约地址String contractAddress = "0x8002b168b1f81d6c6d1148f579370648cd28dde8";// 创建一个私钥对CryptoKeyPair keyPair = client1.getCryptoSuite().createKeyPair();// 加载HelloWorld合约HelloWorld helloWorld = HelloWorld.load(contractAddress, client1, keyPair);// 调用HelloWorld合约set方法//TransactionReceipt receipt = helloWorld.set("Hello sent from Java!——10.26");// 打印交易回执的交易哈希//System.out.println(receipt.getTransactionHash());// 调用HelloWorld合约get方法String s = helloWorld.get();// 打印get方法的返回值System.out.println(s);}
}

这里的contractAddress 必须要和前面部署的时候生成的合约地址保存一致!

在这里插入图片描述

1·测试合约的get方法

在这里插入图片描述

可以看出 这个值是咱们之前在WeBASE-Front平台中通过图形化方式进行合约调用所设置的值 没错

2·测试合约的set方法

在这里插入图片描述

测试跑通了 并且返回了交易哈希

我们可以再次调用get方法测试是不是真的成功赋值
在这里插入图片描述

可以看到没有问题 是我们赋的值没错

更多功能接口请移步Fisco-Bcos官网开发文档!
Fisco-Bcos开发文档

http://www.lryc.cn/news/506675.html

相关文章:

  • OpenHarmony-3.HDF Display子系统(6)
  • Nginx中Server块配置的详细解析
  • php学习资料分享
  • EE308FZ_Sixth Assignment_Beta Sprint_Sprint Essay 3
  • Eureka学习笔记-服务端
  • 无限次使用 cursor pro
  • 网站运维之整站同步
  • 【机器人】Graspness 端到端 抓取点估计 | 论文解读
  • 力扣2300.咒语和药水的成功对数(二分法)
  • WEB开发: 全栈工程师起步 - Python Flask +SQLite的管理系统实现
  • 云原生周刊:Kubernetes v1.32 正式发布
  • 京准电钟:电厂自控NTP时间同步服务器技术方案
  • 深入探索Flink的复杂事件处理CEP
  • clickhouse-数据库引擎
  • 力扣hot100——哈希
  • 少样本学习之CAML算法
  • C# 中的闭包
  • 网络编程 03:端口的定义、分类,端口映射,通过 Java 实现了 IP 和端口的信息获取
  • 制作项目之前的分析
  • LeetCode 1925 统计平方和三元组的数目
  • java开发入门学习三-二进制与其他进制
  • C/S软件授权注册系统(Winform+WebApi+.NET8+EFCore版)
  • Linux —— 管理进程
  • Diffusino Policy学习note
  • 【Python】*args和**kwargs
  • 使用正则表达式提取PDF文件页数的实现方案
  • Android实现RecyclerView边缘渐变效果
  • springboot443旅游管理系统(论文+源码)_kaic
  • 利用git上传项目到GitHub
  • Rust之抽空学习系列(四)—— 编程通用概念(下)