From 4a6da027fb4f1376f7aa0b57a6d7f92fdc82f73a Mon Sep 17 00:00:00 2001
From: Helius <wangdoubleone@gmail.com>
Date: Fri, 11 Jun 2021 15:49:45 +0800
Subject: [PATCH] modify
---
src/main/java/com/xcong/excoin/modules/blackchain/service/TrxUsdtUpdateService.java | 378 +++++++++++++++++++++++++++++++++++++++++++++++
src/main/java/com/xcong/excoin/quartz/job/BlockCoinUpdateJob.java | 68 ++++++++
src/main/java/com/xcong/excoin/quartz/job/CoinTradeInitJob.java | 13 +
3 files changed, 456 insertions(+), 3 deletions(-)
diff --git a/src/main/java/com/xcong/excoin/modules/blackchain/service/TrxUsdtUpdateService.java b/src/main/java/com/xcong/excoin/modules/blackchain/service/TrxUsdtUpdateService.java
new file mode 100644
index 0000000..fbe30a5
--- /dev/null
+++ b/src/main/java/com/xcong/excoin/modules/blackchain/service/TrxUsdtUpdateService.java
@@ -0,0 +1,378 @@
+package com.xcong.excoin.modules.blackchain.service;
+
+import cn.hutool.core.math.MathUtil;
+import cn.hutool.http.HttpResponse;
+import cn.hutool.http.HttpUtil;
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.xcong.excoin.common.enumerates.CoinTypeEnum;
+import com.xcong.excoin.modules.blackchain.model.EthUsdtChargeDto;
+import com.xcong.excoin.modules.member.dao.MemberCoinAddressDao;
+import com.xcong.excoin.modules.member.entity.MemberCoinAddressEntity;
+import com.xcong.excoin.rabbit.producer.UsdtUpdateProducer;
+import com.xcong.excoin.utils.RedisUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.http.*;
+import org.springframework.http.client.SimpleClientHttpRequestFactory;
+import org.springframework.stereotype.Service;
+import org.springframework.web.client.RestTemplate;
+import org.tron.common.utils.ByteArray;
+import org.tron.walletserver.WalletApi;
+
+import javax.annotation.Resource;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.*;
+
+/**
+ * TRX TRC20服务类
+ */
+@Slf4j
+@Service
+public class TrxUsdtUpdateService {
+
+ public static List<String> addressList = new ArrayList<>();
+ private static String http = "https://api.trongrid.io";
+
+ private static String TRC20_CONTRACT_ADDRESS = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t";
+
+ /**
+ * 手续费
+ */
+ private final static BigDecimal TRX_FEE = new BigDecimal("10");
+
+ @Resource
+ private UsdtUpdateProducer usdtUpdateProducer;
+
+ @Resource
+ private MemberCoinAddressDao memberCoinAddressDao;
+
+ @Resource
+ RedisUtils redisUtils;
+
+ /**
+ * 扫块 同步充值USDT-TRC20和TRX
+ */
+ public void monitorCoinListener(Long blockNum) {
+ if (CollectionUtils.isEmpty(addressList)) {
+ List<MemberCoinAddressEntity> coinAddressList = memberCoinAddressDao.selectAllBlockAddressBySymbolAndTag(CoinTypeEnum.USDT.name(), "TRC20");
+ if (CollectionUtils.isNotEmpty(coinAddressList)) {
+ coinAddressList.forEach(e -> {
+ addressList.add(e.getAddress());
+ });
+ }
+ }
+ if (CollectionUtils.isEmpty(addressList)) {
+ return;
+ }
+
+
+ // 解析区块
+ httpTransactionInfo(addressList, blockNum);
+
+ }
+
+ /**
+ * 解析区块数据 同步用户充值
+ *
+ * @param addressList
+ * @param num
+ */
+ private void httpTransactionInfo(List<String> addressList, Long num) {
+ // 查询详情,包含了所有交易信息
+ String transactionInfoByBlockNum = getblockbynum(BigInteger.valueOf(num));
+ if (StringUtils.isBlank(transactionInfoByBlockNum)) {
+ return;
+ }
+// log.info("--->{}, {}", num, System.currentTimeMillis());
+ // 不用等到扫完再累加 只要进来就加 还有一个条件是必须查询出区块再加 否则当区块超过实际区块
+// redisUtils.set("USDT_TRC20_BLOCK_NUM", (num + 1L));
+ JSONArray parseArray = JSON.parseObject(transactionInfoByBlockNum).getJSONArray("transactions");
+ if (parseArray != null && parseArray.size() > 0) {
+ for (Object e : parseArray) {
+ try {
+// String txId = JSON.parseObject(e.toString()).getString("id");
+// String contract_address = JSON.parseObject(e.toString()).getString("contract_address");
+// if(!"41a614f803b6fd780986a42c78ec9c7f77e6ded13c".equals(contract_address)){
+// continue;
+// }
+ //判断 数据库 txId 有 就不用往下继续了
+ JSONObject parseObject = JSON.parseObject(e.toString());
+ String txId = parseObject.getString("txID");
+ String contractRet = parseObject.getJSONArray("ret").getJSONObject(0).getString("contractRet");
+ //交易成功
+ if ("SUCCESS".equals(contractRet)) {
+ String type = parseObject.getJSONObject("raw_data").getJSONArray("contract").getJSONObject(0).getString("type");
+ if ("TriggerSmartContract".equals(type)) {
+ //合约地址转账
+ triggerSmartContract(addressList, txId, parseObject);
+
+ } else if ("TransferContract".equals(type)) {
+ //trx 转账
+ //transferContract(parseObject);
+ }
+ }
+ } catch (Exception exception) {
+ exception.printStackTrace();
+ }
+ }
+ }
+ }
+
+
+ /**
+ * 比对本地地址 同步TRX充值
+ *
+ * @param parseObject
+ */
+ private void transferContract(JSONObject parseObject) {
+ //数量
+ BigDecimal amount = parseObject.getJSONObject("raw_data").getJSONArray("contract").getJSONObject(0).getJSONObject("parameter").getJSONObject("value").getBigDecimal("amount");
+
+ //调用者地址
+ String owner_address = parseObject.getJSONObject("raw_data").getJSONArray("contract").getJSONObject(0).getJSONObject("parameter").getJSONObject("value").getString("owner_address");
+ owner_address = WalletApi.encode58Check(ByteArray.fromHexString(owner_address));
+
+ //转入地址
+ String to_address = parseObject.getJSONObject("raw_data").getJSONArray("contract").getJSONObject(0).getJSONObject("parameter").getJSONObject("value").getString("to_address");
+ to_address = WalletApi.encode58Check(ByteArray.fromHexString(to_address));
+
+ amount = amount.divide(new BigDecimal(1 + TransformUtil.getSeqNumByLong(0L, 6)));
+
+ }
+
+ /**
+ * 获取特定区块的所有交易 Info 信息
+ *
+ * @param num 区块
+ * @return
+ */
+ public static String getTransactionInfoByBlockNum(BigInteger num) {
+ String url = http + "/wallet/gettransactioninfobyblocknum";
+ Map<String, Object> map = new HashMap<>();
+ map.put("num", num);
+ String param = JSON.toJSONString(map);
+ return postForEntity(url, param).getBody();
+ }
+
+ /**
+ * 获取特定区块的所有交易 Info 信息
+ *
+ * @param num 区块
+ * @return
+ */
+ public static String getblockbynum(BigInteger num) {
+ String url = http + "/wallet/getblockbynum";
+ Map<String, Object> map = new HashMap<>();
+ map.put("num", num);
+ String param = JSON.toJSONString(map);
+// return postForEntity(url, param).getBody();
+ return postForEntityHuTool(url, param).body();
+ }
+
+
+ /**
+ * https://cn.developers.tron.network/docs/%E4%BA%A4%E6%98%9311#%E4%BA%A4%E6%98%93%E7%A1%AE%E8%AE%A4%E6%96%B9%E6%B3%95
+ * 按交易哈希查询交易
+ *
+ * @param txId 交易id
+ * @return
+ */
+ public static String getTransactionById(String txId) {
+ // String url = walletSolidityHttp + "/walletsolidity/gettransactionbyid";
+ String url = http + "/wallet/gettransactionbyid";
+ Map<String, Object> map = new HashMap<>();
+ map.put("value", txId);
+ String param = JSON.toJSONString(map);
+ return postForEntity(url, param).getBody();
+ }
+
+ /**
+ * 执行 post 请求
+ *
+ * @param url url
+ * @param param 请求参数
+ * @return
+ */
+ private static ResponseEntity<String> postForEntity(String url, String param) {
+ SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
+ factory.setConnectTimeout(20000);
+ factory.setReadTimeout(20000);
+ RestTemplate restTemplate = new RestTemplate(factory);
+ HttpHeaders headers = new HttpHeaders();
+ headers.setContentType(MediaType.APPLICATION_JSON);
+ headers.set("TRON-PRO-API-KEY", Trc20Service.API_KEY);
+ HttpEntity<String> request = new HttpEntity<>(param, headers);
+ ResponseEntity<String> result = restTemplate.postForEntity(url, request, String.class);
+// System.out.println("url:" + url + ",param:" + param + ",result:" + result.getBody());
+ return result;
+ }
+
+ private static HttpResponse postForEntityHuTool(String url, String param) {
+ System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
+ return HttpUtil.createPost(url).body(param)
+ .timeout(20000).contentType("application/json")
+ .header("TRON-PRO-API-KEY", Trc20Service.API_KEY)
+ .execute();
+ }
+
+ /**
+ * 比对本地地址 同步充值USDT-TRC20
+ *
+ * @param addressList
+ * @param txId
+ * @param parseObject
+ */
+ private void triggerSmartContract(List<String> addressList, String txId, JSONObject parseObject) {
+ //方法参数
+ String data = parseObject.getJSONObject("raw_data").getJSONArray("contract").getJSONObject(0).getJSONObject("parameter").getJSONObject("value").getString("data");
+ // 调用者地址
+ String owner_address = parseObject.getJSONObject("raw_data").getJSONArray("contract").getJSONObject(0).getJSONObject("parameter").getJSONObject("value").getString("owner_address");
+ owner_address = WalletApi.encode58Check(ByteArray.fromHexString(owner_address));
+ //System.out.println("owner_address:"+owner_address);
+ // 合约地址
+ String contract_address = parseObject.getJSONObject("raw_data").getJSONArray("contract").getJSONObject(0).getJSONObject("parameter").getJSONObject("value").getString("contract_address");
+ contract_address = WalletApi.encode58Check(ByteArray.fromHexString(contract_address));
+
+ String dataStr = data.substring(8);
+ List<String> strList = TransformUtil.getStrList(dataStr, 64);
+ //System.out.println(strList);
+ if (strList.size() != 2) {
+ return;
+ }
+
+ String to_address = TransformUtil.delZeroForNum(strList.get(0));
+
+ if (!to_address.startsWith("41")) {
+ to_address = "41" + to_address;
+ }
+
+ to_address = WalletApi.encode58Check(ByteArray.fromHexString(to_address));
+ //System.out.println("to_address:"+to_address);
+ String amountStr = TransformUtil.delZeroForNum(strList.get(1));
+
+ if (amountStr.length() > 0) {
+ amountStr = new BigInteger(amountStr, 16).toString(10);
+ }
+
+ BigDecimal amount = BigDecimal.ZERO;
+ //相匹配的合约地址
+ if (!TRC20_CONTRACT_ADDRESS.equals(contract_address)) {
+ return;
+ }
+
+ //币种
+ if (StringUtils.isNotEmpty(amountStr)) {
+ amount = new BigDecimal(amountStr).divide(new BigDecimal(1 + TransformUtil.getSeqNumByLong(0L, 6)));
+ }
+ for (String address : addressList) {
+ if (address.equals(to_address)) {
+ log.info("存在本地的地址:" + address);
+ // 金额
+ // 发送消息队列
+ EthUsdtChargeDto dto = new EthUsdtChargeDto(address, txId, amount);
+ dto.setSymbol(EthUsdtChargeDto.Symbol.USDT_TRC20);
+ usdtUpdateProducer.sendMsg(JSONObject.toJSONString(dto));
+ log.info("===to_address:" + to_address + "===amount:" + amount);
+ }
+ }
+
+ }
+
+ /**
+ * 根据地址归集USDT-TRC20
+ *
+ * @param address
+ * @return
+ */
+ public boolean poolByAddress(String address) {
+ // 首先查询trx余额
+ BigDecimal trxBalance = Trc20Service.getTrxBalance(address);
+ if (trxBalance == null) {
+ return false;
+ }
+ if (trxBalance.compareTo(TRX_FEE) >= 0) {
+ // 转
+ BigDecimal trc20Balance = Trc20Service.getTrc20Balance(address);
+ if (trc20Balance == null) {
+ return false;
+ }
+ MemberCoinAddressEntity coinAddressEntity = memberCoinAddressDao.selectCoinAddressByAddressAndSymbolTag(address, "USDT", "TRC20");
+ if (coinAddressEntity == null) {
+ return false;
+ }
+ Trc20Service.sendTrc20(coinAddressEntity.getPrivateKey(), Trc20Service.POOL_ADDRESS, trc20Balance);
+ // 需要将存在redis的待归集地址删除
+ Object trc20_pool = redisUtils.get("TRC20_POOL");
+ if (trc20_pool != null) {
+ List<String> poolList = (List) trc20_pool;
+ Iterator<String> iterator = poolList.iterator();
+ while (iterator.hasNext()) {
+ String next = iterator.next();
+ if (address.equals(next)) {
+ iterator.remove();
+ }
+ }
+ if (CollectionUtils.isEmpty(poolList)) {
+ redisUtils.del("TRC20_POOL");
+ } else {
+ redisUtils.set("TRC20_POOL", poolList);
+ }
+ }
+ return true;
+ } else {
+ Trc20Service.sendTrx(Trc20Service.TRX_PRIVATE_KEY, address, TRX_FEE);
+ // 将这个地址记录,后续同步
+ Object trc20_pool = redisUtils.get("TRC20_POOL");
+ List<String> poolList = new ArrayList<>();
+ if (trc20_pool != null) {
+ poolList = (List) trc20_pool;
+ }
+ poolList.add(address);
+ redisUtils.set("TRC20_POOL", poolList);
+ return true;
+ }
+ }
+
+ // https://api.trongrid.io/wallet/getnowblock
+
+ /**
+ * 获取最新区块
+ *
+ * @return
+ */
+ public long getnowblock() {
+ String url = http + "/wallet/getnowblock";
+ RestTemplate restTemplate = new RestTemplate();
+ HttpHeaders headers = new HttpHeaders();
+ headers.setContentType(MediaType.APPLICATION_JSON);
+ headers.set("TRON-PRO-API-KEY", Trc20Service.API_KEY);
+ HttpEntity<String> request = new HttpEntity<>(headers);
+ ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
+ String forObject = exchange.getBody();
+ //System.out.println(forObject);
+ // String forObject = restTemplate.getForObject(url, String.class);
+ String number = JSON.parseObject(forObject).getJSONObject("block_header").getJSONObject("raw_data").getString("number");
+ return Long.valueOf(number);
+ }
+
+ /**
+ * 从tronscan.io查询最新区块
+ * {"whole_block_count":29625671,"whole_pay":3392835760,"last_day_pay":460432,"last_day_block_count":28777}
+ * @return
+ */
+ public Long getnowblockFromTronScan() {
+ String roundNum = Math.random() + "";
+ String url = "https://apiasia.tronscan.io:5566/api/block/statistic?randomNum=" + roundNum;
+ SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
+ factory.setConnectTimeout(20000);
+ factory.setReadTimeout(20000);
+ RestTemplate restTemplate = new RestTemplate(factory);
+ String forObject = restTemplate.getForObject(url, String.class);
+ String wholeBlockCount = JSON.parseObject(forObject).getString("whole_block_count");
+ return Long.valueOf(wholeBlockCount);
+ }
+}
diff --git a/src/main/java/com/xcong/excoin/quartz/job/BlockCoinUpdateJob.java b/src/main/java/com/xcong/excoin/quartz/job/BlockCoinUpdateJob.java
index f91418b..9be6d3d 100644
--- a/src/main/java/com/xcong/excoin/quartz/job/BlockCoinUpdateJob.java
+++ b/src/main/java/com/xcong/excoin/quartz/job/BlockCoinUpdateJob.java
@@ -1,11 +1,14 @@
package com.xcong.excoin.quartz.job;
import com.xcong.excoin.modules.coin.service.BlockCoinService;
+import com.xcong.excoin.utils.RedisUtils;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
+import java.util.concurrent.ConcurrentLinkedQueue;
/**
* 链上币种同步任务
@@ -19,6 +22,65 @@
@Resource
private BlockCoinService blockCoinService;
+
+ @Autowired
+ private RedisUtils redisUtils;
+
+ private
+
+
+ public static ConcurrentLinkedQueue<Long> TRC_BLOCK = new ConcurrentLinkedQueue<>();
+
+ /**
+ * TRC20_USDT 同步
+ */
+ @Scheduled(cron = "0/2 * * * * ? ")
+// @Async
+ public void usdtTc20Update() {
+ // 波场3秒出一个块
+ Long blocnNum = TRC_BLOCK.poll();
+ if (blocnNum == null) {
+ return;
+ }
+ usdtUpdateProducer.sendTrc20BlockMsg(blocnNum.toString());
+ redisUtils.set("USDT_TRC20_CURRENT_BLOCK_NUM", blocnNum);
+// try {
+// trxUsdtUpdateService.monitorCoinListener(blocnNum);
+// } catch (RestClientException | HttpException e) {
+// // 此时是连接问题 这个块需要重新扫描
+// log.info("查询区块超时:" + blocnNum);
+// TRC_BLOCK.add(blocnNum);
+// } catch (Exception e) {
+// e.printStackTrace();
+// }
+
+ }
+
+ @Scheduled(cron = "0 0/1 * * * ? ")
+ public void usdtTc20UpdateQueue() {
+ // 查询最新区块号
+ long getnowblock = trxUsdtUpdateService.getnowblockFromTronScan() - 25;
+ // 拿到redis里最新区块
+ Object trc20BlockNum = redisUtils.get("USDT_TRC20_BLOCK_NUM");
+ if (trc20BlockNum == null) {
+ // 没有则取最新的块
+ trc20BlockNum = getnowblock;
+ redisUtils.set("USDT_TRC20_BLOCK_NUM", getnowblock);
+ }
+ Long blockNum = Long.valueOf(trc20BlockNum.toString());
+ if (getnowblock <= blockNum) {
+ // 如果当前区块比最新已确认区块还大,则不继续执行
+ return;
+ }
+ // 得到最新区块和当前区块的差值
+ Long diff = getnowblock-blockNum;
+ for(long i=1;i<=diff;i++){
+ blockNum++;
+ TRC_BLOCK.add(blockNum);
+ }
+ // 将最新的最大区块放入redis
+ redisUtils.set("USDT_TRC20_BLOCK_NUM", blockNum);
+ }
/**
@@ -45,17 +107,17 @@
blockCoinService.updateBtcUsdt();
}
- @Scheduled(cron = "0 3/20 * * * ? ")
+// @Scheduled(cron = "0 3/20 * * * ? ")
public void btcUpdate() {
blockCoinService.updateBtc();
}
- @Scheduled(cron = "0 4/20 * * * ? ")
+// @Scheduled(cron = "0 4/20 * * * ? ")
public void eosUpdate() {
blockCoinService.updateEos();
}
- @Scheduled(cron = "0 6/20 * * * ? ")
+// @Scheduled(cron = "0 6/20 * * * ? ")
public void xrpUpdate() {
blockCoinService.updateXrp();
}
diff --git a/src/main/java/com/xcong/excoin/quartz/job/CoinTradeInitJob.java b/src/main/java/com/xcong/excoin/quartz/job/CoinTradeInitJob.java
index a72ee84..58fd0fa 100644
--- a/src/main/java/com/xcong/excoin/quartz/job/CoinTradeInitJob.java
+++ b/src/main/java/com/xcong/excoin/quartz/job/CoinTradeInitJob.java
@@ -33,6 +33,7 @@
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -124,6 +125,18 @@
if(o!=null){
Map<String, Candlestick> currentKlineMap = (Map<String, Candlestick> )o;
((DefaultCoinProcessor) processor).setCurrentKlineMap(currentKlineMap);
+ }else{
+ // 当最新K线不存在时 需要初始化
+ // 1min 5min 15min 30min 1hour 4hour 1day 1week
+ String[] rang = {"1min","5min","15min","30min","1hour","4hour","1day","1week"};
+ Map<String, Candlestick> currentKlineMap = new HashMap<>();
+ long currentTimeMillis = System.currentTimeMillis();
+ for (String s : rang) {
+ Candlestick candlestick = new Candlestick();
+ candlestick.setTimestamp(currentTimeMillis);
+ currentKlineMap.put(s,candlestick);
+ }
+ redisUtils.set(key,currentKlineMap);
}
processorFactory.addProcessor(symbol, processor);
--
Gitblit v1.9.1