Calling Java SDK in FISCO BCOS blockchain system

New SpringBoot project

  • Use IDEA to create a new SpringBoot project, use Maven to manage dependencies, and select Spring Web as the dependency of SpringBoot.

Add FISCO BCOS blockchain system dependency

  • Add the Java SDK dependency of the FISCO BCOS blockchain system in pom.xml
<dependency>
<groupId>org.fisco-bcos.java-sdk</groupId>
<artifactId>fisco-bcos-java-sdk</artifactId>
<version>2.9.1</version>
</dependency>

Copy the blockchain key

  • Create a new folder conf under resources in the project directory

  • Copy the certificate in the “blockchain folder/nodes/${ip}/sdk/” directory to the conf folder
  • My blockchain folder is fisco, and I deploy a local four-node blockchain, so my IP here is 127.0.0.1, and the certificates under the folder are as follows

Configuring the blockchain system

  • Create the configuration file fisco-config.toml under the project’s resources

  • The sample code of fisco-config.toml is given below
[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=["192.168.3.54:20200", "192.168.3.54:20201", "192.168.3.54:20202", "192.168.3.54:20203"] # The peer list to connect


# AMOP configuration
# You can use the following two methods to configure as a private topic message sender or subscriber.
# Usually, the public key and private key are generated by subscriber.
# Message sender receive public key from topic subscriber then make configuration.
# But, please do not config as both the message sender and the subscriber of one private topic, or you may send the message to yourself.

# Configure a private topic as a topic message sender.
# [[amop]]
# topicName = "PrivateTopic"
# 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 = "PrivateTopic"
# 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

  • The main modification is peers=[“192.168.3.54:20200”, “192.168.3.54:20201”, “192.168.3.54:20202”, “192.168.3.54:20203”], which represents the value in your own blockchain The ip and port of each node. Since my blockchain system runs on a virtual machine, I fill in the ip address of the virtual machine here. If the node runs on this machine, fill in the ip address here as 127.0.0.1

Convert smart contracts into Java classes

  • The written smart contract must be converted into a Java class if it is to be used in a Java project. The FISCO BCOS system provides us with a conversion script, but we need to download the console first.
mkdir -p ~/fisco & amp; & amp; cd ~/fisco
# Get the console
curl -#LO https://github.com/FISCO-BCOS/console/releases/download/v2.9.2/download_console.sh

# If the above command cannot be executed for a long time due to network problems, please try the following command:
https://osp-1257653870.cos.ap-guangzhou.myqcloud.com/FISCO-BCOS/console/releases/v2.9.2/download_console.sh

bash download_console.sh

  • Put the Solidity smart contract you need to use into the directory of fisco/console/contracts/solidity. Here I use HelloWorld.sol in the console as an example. Make sure HelloWorld.sol is in the specified directory, and then enter the directory fisco/console
# Enter the directory ~/fisco/console
cd ~/fisco/console
  • Generate the Java class corresponding to the smart contract. Here you need to use different commands according to the console version used.
If the console version is greater than or equal to 2.8.0:
# Use sol2java.sh to compile all contracts under contracts/solidity to generate bin, abi, and java tool classes.
# Current directory ~/fisco/console
$ bash sol2java.sh -p org.com.fisco
# The parameter "org.com.fisco" in the above command is the package name to which the generated java class belongs.
# Use the command ./sol2java.sh -h to view how to use this script.

If the console version is less than 2.8.0:
# Use sol2java.sh to compile all contracts under contracts/solidity to generate bin, abi, and java tool classes.
# Current directory ~/fisco/console
$ bash sol2java.sh org.com.fisco
# The parameter "org.com.fisco" in the above command is the package name to which the generated java class belongs.
# ./sol2java.sh [packageName] [solidityFilePath] [javaCodeOutputDir]
  • Copy the generated Java class to the project, and the location must be the same as the package name we set.

Create and write a controller class

  • Create a new package controller in the project and create a new controller class FiscoController. The controller code is as follows
package com.example.fiscotest.controller;

import com.example.fiscotest.HelloWorld;
import org.fisco.bcos.sdk.BcosSDK;
import org.fisco.bcos.sdk.client.Client;
import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FiscoController {<!-- -->
    public final String configFile = FiscoController.class.getClassLoader().getResource("fisco-config.toml").getPath();
    BcosSDK sdk = BcosSDK.build(configFile);
    Client client = sdk.getClient(Integer.valueOf(1));

    HelloWorld helloWorld=null;
    @GetMapping("/deploy")
    public String deploycontract() throws Exception{<!-- -->
        CryptoKeyPair cryptoKeyPair = client.getCryptoSuite().getCryptoKeyPair();
        helloWorld = HelloWorld.deploy(client,cryptoKeyPair);
        return "deploy success!!";
    }

    @GetMapping("/get")
    public String getcontract() throws Exception{<!-- -->
        String value = helloWorld.get();
        return "ContractValue=" + value;
    }

    @PostMapping("/set")
    public String setcontract(String name) throws Exception{<!-- -->
        helloWorld.set(name);
        String value = helloWorld.get();
        return "set success!! now ContractValue=" + value;
    }
}

Test Java SDK

  • Run the SpringBoot project
  • Enter the virtual machine to run the blockchain node

  • Enter the blockchain and run the blockchain browser

  • Successfully enter the blockchain browser by accessing http://${virtual machine ip}:5100 on this machine.

  • Test the deployment of smart contracts locally through the browser

  • Test the acquisition of the smart contract name through the browser on this machine

  • Test the modification of the smart contract name through ApiPost on this machine

  • After the above test, refresh the blockchain browser and find that the data has changed and the Java SDK was successfully called in our project.