FISCO BCOS JAVA SDK(以HelloWorld合约为例)

2023-11-15

FISCO BCOS JAVA SDK(环境搭建)



前言

参考官方文档


提示:以下是本篇文章正文内容,下面案例可供参考

一、环境准备

1.开发工具

Java:JDK 14 (JDK1.8 至JDK 14都支持)
IDE:IntelliJ IDE.

安装官网

2.开发环境

搭建一条FISCO BCOS链
FISCO BCOS安装搭建。

二、开发步骤

1.创建一个Gradle应用

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.引入Java SDK

在build.gradle中引入Java SDK

compile ('org.fisco-bcos.java-sdk:fisco-bcos-java-sdk:2.7.2')

在这里插入图片描述

如果您使用maven 通过以下方法引入Java SDK

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

3.配置SDK证书

SDK证书位于(搭建第一个区块链网络)~/fisco/nodes/127.0.0.1/sdk/目录
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
或者直接拷贝该文件夹
在这里插入图片描述
后续在对其中的配置文件进行修改
在这里插入图片描述

4.准备智能合约

控制台console和java-sdk-demo均提供了工具,可以将solidity合约生成出调用该合约java工具类。本例中使用console做为例子. 使用java-sdk-demo给智能合约生成调用它的Java工具类” 首先,下载控制台。

cd ~/fisco/console

在这里插入图片描述
然后,将您要用到的Solidity智能合约放入~/fisco/console/contracts/solidity的目录。本次我们用console中的HelloWorld.sol作为例子。保证HelloWorld.sol在指定的目录下。

cd ~/fisco/console/contracts/solidity
ls

在这里插入图片描述
生成调用HelloWorld.sol智能合约的java类
代码如下(示例):

#使用sol2java.sh将contracts/solidity下的所有合约编译产生bin,abi,java工具类。
#当前目录~/fisco/console
 bash sol2java.sh org.com.fisco
#以上命令中参数“org.com.fisco”是指定产生的java类所属的包名。
#./sol2java.sh [packageName] [solidityFilePath] [javaCodeOutputDir]

未执行该脚本时:
在这里插入图片描述
执行脚本进行合约编译
在这里插入图片描述
在这里插入图片描述

5.创建配置文件

在项目中创建配置文件config.toml, 可参照配置向导进行配置,也可以参照config-example.toml,

将编译生出的ABI和BIN以及两个配置文件放到resource目录下
在这里插入图片描述
把编译生成的java类,放到新建包(org.com.fisco)下,点击构建项目无报错。
在这里插入图片描述
对配置文件进行修改,IDE工具在Windows系统,区块链网络为centos7服务器上。
如果是虚拟机我们用ifconfig查看IP进行配置,服务器就用服务器ip地址
在这里插入图片描述
在这里插入图片描述

log4j.propertise配置如下:

#
# Copyright 2014-2020  [fisco-dev]
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
#

### set log levels ###
log4j.rootLogger=DEBUG, file

### output the log information to the file ###
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern='_'yyyyMMddHH'.log'
log4j.appender.file.File=./log/console.log
log4j.appender.file.Append=true
log4j.appender.file.filter.traceFilter=org.apache.log4j.varia.LevelRangeFilter
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C{1}.%M(%L) | %m%n

###output the log information to the console ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C{1}.%M(%L) | %m%n

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=["101.37.116.199:20200", "101.37.116.199: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 cores

maxBlockingQueueSize = "102400"             # The max blocking queue size of the thread pool

也可以通过xml配置. 使用xml配置进行配置”。

6.使用Java SDK部署和调用智能合约

在这里插入图片描述

BcosSDKTest代码如下(示例):
官方示例代码

public class BcosSDKTest {
// 获取配置文件路径
public final String configFile = BcosSDKTest.class.getClassLoader().getResource(“config-example.toml”).getPath();
public void testClient() throws ConfigException {
// 初始化BcosSDK
BcosSDK sdk = BcosSDK.build(configFile);
// 为群组1初始化client
Client client = sdk.getClient(Integer.valueOf(1));

    // 获取群组1的块高
    BlockNumber blockNumber = client.getBlockNumber();

    // 向群组1部署HelloWorld合约
    CryptoKeyPair cryptoKeyPair = client.getCryptoSuite().getCryptoKeyPair();
    HelloWorld helloWorld = HelloWorld.deploy(client, cryptoKeyPair);

    // 调用HelloWorld合约的get接口
    String getValue = helloWorld.get();
    
    // 调用HelloWorld合约的set接口
    TransactionReceipt receipt = helloWorld.set("Hello, fisco");
 } }

本运用中代码如下:

package org.com.fisco;

import org.fisco.bcos.sdk.BcosSDK;
import org.fisco.bcos.sdk.client.Client;
import org.fisco.bcos.sdk.client.protocol.response.BcosBlock;
import org.fisco.bcos.sdk.client.protocol.response.BcosTransactionReceipt;
import org.fisco.bcos.sdk.client.protocol.response.BlockNumber;
import org.fisco.bcos.sdk.config.exceptions.ConfigException;
import org.fisco.bcos.sdk.crypto.CryptoSuite;
import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair;
import org.fisco.bcos.sdk.model.TransactionReceipt;
import org.fisco.bcos.sdk.transaction.codec.decode.TransactionDecoderInterface;
import org.fisco.bcos.sdk.transaction.codec.decode.TransactionDecoderService;
import org.fisco.bcos.sdk.transaction.model.exception.ContractException;
import org.junit.Test;

public class BcosSDKTest
{
    // 获取配置文件路径
    public final String configFile = BcosSDKTest.class.getClassLoader().getResource("config-example.toml").getPath();
    @Test
    public void testClient() throws ConfigException {
        // 初始化BcosSDK
        BcosSDK sdk =  BcosSDK.build(configFile);
        // 为群组1初始化client
        Client client = sdk.getClient(Integer.valueOf(1));

        // 获取群组1的块高
        BlockNumber blockNumber = client.getBlockNumber();

        // 向群组1部署HelloWorld合约
        CryptoKeyPair cryptoKeyPair = client.getCryptoSuite().getCryptoKeyPair();
        HelloWorld helloWorld = null;
        try {
            helloWorld = HelloWorld.deploy(client, cryptoKeyPair);
        } catch (ContractException e) {
            e.printStackTrace();
        }
        // 调用HelloWorld合约的get接口
        String getValue= null;
        try {
            getValue = helloWorld.get();
        } catch (ContractException e) {
            e.printStackTrace();
        }
        // 调用HelloWorld合约的set接口
        TransactionReceipt receipt = helloWorld.set("Hello, fisco");

        BcosBlock block = client.getBlockByNumber(blockNumber.getBlockNumber(), false); //得到块的信息
        Object o = block.getBlock().getTransactions().get(0).get(); //在块中得到交易哈希
        Object b = block.getBlock().getHash();//在块中得到区块哈希
        Object c=block.getBlock().getNumber();//当前块高
        BcosTransactionReceipt transactionReceipt = client.getTransactionReceipt((String) o); //通过交易哈希得到交易回执
        CryptoSuite cryptoSuite = client.getCryptoSuite();        // 获取当前群组对应的密码学接口
        // 构造TransactionDecoderService实例,传入是否密钥类型参数。 事务解码器接口
        TransactionDecoderInterface decoder = new TransactionDecoderService(cryptoSuite);
        String setValue = decoder.decodeReceiptMessage(transactionReceipt.getResult().getInput());
        System.out.println("getValue:"+getValue);
        System.out.println("setValue:"+setValue);
        System.out.println("receipt:"+receipt);
    }
}

7.运用测试

首先确保我们的区块链网络节点处于运行状态
在这里插入图片描述
测试结果:
在这里插入图片描述


总结

欢迎交流!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

FISCO BCOS JAVA SDK(以HelloWorld合约为例) 的相关文章

随机推荐

  • 运行vue项目出现错误 SyntaxError:Unexpected identifier

    运行vue项目出现错误 SyntaxError Unexpected identifier 1 运行从svn拉下来的项目 下载完依赖 执行npm install 后 运行出现此错误 2 试了很多方式 重新导入项目 重新下载依赖 查看错误日志
  • Python手册(Python Basics)--Python进阶

    Python 标准库非常庞大 所提供的组件涉及范围十分广泛 正如以下内容目录所显示的 这个库包含了多个内置模块 以 C 编写 Python 程序员必须依靠它们来实现系统级功能 文章目录 字符串 字符串方法 格式化字符串 字符串常量 file
  • C++——并发之std::async使用注意的坑,以及promise,future

    promise背景1 promise背景2 async 1 async 与promise future 1 1 async以及获取时间 async函数如下所示 template
  • matlab-min函数

    matlab对二维矩阵用min函数的用法如下 C min A 如果A是一个向量 min A 返回A中的最小元素 如果A是一个矩阵 min A 将A的每一列作为一个向量 返回一行向量包含了每一列的最小元素 C min A B 返回一个和A和B
  • 不看绝对血亏!java面试项目中的技术难点

    正文 MyBatis 的整体架构分为三层 分别是基础支持层 核心处理层和接口层 如下图所示 基础支持层 反射模块 该模块对 Java 原生的反射进行了良好的封装 提供了更加简洁易用的 API 方便上层使调用 并且对反射操作进行了一系列优化
  • 一边是计算机就业哀鸿遍野,一边是高考生疯狂涌向计算机专业

    在张雪峰推荐的几大专业里 计算机专业是其中之一 近几年 计算机专业报考热度不减 但就业前景却令人堪忧 互联网裁员接二连三 许多码农找不到工作 一位网友感叹 一边是计算机就业哀鸿遍野 一边是高考生疯狂涌向计算机专业 太魔幻了 有人说 大部分家
  • 解决报错:java.net.BindException: 无法指定被请求的地址

    今天在linux虚拟机上装了tomcat 但是一直启动不了 查看日志 主要报错如下 严重 StandardServer await create localhost 8005 java net BindException 无法指定被请求的地
  • VCS IDEA没有Enable Version Control Intergration

    在使用IDEA 提交git push到远程上 找到快忘了的流程 仿照着一步步来 发现都有一个步骤就是指定使用版本管理工具 Enable Version Control Integration 我这找了找发现没有 确实是有这一步指定 版本管理
  • 基于 springboot+vue 进行多条件查询历史聊天记录

    查询历史聊天记录 多条件查询记录是经常需要进行编写的功能 这里就以多条件查询历史聊天记录为例子来介绍如何进行基于关键字 日期 聊天记录类型 三种条件进行模糊查询 日期拼接 条件拼接查询 前端 抽屉管理 首先我们控制 element ui 的
  • spring-boot+maven运行和调试的配置

    spring boot maven 首先说直接运行 WIP Saved Searches migrated to WS 6 0 NJ数据下载工具 基于spring boot的小工具运行方法 在控制台上跳转到项目里initial文件夹所在的目
  • 火币什么时间服务器维护,火币全球站已于今日21:45进行系统维护,时间?

    8月10日消息 Twitter在6月30日发布的NFT系列 The 140 Collection 在OpenSea NFT市场上创造了1700 ETH 530万美元 的总交易量 虽然这个数字远低于Axis Infinity和CryptoPu
  • 一个简单的CountDownLauch

    这个类的主要功能就是 当多个线程运行的时候 count满足一定的条件的时候 这里为0 部分线程才开始工作 具体如下 include
  • Python py文件打包成 exe文件

    文章目录 安装 pyinstaller 模块 pyinstaller 的使用 pyinstaller 常用参数 多文件打包 安装 pyinstaller 模块 pip install pyinstaller i https pypi tun
  • 个人简历与自我介绍

    尊敬的面试官你好 我叫谢炜豪 我对本次校招的软件研发工程师和C 开发工程师很感兴趣 希望能得到在贵公司发挥作用的机会 以下是我的自我介绍 我所学的专业是计算机科学与技术 在校期间 除了专业的必修课程之外 我还重点学习了C 语言 能够熟练使用
  • linux sftp目录无法切换,linux – SFTP用户无法编辑或创建文件

    要正确chroot sftponly组成员 您需要在 etc ssh sshd config中设置此选项 Subsystem sftp internal sftp Match Group sftponly ChrootDirectory s
  • 多线程入门学习

    多线程 目录 多线程 1 继承Thread类 2 网图下载 3 初识并发问题 4 龟兔赛跑 5 lamda表达式 6 线程休眠Sleep 1 sleep 时间 指定当前线程阻塞的毫秒数 2 sleep存在异常InterruptedExcep
  • canvas圆球碰撞检测

    本文为canvas绘制圆形碰撞检测 圆形与圆形 后期一直更新哦 x 圆横坐标 y 圆纵坐标 r 圆半径 w 浏览器宽度 h 浏览器高度 arc画圆碰撞 move移动后 碰撞浏览器边缘反弹回来 碰撞检测 x r lt 0 浏览器左边缘 x r
  • Android Studio 中的 Gradle 是什么

    Gradle 是什么 学习内容 Gradle 是一个构建系统 在使用 Android Studio 之前 您将Eclipse用于开发目的 而且很可能您不知道如何在没有 Eclipse 的情况下构建您的 Android APK 您可以在命令行
  • 2020年度 个人随笔

    2020年的年度总结其实很好写 for index in 0 2 Log 我太难了 Log 完 2020年这么难 哪里还有心情写总结 回归正题 总结还是要写的 毕竟人老了就爱回忆 就让往事随风 往事随风 随风 风 前言 马上就是2021年了
  • FISCO BCOS JAVA SDK(以HelloWorld合约为例)

    FISCO BCOS JAVA SDK 环境搭建 文章目录 FISCO BCOS JAVA SDK 环境搭建 前言 一 环境准备 1 开发工具 2 开发环境 二 开发步骤 1 创建一个Gradle应用 2 引入Java SDK 3 配置SD