442 lines
23 KiB
Java
442 lines
23 KiB
Java
package com.ruoyi.system.rental;
|
|
|
|
import com.fasterxml.jackson.databind.JsonNode;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import okhttp3.*;
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
import org.springframework.stereotype.Service;
|
|
import org.tron.trident.core.ApiWrapper;
|
|
|
|
import java.math.BigDecimal;
|
|
import java.util.Locale;
|
|
import java.util.Map;
|
|
import java.util.concurrent.TimeUnit;
|
|
|
|
import static com.ruoyi.system.rental.RentalValues.*;
|
|
|
|
/**
|
|
* 云端只读链上适配器,不持有私钥且不调用广播接口。 普通TRON RPC不提供任意历史资源状态;确认区块资源证明必须来自配置的受信历史节点。
|
|
* 缺少历史证据时保留真实交易与资金占位,禁止用当前参数冒充历史交付成功。
|
|
*/
|
|
@Slf4j
|
|
@Service
|
|
public class RentalChain {
|
|
@Value("${rental.rpc.nile:https://nile.trongrid.io}")
|
|
private String nile;
|
|
|
|
@Value("${rental.rpc.mainnet:https://api.trongrid.io}")
|
|
private String mainnet;
|
|
|
|
@Value("${rental.history.nile:}")
|
|
private String nileHistory;
|
|
|
|
@Value("${rental.history.mainnet:}")
|
|
private String mainHistory;
|
|
|
|
@Value("${rental.history.embedded-enabled:false}")
|
|
private boolean embeddedHistory;
|
|
|
|
// 延迟获取内置历史服务,避免历史采集复用本只读RPC适配器时发生构造循环依赖。
|
|
@org.springframework.beans.factory.annotation.Autowired
|
|
private org.springframework.beans.factory.ObjectProvider<RentalHistoryService> historyService;
|
|
|
|
@Value("${rental.rpc.api-key:}")
|
|
private String apiKey;
|
|
|
|
@Value("${rental.confirmations:19}")
|
|
private long confirmations;
|
|
|
|
private final ObjectMapper json;
|
|
|
|
@org.springframework.beans.factory.annotation.Autowired
|
|
private com.ruoyi.system.service.TronServiceProvider tronServices;
|
|
|
|
private final OkHttpClient client =
|
|
new OkHttpClient.Builder()
|
|
.connectTimeout(5, TimeUnit.SECONDS)
|
|
.readTimeout(8, TimeUnit.SECONDS)
|
|
.callTimeout(12, TimeUnit.SECONDS)
|
|
.retryOnConnectionFailure(false)
|
|
.build();
|
|
|
|
public RentalChain(ObjectMapper json) {
|
|
this.json = json;
|
|
}
|
|
|
|
public JsonNode call(String network, String path, Map<String, Object> body) {
|
|
return request("NILE".equals(network(network)) ? nile : mainnet, path, body);
|
|
}
|
|
|
|
private JsonNode request(String base, String path, Map<String, Object> body) {
|
|
try {
|
|
Request request =
|
|
new Request.Builder()
|
|
.url(base + path)
|
|
.header("TRON-PRO-API-KEY", apiKey)
|
|
.post(
|
|
RequestBody.create(
|
|
MediaType.parse("application/json"),
|
|
json.writeValueAsString(body)))
|
|
.build();
|
|
try (Response response = client.newCall(request).execute()) {
|
|
boolean fullBlock = path.endsWith("/getnowblock") || path.endsWith("/getblockbynum")
|
|
|| path.endsWith("/gettransactioninfobyblocknum");
|
|
return json.readTree(RentalHttp.body(response,
|
|
(fullBlock ? 16 : 1) * 1024 * 1024));
|
|
}
|
|
} catch (Exception ex) {
|
|
log.error(ex.getMessage(), ex);
|
|
throw new IllegalStateException("链上查询失败,保留原业务状态 " + base + path);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 地址激活以所选网络最新全节点账户记录为准,不能用余额是否为零判断。
|
|
* 仅TRON getaccount返回空对象表示未激活;错误/异常结构视为未知,禁止继续冻结资金。
|
|
*/
|
|
public void requireUnactivated(String network, String address) {
|
|
network(network);
|
|
RentalOrders.address(address);
|
|
log.info("地址上链激活检查开始 network={} receiver={}", network, address);
|
|
JsonNode account = call(network, "/wallet/getaccount", map("address", address, "visible", true));
|
|
require(account != null && account.isObject(), "地址激活状态查询异常,请稍后重试");
|
|
if (account.size() == 0) {
|
|
log.info("地址上链激活检查通过 network={} receiver={} activated=false", network, address);
|
|
return;
|
|
}
|
|
String returnedAddress = account.path("address").asText();
|
|
require(address.equals(returnedAddress)
|
|
|| ApiWrapper.toHex(ApiWrapper.parseAddress(address)).equalsIgnoreCase(returnedAddress),
|
|
"地址激活状态响应不完整或不一致,请稍后重试");
|
|
log.warn("地址上链创建被拒绝 network={} receiver={} activated=true", network, address);
|
|
throw new IllegalArgumentException("该地址在当前网络已激活,无需地址上链,不允许创建订单");
|
|
}
|
|
|
|
private long block(JsonNode row) {
|
|
return row.path("block_header").path("raw_data").path("number").asLong(-1);
|
|
}
|
|
|
|
public Map<String, Object> snapshot(String network, String address) {
|
|
JsonNode beforeBlock = call(network, "/wallet/getnowblock", map());
|
|
long before = block(beforeBlock);
|
|
JsonNode resources =
|
|
call(
|
|
network,
|
|
"/wallet/getaccountresource",
|
|
map("address", address, "visible", true));
|
|
long energy = delegatable(network, address, 1);
|
|
long bandwidth = delegatable(network, address, 0);
|
|
JsonNode afterBlock = call(network, "/wallet/getnowblock", map());
|
|
long after = block(afterBlock);
|
|
require(
|
|
before >= 0 && before == after && energy >= 0 && bandwidth >= 0
|
|
&& beforeBlock.path("blockID").asText().matches("[0-9a-fA-F]{64}")
|
|
&& beforeBlock.path("blockID").asText().equalsIgnoreCase(afterBlock.path("blockID").asText()),
|
|
"快照跨区块或本金查询不完整,请重试");
|
|
Map<String, Object> result =
|
|
map(
|
|
"snapshot_block_height",
|
|
after,
|
|
"energy_delegatable_sun",
|
|
energy,
|
|
"bandwidth_delegatable_sun",
|
|
bandwidth,
|
|
"energy_available",
|
|
Math.max(
|
|
0,
|
|
resources.path("EnergyLimit").asLong()
|
|
- resources.path("EnergyUsed").asLong()),
|
|
"bandwidth_available",
|
|
Math.max(
|
|
0,
|
|
resources.path("NetLimit").asLong()
|
|
- resources.path("NetUsed").asLong()),
|
|
"total_energy_limit",
|
|
resources.path("TotalEnergyLimit").asLong(),
|
|
"total_energy_weight",
|
|
resources.path("TotalEnergyWeight").asLong(),
|
|
"total_bandwidth_limit",
|
|
resources.path("TotalNetLimit").asLong(),
|
|
"total_bandwidth_weight",
|
|
resources.path("TotalNetWeight").asLong(),
|
|
"snapshot_at",
|
|
now(),
|
|
"snapshot_expires_at",
|
|
after(15));
|
|
require(
|
|
number(result, "total_energy_limit") > 0
|
|
&& number(result, "total_energy_weight") > 0
|
|
&& number(result, "total_bandwidth_limit") > 0
|
|
&& number(result, "total_bandwidth_weight") > 0,
|
|
"全网参数不完整");
|
|
if (embeddedHistory && historyService != null) {
|
|
// 复用本次夹读,不再为每个订单额外请求全网资源参数;不读取旧rent_wallet快照。
|
|
try {
|
|
historyService.getObject().offerParameters(network, beforeBlock, afterBlock, resources);
|
|
} catch (RuntimeException ex) {
|
|
log.warn("钱包全局参数采样未入库 network={},独立采样器将继续重试", network);
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
/** protobuf省略零字段的空对象表示0;显式错误和非整数绝不能当作0。 */
|
|
private long delegatable(String network, String address, int type) {
|
|
JsonNode row = call(network, "/wallet/getcandelegatedmaxsize",
|
|
map("owner_address", address, "type", type, "visible", true));
|
|
require(row.isObject() && (row.size() == 0 || row.has("max_size"))
|
|
&& !row.has("Error") && !row.has("error") && !row.has("code") && !row.has("result"),
|
|
"可代理本金查询失败");
|
|
JsonNode value = row.path("max_size");
|
|
require(value.isMissingNode() || (value.isIntegralNumber() && value.canConvertToLong()
|
|
&& value.longValue() >= 0), "可代理本金响应无效");
|
|
return value.isMissingNode() ? 0 : value.longValue();
|
|
}
|
|
|
|
public long relation(String network, String owner, String receiver, String resource) {
|
|
JsonNode rows =
|
|
call(
|
|
network,
|
|
"/wallet/getdelegatedresourcev2",
|
|
map("fromAddress", owner, "toAddress", receiver, "visible", true))
|
|
.path("delegatedResource");
|
|
long total = 0;
|
|
for (JsonNode row : rows) {
|
|
total =
|
|
Math.addExact(
|
|
total,
|
|
row.path(
|
|
"ENERGY".equals(resource)
|
|
? "frozen_balance_for_energy"
|
|
: "frozen_balance_for_bandwidth")
|
|
.asLong());
|
|
}
|
|
return total;
|
|
}
|
|
|
|
/**
|
|
* 内置历史模式在派单前建立确认关系基线,RPC失败时继续等待派单,不先广播再补基线。
|
|
*/
|
|
public void prepareHistory(String network, String owner, String receiver, String resource) {
|
|
if (embeddedHistory) {
|
|
historyService.getObject().anchor(network, owner, receiver, resource);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 返回CONFIRMED仅代表交易真实成功;历史资源证据不足时delivery_proven=false。
|
|
*/
|
|
public Map<String, Object> verify(
|
|
Map<String, Object> task, String txId, String owner, String receiver) {
|
|
require(txId.matches("[0-9a-fA-F]{64}"), "交易哈希无效");
|
|
String network = text(task, "network");
|
|
JsonNode tx = call(network, "/wallet/gettransactionbyid", map("value", txId));
|
|
JsonNode receipt =
|
|
call(network, "/walletsolidity/gettransactioninfobyid", map("value", txId));
|
|
require(
|
|
txId.equalsIgnoreCase(tx.path("txID").asText()) && receipt.has("blockNumber"),
|
|
"交易尚未确认,不能判定未执行");
|
|
long height = receipt.path("blockNumber").asLong();
|
|
long head = block(call(network, "/walletsolidity/getnowblock", map()));
|
|
require(head - height + 1 >= confirmations, "确认深度不足");
|
|
JsonNode contracts = tx.path("raw_data").path("contract");
|
|
require(contracts.size() == 1, "交易合约数量异常");
|
|
JsonNode contract = contracts.get(0);
|
|
JsonNode value = contract.path("parameter").path("value");
|
|
if (RentalOnchain.TASK_TYPE.equals(text(task, "task_type"))) {
|
|
return verifyOnchain(task, tx, receipt, contract, value, owner, receiver, height);
|
|
}
|
|
String expected =
|
|
"DELEGATE".equals(text(task, "task_type"))
|
|
? "DelegateResourceContract"
|
|
: "UnDelegateResourceContract";
|
|
require(
|
|
expected.equals(contract.path("type").asText())
|
|
&& !value.path("lock").asBoolean(false)
|
|
&& contract.path("Permission_id").asInt(0) == 0
|
|
&& hexAddress(owner).equalsIgnoreCase(value.path("owner_address").asText())
|
|
&& hexAddress(receiver)
|
|
.equalsIgnoreCase(value.path("receiver_address").asText())
|
|
&& number(task, "delegate_sun") == value.path("balance").asLong()
|
|
&& text(task, "resource_type")
|
|
.equals(value.path("resource").asText("BANDWIDTH")),
|
|
"链上交易参数与任务意图不符");
|
|
require(tx.path("ret").size() == 1, "缺少执行回执");
|
|
if (!"SUCCESS".equals(tx.path("ret").get(0).path("contractRet").asText())) {
|
|
return map("status", "FAILED");
|
|
}
|
|
long after = relation(network, owner, receiver, text(task, "resource_type"));
|
|
boolean delegate = "DELEGATE".equals(text(task, "task_type"));
|
|
require(after == (delegate ? number(task, "delegate_sun") : 0), "当前地址对关系与原委托本金不符,需要人工核对");
|
|
Map<String, Object> result =
|
|
map(
|
|
"status",
|
|
"CONFIRMED",
|
|
"block_height",
|
|
height,
|
|
"block_time",
|
|
java.time.LocalDateTime.ofInstant(
|
|
java.time.Instant.ofEpochMilli(
|
|
receipt.path("blockTimeStamp").asLong()),
|
|
java.time.ZoneOffset.UTC),
|
|
"after_sun",
|
|
after,
|
|
"delivery_proven",
|
|
!delegate);
|
|
String history = "NILE".equals(network) ? nileHistory : mainHistory;
|
|
if (delegate && (embeddedHistory || !history.isEmpty())) {
|
|
JsonNode proof;
|
|
if (embeddedHistory) {
|
|
Map<String, Object> archived = historyService.getObject().proof(
|
|
network, txId, height, owner, receiver, text(task, "resource_type"));
|
|
if (archived == null) {
|
|
result.put("delivery_evidence_gap", historyService.getObject().missingProofCode(
|
|
network, height, owner, receiver, text(task, "resource_type")));
|
|
// 参数漏采或缺少派单前基线:保留原有MANUAL_REVIEW路径,绝不降级为当前快照。
|
|
return result;
|
|
}
|
|
proof = json.valueToTree(archived);
|
|
} else {
|
|
proof = request(
|
|
history,
|
|
"/rental/resource-proof",
|
|
map(
|
|
"network",
|
|
network,
|
|
"tx_id",
|
|
txId,
|
|
"block_height",
|
|
height,
|
|
"owner",
|
|
owner,
|
|
"receiver",
|
|
receiver,
|
|
"resource_type",
|
|
text(task, "resource_type")));
|
|
}
|
|
require(
|
|
height == proof.path("block_height").asLong(-1)
|
|
&& txId.equalsIgnoreCase(proof.path("tx_id").asText())
|
|
&& proof.path("baseline_sun").asLong(-1) == 0
|
|
&& proof.path("after_sun").asLong(-1) == number(task, "delegate_sun"),
|
|
"历史关系证据不匹配");
|
|
long limit = proof.path("total_limit").asLong(),
|
|
weight = proof.path("total_weight").asLong();
|
|
result.put("verified_total_limit", limit);
|
|
result.put("verified_total_weight", weight);
|
|
// 完整历史证明写入交易evidence JSON,保留区块哈希、基线高度和数据来源供审计。
|
|
result.put("history_proof", json.convertValue(proof, Map.class));
|
|
result.put(
|
|
"verified_resource_quantity",
|
|
quantity(number(task, "delegate_sun"), limit, weight));
|
|
result.put("delivery_proven", true);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
private String hexAddress(String address) {
|
|
return ApiWrapper.toHex(ApiWrapper.parseAddress(address));
|
|
}
|
|
|
|
/** 不信任节点 RESULT:在指定网络独立核对原生单合约、owner、to、固定金额及确认回执。 */
|
|
private Map<String, Object> verifyOnchain(Map<String, Object> task, JsonNode tx, JsonNode receipt,
|
|
JsonNode contract, JsonNode value, String owner, String receiver, long height) {
|
|
long timestamp = tx.path("raw_data").path("timestamp").asLong(-1);
|
|
require(tx.path("txID").asText().equalsIgnoreCase(receipt.path("id").asText())
|
|
&& timestamp >= time(task.get("signed_at")).toEpochMilli() - 5000
|
|
&& timestamp <= time(task.get("deadline")).toEpochMilli(),
|
|
"转账不在任务授权时间内或回执哈希不符,保留冻结核对");
|
|
require("TransferContract".equals(contract.path("type").asText())
|
|
&& contract.path("Permission_id").asInt(0) == 0
|
|
&& hexAddress(owner).equalsIgnoreCase(value.path("owner_address").asText())
|
|
&& hexAddress(receiver).equalsIgnoreCase(value.path("to_address").asText())
|
|
&& value.path("amount").asLong(-1) == RentalOnchain.TRANSFER_SUN
|
|
&& number(task, "delegate_sun") == RentalOnchain.TRANSFER_SUN
|
|
&& "TRX".equals(text(task, "resource_type")), "链上转账与固定1TRX任务不符");
|
|
require(tx.path("ret").size() == 1 && receipt.path("blockTimeStamp").asLong() > 0,
|
|
"转账执行回执缺失,保留冻结资金");
|
|
if (!"SUCCESS".equals(tx.path("ret").get(0).path("contractRet").asText())) {
|
|
return map("status", "FAILED");
|
|
}
|
|
require(!"FAILED".equals(receipt.path("result").asText()), "回执状态冲突,需人工核对");
|
|
log.info("地址上链证明通过 taskId={} network={} txId={} blockHeight={} transferSun={}",
|
|
task.get("id"), task.get("network"), tx.path("txID").asText(), height, RentalOnchain.TRANSFER_SUN);
|
|
return map("status", "CONFIRMED", "block_height", height, "block_time",
|
|
java.time.LocalDateTime.ofInstant(java.time.Instant.ofEpochMilli(receipt.path("blockTimeStamp").asLong()),
|
|
java.time.ZoneOffset.UTC));
|
|
}
|
|
|
|
/** 自动充值定位唯一匹配日志;不信任支付平台传入的日志索引,兼用人工充值去重键。 */
|
|
public Map<String, Object> paymentTransfer(String network, String txId, String address,
|
|
BigDecimal expected, long createdAt, long expiresAt) {
|
|
require(txId.matches("[0-9a-fA-F]{64}"), "支付交易哈希无效");
|
|
JsonNode receipt = call(network, "/walletsolidity/gettransactioninfobyid", map("value", txId));
|
|
long timestamp = receipt.path("blockTimeStamp").asLong(-1);
|
|
require(timestamp >= createdAt - 5000 && timestamp <= expiresAt, "支付交易不在订单有效期内");
|
|
JsonNode logs = receipt.path("log");
|
|
require(logs.isArray() && logs.size() <= 512, "支付交易日志缺失或过多");
|
|
int selected = -1;
|
|
String contract = hexAddress(tronServices.getServiceForNetwork(network).contractAddress()).substring(2);
|
|
for (int index = 0; index < logs.size(); index++) {
|
|
JsonNode entry = logs.get(index);
|
|
if (contract.equalsIgnoreCase(entry.path("address").asText())
|
|
&& entry.path("topics").size() == 3
|
|
&& "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef".equalsIgnoreCase(entry.path("topics").get(0).asText())
|
|
&& entry.path("topics").get(2).asText().toLowerCase(Locale.ROOT).endsWith(hexAddress(address).substring(2).toLowerCase(Locale.ROOT))
|
|
&& new BigDecimal(new java.math.BigInteger(entry.path("data").asText(), 16)).movePointLeft(6).compareTo(expected) == 0) {
|
|
require(selected < 0, "同交易存在多笔匹配充值,需要人工核对");
|
|
selected = index;
|
|
}
|
|
}
|
|
require(selected >= 0, "未找到匹配的USDT充值日志");
|
|
Map<String, Object> result = transfer(network, txId, selected, address, expected);
|
|
result.put("log_index", selected);
|
|
return result;
|
|
}
|
|
|
|
/**
|
|
* 人工充值/付款依据必须由配置网络的USDT Transfer日志独立核对。
|
|
*/
|
|
public Map<String, Object> transfer(
|
|
String network, String txId, int index, String to, BigDecimal expected) {
|
|
network(network);
|
|
RentalOrders.address(to);
|
|
require(index >= 0 && txId.matches("[0-9a-fA-F]{64}"), "付款凭据无效");
|
|
JsonNode receipt =
|
|
call(network, "/walletsolidity/gettransactioninfobyid", map("value", txId));
|
|
require(
|
|
receipt.has("blockNumber")
|
|
&& block(call(network, "/walletsolidity/getnowblock", map()))
|
|
- receipt.path("blockNumber").asLong()
|
|
+ 1
|
|
>= confirmations
|
|
&& receipt.path("log").size() > index,
|
|
"付款未确认或日志不存在");
|
|
JsonNode log = receipt.path("log").get(index);
|
|
String contract = tronServices.getServiceForNetwork(network).contractAddress();
|
|
require(
|
|
hexAddress(contract).substring(2).equalsIgnoreCase(log.path("address").asText())
|
|
&& log.path("topics").size() == 3
|
|
&& "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
|
|
.equalsIgnoreCase(log.path("topics").get(0).asText())
|
|
&& log.path("topics")
|
|
.get(2)
|
|
.asText()
|
|
.endsWith(hexAddress(to).substring(2).toLowerCase(Locale.ROOT))
|
|
&& new BigDecimal(new java.math.BigInteger(log.path("data").asText(), 16))
|
|
.movePointLeft(6)
|
|
.compareTo(expected)
|
|
== 0
|
|
&& !"FAILED".equals(receipt.path("result").asText())
|
|
&& "SUCCESS"
|
|
.equals(receipt.path("receipt").path("result").asText("SUCCESS")),
|
|
"USDT付款日志不匹配");
|
|
return map(
|
|
"reference",
|
|
network + ":" + txId.toLowerCase(Locale.ROOT) + ":" + index,
|
|
"receipt",
|
|
receipt);
|
|
}
|
|
}
|