java如何对接波场链

这篇具有很好参考价值的文章主要介绍了java如何对接波场链。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

java如何对接波场链,java,开发语言,区块链

引言

本文将通过列举一些核心步骤的例子,确保大家看完之后能通过举一反三自行对接。
0,建立波场链连接
1,同步区块,
2,区块解析
3,交易状态判断
4,交易转账如何打包
5,如何调用链上指定方法
6,本地钱包如何生成

java如何对接波场链,java,开发语言,区块链

首先引入tron核心pom依赖,由于科学上网的原因,我是直接从官网下的包,jar包我放在文章最后面
依赖配置如下

        <dependency>
            <groupId>com.github.tronprotocol</groupId>
            <artifactId>java-tron</artifactId>
            <version>Odyssey-v3.2</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/lib/java-tron-Odyssey-v3.2.jar</systemPath>
        </dependency>

上DEMO

0,建立波场链连接


 

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

 
public class TronRpcUtil {
    private static final Logger log = LoggerFactory.getLogger(TronRpcUtil.class);

    private static final RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());


    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    public TronRpcUtil() {
        dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    }


    /**
     * get请求,返回JSONObject
     * @param url
     * @return
     */
    public ResponseEntity<JSONObject> get(String url) {
        ResponseEntity<JSONObject> responseEntity = null;
        try {
            responseEntity = restTemplate.getForEntity(url, JSONObject.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseEntity;
    }

    /**
     * get请求,返回String
     * @param url
     * @return
     */
    public ResponseEntity<String> getResponseString(String url) {
        ResponseEntity<String> responseEntity = null;
        try {
            responseEntity = restTemplate.getForEntity(url, String.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseEntity;
    }

    /**
     * post请求
     * @param url
     * @param parameterJson
     * @return
     */
    public ResponseEntity<JSONObject> post(String url, String parameterJson) {
        ResponseEntity<JSONObject> responseEntity = null;
        try {
            responseEntity = restTemplate.postForEntity(url, parameterJson, JSONObject.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseEntity;
    }

    /**
     * post请求
     *
     * @param url 测试网:https://api.shasta.trongrid.io/
     * @param parameterJson
     * @return
     */
    public ResponseEntity<String> postResponseString(String url, String parameterJson) {
        ResponseEntity<String> responseEntity = null;
        try {
            responseEntity = restTemplate.postForEntity(url, parameterJson, String.class);
        } catch (Exception e) {
             log.error("广播请求异常",e);
        }
        return responseEntity;
    }

    /**
     * 配置HttpClient超时时间
     * @return
     */
    private static ClientHttpRequestFactory getClientHttpRequestFactory() {
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(6000)
                .setConnectTimeout(10000).build();
        CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
        return new HttpComponentsClientHttpRequestFactory(client);
    }
}

1,同步区块,

    public JSONObject getNewBlock() {
        String url = tronConfig.getInstance().getUrl() + WALLET + GET_NOW_BLOCK;
        ResponseEntity<String> responseEntity = tronRpc.getResponseString(url);
        if (responseEntity == null) return null;
        return JSONObject.parseObject(responseEntity.getBody());
    }
    public BigInteger getNewBlocknNumber() {

        JSONObject jsonObject = getNewBlock();
        if(jsonObject != null){
            return jsonObject.getJSONObject("block_header").getJSONObject("raw_data").getBigInteger("number");

        }
        return null;
    }

2,区块解析

            JSONObject jsonObject = tronWalletUtilService.getBlockByNum(blockNumber);

    public JSONObject getBlockByNum(BigInteger num) {
        String url = tronConfig.getInstance().getUrl() + WALLET + GET_BLOCK_BY_NUM;
        Map<String, BigInteger> map = new HashMap<>();
        map.put("num", num);
        String param = JsonUtils.objectToJson(map);
        return getPost(url, param);
    }
    private JSONObject getPost(String url, String param) {
        ResponseEntity<String> stringResponseEntity = tronRpc.postResponseString(url, param);
        if (stringResponseEntity == null) return null;
        return JSONObject.parseObject(stringResponseEntity.getBody());
    }

3,交易状态判断

    public JSONObject getTransaction(String hashId) {
        String url = tronConfig.getInstance().getUrl() + WALLET + GET_TRANSACTION;
        Map<String, String> map = new HashMap<>();
        map.put("value", hashId);
        String param = JsonUtils.objectToJson(map);
        ResponseEntity<String> stringResponseEntity = tronRpc.postResponseString(url, param);
        try {
            if (stringResponseEntity != null) return JSONObject.parseObject(stringResponseEntity.getBody());
        } catch (Exception e) {
            return null;
        }
        return null;
    }

4,交易转账如何打包

    /**
     * trx
     * @param owner
     * @param privateKey
     * @param to
     * @param amount
     * @return
     */
    @Override
    public String handleTransactionTRX(String owner, String privateKey, String to, BigInteger amount) {
        log.info("Tron 转账入参:{}, {}, {}, {}",owner,privateKey,to,amount);
        // 创建交易
        String url = tronConfig.getInstance().getUrl() + WALLET + CREATE_TRANSACTION;
        Map<String, Object> map = new HashMap<>();
        map.put("to_address", to);
        map.put("owner_address", owner);
        map.put("amount", amount);
        String param = JsonUtils.objectToJson(map);
        ResponseEntity<String> stringResponseEntity = tronRpc.postResponseString(url, param);
        log.info("创建交易:{}",stringResponseEntity);
        return signAndBroadcast(stringResponseEntity.getBody(), privateKey);
     }

/**
     * 交易TRC20
     *
     * @param owner
     * @param privateKey
     * @param to
     * @param amount
     * @param tokenHexAddr
     * @return
     */
    @Override
    public String handleTransactionTRC20(String owner, String privateKey, String to, BigInteger amount, String tokenHexAddr) {
        log.debug("trc20转账入参:owner:{},privateKey:{},to:{},amount:{},tokenHexAddr:{}",owner,privateKey,to,amount,tokenHexAddr);
        String url = tronConfig.getInstance().getUrl() + WALLET + TRIGGER_SMART_CONTRACT;
        // 格式化参数
        log.info("owner:{}, parameter:{}",owner,to);
        String parameter = formatParameter(to) + formatParameter(amount.toString(16));
        Map<String, Object> map = new HashMap<>();
        map.put("contract_address", tokenHexAddr);
        map.put("function_selector", "transfer(address,uint256)");
        //最高gas 不超过30trx
        map.put("fee_limit", 30000000);
        map.put("parameter", parameter);
        map.put("owner_address", owner);
        log.info(JsonUtils.objectToJson(map));
        ResponseEntity<String> stringResponseEntity = tronRpc.postResponseString(url, JsonUtils.objectToJson(map));
        JSONObject data = JSONObject.parseObject(stringResponseEntity.getBody());
        JSONObject transaction = data.getJSONObject("transaction");
        transaction.remove("visible");
        transaction.remove("raw_data_hex");
        return signAndBroadcast(JsonUtils.objectToJson(transaction), privateKey);
    }

5,如果调用链上指定方法

6,本地钱包如何生成

 

 
import org.spongycastle.math.ec.ECPoint;
import org.tron.common.crypto.ECKey;
import org.tron.common.crypto.Hash;
import org.tron.common.crypto.Sha256Sm3Hash;
import org.tron.common.utils.Base58;
import org.tron.common.utils.ByteArray;
import org.tron.common.utils.Utils;
import org.tron.core.exception.CipherException;
import org.tron.walletserver.WalletApi;

import java.math.BigInteger;

import static java.util.Arrays.copyOfRange;

public class ECCreateKey {

  private static byte[] private2PublicDemo(byte[] privateKey) {
    BigInteger privKey = new BigInteger(1, privateKey);
    ECPoint point = ECKey.CURVE.getG().multiply(privKey);
    return point.getEncoded(false);
  }


  private static byte[] public2AddressDemo(byte[] publicKey) {
    byte[] hash = Hash.sha3(copyOfRange(publicKey, 1, publicKey.length));
    //System.out.println("sha3 = " + ByteArray.toHexString(hash));
    byte[] address = copyOfRange(hash, 11, hash.length);
    address[0] = WalletApi.getAddressPreFixByte();
    return address;
  }

  public static String address2Encode58CheckDemo(byte[] input) {
    byte[] hash0 = Sha256Sm3Hash.hash(input);

    byte[] hash1 = Sha256Sm3Hash.hash(hash0);

    byte[] inputCheck = new byte[input.length + 4];

    System.arraycopy(input, 0, inputCheck, 0, input.length);
    System.arraycopy(hash1, 0, inputCheck, input.length, 4);

    return Base58.encode(inputCheck);
  }

  public static String private2Address() throws CipherException {
    ECKey eCkey = new ECKey(Utils.getRandom()); //

    String privateKey=ByteArray.toHexString(eCkey.getPrivKeyBytes());
    System.out.println("Private Key: " + privateKey);

    byte[] publicKey0 = eCkey.getPubKey();
    byte[] publicKey1 = private2PublicDemo(eCkey.getPrivKeyBytes());
    if (!ECCreateKey.equals(publicKey0, publicKey1)) {
      throw new CipherException("publickey error");
    }
    String publicKey=ByteArray.toHexString(publicKey0);
    System.out.println("Public Key: " + publicKey);

    byte[] address0 = eCkey.getAddress();
    byte[] address1 = public2AddressDemo(publicKey0);
    if (!ECCreateKey.equals(address0, address1)) {
      throw new CipherException("address error");
    }
    String address=ByteArray.toHexString(address0);
    System.out.println("Address: " +address);

    String base58checkAddress0 = WalletApi.encode58Check(address0);
    String base58checkAddress1 = address2Encode58CheckDemo(address0);
    if (!base58checkAddress0.equals(base58checkAddress1)) {
      throw new CipherException("base58checkAddress error");
    }
    String dataList=privateKey+ TronConstant.DELIMIT+base58checkAddress1+TronConstant.DELIMIT+address;
    return dataList;
  }

  public static boolean equals(byte[] a, byte[] a2) {
    if (a==a2)
      return true;
    if (a==null || a2==null){
      System.out.println("都为null");
      return false;
    }


    int length = a.length;
    if (a2.length != length){
      System.out.println("长度不等");
      return false;
    }


    for (int i=0; i<length; i++)
      if (a[i] != a2[i]){
        System.out.println("值不等");
        return false;
      }


    return true;
  }

  public static void main(String[] args) throws CipherException {

 
    System.out.println("================================================================\r\n");
    String dataList = private2Address();
    System.out.println("base58Address: " + dataList);
    String[] split = dataList.split(TronConstant.DELIMIT);
    String privateKey = split[0];
    String address = split[1];
    String hexAddress =split[2];
    System.out.println("privateKey:"+privateKey+" address:"+address+" hexAddress:"+hexAddress);
  }
}

到这里基本上一套完整的流程已经对接完了,剩下的稍微琢磨一下就全明白了,至于详细的波场链字段说明,参考api即可文章来源地址https://www.toymoban.com/news/detail-850447.html

到了这里,关于java如何对接波场链的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 区块链-java对接web3合约

    本文章讲述了如何在合约已经部署并且能拿到合约abi文件的情况下,用java代码去进行调用合约 已经部署好的合约地址 编译合约后生成的abi文件  通过hardhat-build去编译 通过remix网站去编译获取(教程可自行百度查询) 引入web3的jar包 版本用最新的就行了 引入web3j-maven-plugin 将编

    2024年01月16日
    浏览(41)
  • GO语言-区块链离线钱包开发之如何存储私钥

    # 如何存储私钥 在确保私钥安全的情况下,为了更好的体验,我们需要让钱包把私钥存储起来。给用户更好的体验感。Geth是将私钥通过加密技术转换为json格式的文件,这个文件虽然是明文的,但是解析它的时候需要密码,否则将无法解密。 在Geth中,使用`personal.newAccount(\\\"p

    2024年02月16日
    浏览(28)
  • 波场(Tron)监控区块交易记录(http 版本,不依赖 sdk)

    做项目的时候经常需要通过监控链的区块交易记录,然后根据交易记录与用户的地址进行核对,从而得知用户地址的充币和提币的情况。 引用依赖 这段代码运行的时候,首选是获取的最新的区块高度(接口 getnowblock),然后逐个累加(接口 getblockbynum)区块进行检查,核对交

    2024年01月18日
    浏览(47)
  • 微信支付-超详细java开发-小程序对接

    本文适用于有一定基础的开发者,简单易通。后台用的的是java,我用的是springBoot,其它框架基本同理,前端就是一个简单的demo。微信官方提供了V2和V3两种方式,本文基于V2版支付开发(后续更新V3)。V2和V3版本区别 1.思路介绍 本次以微信小程序开发为例,如果自己想要玩一

    2024年02月09日
    浏览(41)
  • Android 安卓开发语言kotlin与Java该如何选择

            如今在Android开发中,应用层开发语言主要是Java和Kotlin,Kotlin是后来加入的,主导的语言还是Java。kotlin的加入仿佛让会kotlin语言的开发者更屌一些,其实不然。         有人说kotlin的引入是解决开发者复杂的逻辑,并且对空指针控制的比较友好,但是我们在开

    2024年02月11日
    浏览(33)
  • java如何对接cahtgpt API(简单记录)

    springboot+mybatis-plus 通过java调用chatgpt API实现对话,将chatgpt生成的内容通过与前端建立websocket及时发送给前端,为加快chatgpt响应速度,采用exent/stream的方式进行,实现了逐字出现的效果 java对接chatgpt API 使用java原生的网络请求方式完成 在发送网络请求时,将\\\"stream\\\"设置为 tru

    2024年02月16日
    浏览(29)
  • 用Python编程实现百度自然语言处理接口的对接,助力你开发智能化处理程序

    用Python编程实现百度自然语言处理接口的对接,助力你开发智能化处理程序 随着人工智能的不断进步,自然语言处理(Natural Language Processing,NLP)成为了解决文本处理问题的重要工具。百度自然语言处理接口提供了一系列强大的功能,如提取、文本分类、情感分析等,

    2024年02月13日
    浏览(49)
  • Java 亚马逊Amazon spapi对接开发,java Sdk,授权和接口访问步骤详细说明

    确认是否收到通过sp-api开发人员资料申请。   创建一个策略,我们建议您将 IAM 策略命名为 SellingPartnerAPI 。     开发商名称:任意字符 开发者id :accessKeyId 客户端相关信息,包含clientId和clientSecret。 1.8.1访问需要的参数和数据如图 参数 说明 样例 roleArn 角色Arn,在角色中

    2024年02月03日
    浏览(32)
  • 设计模式之美-实战二:如何对接口鉴权这样一个功能开发做面向对象分析?

            面向对象的三个环节:面向对象分析(OOA)、面向对象设计(OOD)、面向对象编程(OOP)。只知道OOA、OOD、OOP只能说有一个宏观了解,我们更重要的还是要知道“如何做”,也就是,如何进行面向对象分析、设计与编程。         本文结合一个真实的开发案例,从基

    2024年02月09日
    浏览(32)
  • 【区块链技术开发】 关于Windows10平台Solidity语言开发环境配置

    在 Windows 上配置 Solidity 语言开发环境需要进行以下步骤:

    2023年04月20日
    浏览(44)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包