Using WEB3J to interact with intelligent contracts

Source: Internet
Author: User

WEB3J Documents: Https://web3j.readthedocs.io/en/latest

JAVA-IPFS-API Documents: Https://github.com/ipfs/java-ipfs-api

You've been using Nodejs to invoke web3.js to interact with smart contracts, but you haven't found a way to interact with Java projects. The original Ethernet square is a Java interface web3j.

This article implements:

1, the data exist IPFs above, get the hash, will be the hash of the block chain above.

2, from the block chain to get the hash, through the hash from the data on the IPFs down.

--------------------------------------------------------------------------------------------------------------- ----------

Environment configuration:

First, import the web3j and IPFs jar packages into the project (refer to the topmost document), or download and import them yourself, download the address:

Web3j:https://github.com/web3j/web3j/releases

Java-ipfs-api:https://github.com/ipfs/java-ipfs-api/releases

--------------------------------------------------------------------------------------------------------------- -------------

1, the use of Geth to build a private chain, create an account, mining to obtain some ether, the following deployment or loading contracts will use this account.

2. Create a contract only:

pragma solidity ^0.4.17;

Contract data{

  string public Data;

  function data () public{
    data = "";
  }
  function SetData (string str) public payable{
    data = str;
  }

  function GetData () public view Returns (String) {return
    data;
  }
}

3, compile, generate Java files

Solcjs Data.sol--abi--bin-o./

Data_sol_data.abi files and Data_sol_data.bin files are generated at this time, and the following command uses these two files

The address of the. bin file after the web3j solidity generate--soliditytypes < smart contract is >.bin < the address of the. Abi file after the compilation of the smart contract >.abi-o/PATH/TO/SRC /main/java-p Com.your.organisation.name

The location of the generated Java file after-O followed by the package name of the generated Java file-p

(Web3j is a command-line tool, installed in the top of the document, I use Linux, using the decompression package in the WEB3J)

Generate Java files directly in a Java project, or after a build to copy the past to change the package name. The following are auto-generated Java files:

Package test_eth;
Import Java.math.BigInteger;
Import Java.util.Arrays;
Import java.util.Collections;
Import org.web3j.abi.TypeReference;
Import org.web3j.abi.datatypes.Function;
Import Org.web3j.abi.datatypes.Type;
Import org.web3j.abi.datatypes.Utf8String;
Import Org.web3j.crypto.Credentials;
Import org.web3j.protocol.Web3j;
Import Org.web3j.protocol.core.RemoteCall;
Import Org.web3j.protocol.core.methods.response.TransactionReceipt;
Import Org.web3j.tx.Contract;

Import Org.web3j.tx.TransactionManager;
 /** * <p>auto generated code. * <p><strong>do not modify!</strong> * <p>please use the <a href= "https://docs.web3j.io/" command_line.html ">web3j command line tools</a>, * or the Org.web3j.codegen.SolidityFunctionWrapperGenerator
 In the * <a href= "Https://github.com/web3j/web3j/tree/master/codegen" >codegen module</a> to update.
 * * <p>generated with web3j version 3.3.1.
* * public class Data_sol_data extends Contract {    private static final String BINARY = " 6060604052341561000f57600080fd5b6040805190810160405280600981526020017f696e69742064617461000000000000000000000000000000000 00000000000008152506000908051906020019061005a929190610060565b50610105565b828054600181600116156101000203166002900490600052 602060002090601f016020900481019282601f106100a157805160ff19168380011785556100cf565b828001600101855582156100cf579182015b828 111156100ce5782518255916020019190600101906100b3565b5b5090506100dc91906100e0565b5090565b61010291905b808211156100fe57600081 60009055506001016100e6565b5090565b90565b61040f806101146000396000f300606060405260043610610057576000357c0100000000000000000 000000000000000000000000000000000000000900463ffffffff1680633bc5de301461005c57806347064d6a146100ea57806373d4a13a1461013c57 5b600080fd5b341561006757600080fd5b61006f6101ca565b60405180806020018281038252838181518152602001915080519060200190808383600 05b838110156100af578082015181840152602081019050610094565b50505050905090810190601f1680156100dc5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61013a600480803590602001908201803590602001908080601f01602 080910402602001604051908101604052809392919081815260200183838082843782019150505050505091905050610272565b005b34156101475760 0080fd5b61014f61028c565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561018f578082015 181840152602081019050610174565b50505050905090810190601f1680156101bc5780820380516001836020036101000a031916815260200191505b 509250505060405180910390f35b6101d261032a565b60008054600181600116156101000203166002900480601f01602080910402602001604051908 10160405280929190818152602001828054600181600116156101000203166002900480156102685780601f1061023d57610100808354040283529160 200191610268565b820191906000526020600020905b81548152906001019060200180831161024b57829003601f168201915b5050505050905090565 b806000908051906020019061028892919061033e565b5050565b60008054600181600116156101000203166002900480601f01602080910402602001 60405190810160405280929190818152602001828054600181600116156101000203166002900480156103225780601f106102f757610100808354040283529160200191610322565b8201919 06000526020600020905b81548152906001019060200180831161030557829003601f168201915b505050505081565b60206040519081016040528060 0081525090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061037f57805160ff191 68380011785556103ad565b828001600101855582156103ad579182015b828111156103ac578251825591602001919060010190610391565b5b509050 6103ba91906103be565b5090565b6103e091905b808211156103dc5760008160009055506001016103c4565b5090565b905600a165627a7a72305820c

    88de5343e43686be6997856d3a1239da233f21f97cf4a51b590864fd723010c0029 "; Protected Data_sol_data (String contractaddress, web3j web3j, Credentials Credentials, BigInteger Gasprice, BigInteger
    Gaslimit) {super (BINARY, contractaddress, web3j, credentials, Gasprice, gaslimit); } protected Data_sol_data (String contractaddress, web3j web3j, TransactionManager TransactionManager, BigInteger Gasprice, BigInteger gaslimit) {super (BINARY, contractaddress, web3j, TransactionManager, Gasprice, G
    Aslimit); 
                The public remotecall<string> GetData () {final function function = new function ("GetData") Arrays.<type>aslist (), Arrays.<typereference<?>>aslist (New Typereference<utf8str
        Ing> () {}));
    return Executeremotecallsinglevaluereturn (function, string.class); Public remotecall<transactionreceipt> setData (String str, BigInteger weivalue) {final Function funct Ion = new Function ("SetData", Arrays.<type>aslist (new Org.web3j.abi.datatypes.Utf8
        String (str)), collections.<typereference<?>>emptylist ());
    return executeremotecalltransaction (function, weivalue); Public remotecall<string> data () {final function function = new function ("Data", Ar RayS.<type>aslist (), Arrays.<typereference<?>>aslist (New typereference<utf8string> ()
        {}));
    return Executeremotecallsinglevaluereturn (function, string.class); public static remotecall<data_sol_data> Deploy (web3j web3j, Credentials Credentials, BigInteger Gasprice, big Integer gaslimit) {return Deployremotecall (Data_sol_data.class, web3j, credentials, Gasprice, Gaslimit, BINARY, "
    ");  public static remotecall<data_sol_data> Deploy (web3j web3j, TransactionManager TransactionManager, BigInteger Gasprice, BigInteger gaslimit) {return Deployremotecall (Data_sol_data.class, web3j, TransactionManager, GasPrice
    , Gaslimit, BINARY, "");  public static Data_sol_data load (String contractaddress, web3j web3j, Credentials Credentials, BigInteger Gasprice,
    BigInteger gaslimit) {return to New Data_sol_data (contractaddress, web3j, credentials, Gasprice, gaslimit); } public static Data_Sol_data Load (String contractaddress, web3j web3j, TransactionManager TransactionManager, BigInteger GasPrice,
    BigInteger gaslimit) {return to New Data_sol_data (Contractaddress, web3j, TransactionManager, Gasprice, GasLimit);
 }
}

4, write code that interacts with IPFs Ipfsfile.java:

Package test_eth;

Import java.io.IOException;
Import Io.ipfs.api.IPFS;
Import Io.ipfs.api.MerkleNode;

Import io.ipfs.api.NamedStreamable; public class Ipfsfile {public static string add (String data) throws IOException {IPFs IPFs = new IPFs ("/ip4/127.0.0
		.1/tcp/5001 ");
		Namedstreamable.bytearraywrapper file = new Namedstreamable.bytearraywrapper (Data.getbytes ());
		Merklenode hash = ipfs.add (file). Get (0);
	return hash.hash.toString ();
		public static string get (String hash) throws IOException {IPFs IPFs = new IPFs ("/ip4/127.0.0.1/tcp/5001");
		Merklenode MD = new Merklenode (hash);
		byte[] data = Ipfs.cat (Md.hash);
	return new String (data); }//public static void Main (String []argv) {//try {//String hash = Add ("\ name\": \ zhj\ "");//System.out.prin
TLN ("hash:" +hash);
String data = get (hash);
SYSTEM.OUT.PRINTLN ("Data:" +data); catch (IOException e) {////TODO auto-generated catch block//E.printstacktrace ();//}//}}

5, write Blockchain-ipfs Interactive code Dataoperator.java:

Package test_eth;

Import java.io.IOException;
Import org.web3j.crypto.CipherException;
Import Org.web3j.crypto.Credentials;
Import Org.web3j.crypto.WalletUtils;

Import org.web3j.protocol.Web3j; public class Dataoperator {//Get hash form blockchain, then get data from IPFs using the hash public String GetData (W
		Eb3j web3j) throws Exception {Credentials Credentials = walletutils.loadcredentials (Consts.password, Consts.path);
		String address = consts.address;
		Data_sol_data DATAOP = Data_sol_data.load (consts.address, web3j, credentials, Consts.gas_price, consts.gas_limit);
		String Ipfs_hash = Dataop.getdata (). Send ();

		String data = Ipfsfile.get (Ipfs_hash);
	return data; }//Set data to IPFs and get a hash, the save the hash to blockchain public Boolean setData (web3j web3j, String data)
		Throws Exception {Credentials Credentials = walletutils.loadcredentials (Consts.password, Consts.path);
		String address = consts.address; Data_sol_data DATAOP = Data_sol_datA.load (consts.address, web3j, credentials, Consts.gas_price, consts.gas_limit);
		String Ipfs_hash = ipfsfile.add (data);
		Dataop.setdata (Ipfs_hash, Consts.gas_value). Send ();
	return true; }
}

There is no deployment contract above, deployed directly before loading. If you have not already deployed, you can use the Data_sol_data.deploy () function to deploy, only once to record the address of the contract, the next call before the direct load has been deployed to the good.

(Supplemental: The way to connect the chain above is unsafe because no chain_id is specified, so it is possible to broadcast the information to another chain, which can be set up in the following way:

TransactionManager TransactionManager = new Rawtransactionmanager (web3j, credentials, Consts.chainid);
DATAOP = Dataoperatorcontract.load (address, web3j, TransactionManager, Consts.gas_price, Consts.gas_limit);
So it won't be broadcast to the other chain.

The constants used are written in a Consts.java file:

Package test_eth;

Import Java.math.BigInteger;

public class Consts {

	//gas price public
    static BigInteger Gas_price = Biginteger.valueof (20_000_000_000l);
    Gas cap public
    static BigInteger gas_limit = Biginteger.valueof (4_300_000l);

    Transaction costs public
    static BigInteger Gas_value = Biginteger.valueof (100_000l);;
    Account password public
    static String PASSWORD = "123";
    Account file path public
    static String path = "/home/zhj/project/test_chain/web3j/keystore/ utc--2018-03-25t08-56-52.659408004z--5daa1392dc380cbbd7fb86614514c80bb7b54424 ";
    The address of the contract, recorded after the first deployment of public
    static String addresses = "0x9bc65f8c4f3dc31436e561cd6d893669710225e2";
    public static byte Chainid = (byte) 1234; Chain ID, defined in the Genesis block

6, test entrance:

Package test_eth;

Import org.web3j.protocol.Web3j;
Import Org.web3j.protocol.http.HttpService;

public class Test {public

	static void Main (string[] argv) {
		try {
			web3j web3j = web3j.build (New Httpservice (" http://localhost:8545 "));

			Dataoperator DATAOP = new Dataoperator ();

			String data = "";

			Set data and get Data
			dataop.setdata (web3j, "Fly");
			data = Dataop.getdata (WEB3J);
			SYSTEM.OUT.PRINTLN ("Data:" + data);
		} catch (Exception e) {
			e.printstacktrace ();}}}

7. Operation:

Start IPFs, command line input: IPFs daemon

Enter the Geth console interface for digging (if a mine card is dug, it can be dug only at the time of deployment of the contract and SetData)


(This article only implements some simple functions, complex operations refer to official documents)

Article reference: HTTPS://WWW.JIANSHU.COM/P/3671B65462AA



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.