代理租赁实现
This commit is contained in:
1 parent
1c0544afe0
commit
2a9f1c4c7c
38 files changed
+5824
-6
No files matched your search
@@ -0,0 +1,308 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
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.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 云端只读链上适配器,不持有私钥且不调用广播接口。 普通TRON RPC不提供任意历史资源状态;确认区块资源证明必须来自配置的受信历史节点。
|
||||
* 缺少历史证据时保留真实交易与资金占位,禁止用当前参数冒充历史交付成功。
|
||||
*/
|
||||
@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.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()) {
|
||||
return json.readTree(RentalHttp.body(response));
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalStateException("链上查询失败,保留原业务状态");
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
long before = block(call(network, "/wallet/getnowblock", map()));
|
||||
JsonNode resources =
|
||||
call(
|
||||
network,
|
||||
"/wallet/getaccountresource",
|
||||
map("address", address, "visible", true));
|
||||
long energy =
|
||||
call(
|
||||
network,
|
||||
"/wallet/getcandelegatedmaxsize",
|
||||
map("owner_address", address, "type", 1, "visible", true))
|
||||
.path("max_size")
|
||||
.asLong(-1);
|
||||
long bandwidth =
|
||||
call(
|
||||
network,
|
||||
"/wallet/getcandelegatedmaxsize",
|
||||
map("owner_address", address, "type", 0, "visible", true))
|
||||
.path("max_size")
|
||||
.asLong(-1);
|
||||
long after = block(call(network, "/wallet/getnowblock", map()));
|
||||
require(
|
||||
before >= 0 && before == after && energy >= 0 && bandwidth >= 0,
|
||||
"快照跨区块或本金查询不完整,请重试");
|
||||
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,
|
||||
"全网参数不完整");
|
||||
return result;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/** 返回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");
|
||||
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 && !history.isEmpty()) {
|
||||
JsonNode 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);
|
||||
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));
|
||||
}
|
||||
|
||||
/** 人工充值/付款依据必须由配置网络的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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user