FISCO BCOS JAVA SDK(環境搭建)
文章目錄
- FISCO BCOS JAVA SDK(環境搭建)
- 前言
- 一、環境準備
- 1.開發工具
- 2.開發環境
- 二、開發步驟
- 1.創建一個Gradle應用
- 2.引入Java SDK
- 3.配置SDK證書
- 4.準備智能合約
- 5.創建組態檔
- 6.使用Java SDK部署和呼叫智能合約
- 7.運用測驗
- 總結
前言
參考官方檔案
提示:以下是本篇文章正文內容,下面案例可供參考
一、環境準備
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.運用測驗
首先確保我們的區塊鏈網路節點處于運行狀態

測驗結果:

總結
歡迎交流!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/302561.html
標籤:區塊鏈
