代理租赁实现
This commit is contained in:
1 parent
1c0544afe0
commit
2a9f1c4c7c
38 files changed
+5824
-6
No files matched your search
@@ -33,7 +33,7 @@ public class RentCredential extends BaseEntity
|
||||
private String apiKey;
|
||||
|
||||
/** AES-GCM加密封装的API Secret,含IV和tag;禁止返回或记录明文 */
|
||||
@Excel(name = "AES-GCM加密封装的API Secret,含IV和tag;禁止返回或记录明文")
|
||||
@com.fasterxml.jackson.annotation.JsonIgnore
|
||||
private String apiSecret;
|
||||
|
||||
/** 外部AES主密钥版本,不存主密钥 */
|
||||
@@ -184,7 +184,6 @@ public class RentCredential extends BaseEntity
|
||||
.append("ownerType", getOwnerType())
|
||||
.append("ownerId", getOwnerId())
|
||||
.append("apiKey", getApiKey())
|
||||
.append("apiSecret", getApiSecret())
|
||||
.append("masterKeyVersion", getMasterKeyVersion())
|
||||
.append("status", getStatus())
|
||||
.append("expiresAt", getExpiresAt())
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/** 商户HTTPS API,仅接受JSON POST;HMAC覆盖实际UTF-8请求体,禁止二次序列化验签。 */
|
||||
@RestController
|
||||
@RequestMapping("/api/rental/v1")
|
||||
public class RentalApiController {
|
||||
private final RentalIdentity identity;
|
||||
private final RentalStore store;
|
||||
private final RentalOrders orders;
|
||||
private final ObjectMapper json;
|
||||
|
||||
public RentalApiController(
|
||||
RentalIdentity identity, RentalStore store, RentalOrders orders, ObjectMapper json) {
|
||||
this.identity = identity;
|
||||
this.store = store;
|
||||
this.orders = orders;
|
||||
this.json = json;
|
||||
}
|
||||
|
||||
@PostMapping(value = "/{operation}", consumes = "application/json")
|
||||
public AjaxResult execute(@PathVariable String operation, HttpServletRequest request)
|
||||
throws Exception {
|
||||
require(
|
||||
Arrays.asList("create", "query", "packages").contains(operation)
|
||||
&& request.getQueryString() == null,
|
||||
"接口或查询参数不支持");
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[4096];
|
||||
int size;
|
||||
while ((size = request.getInputStream().read(buffer)) != -1) {
|
||||
require(output.size() + size <= 65536, "请求体超过64KiB");
|
||||
output.write(buffer, 0, size);
|
||||
}
|
||||
String body =
|
||||
StandardCharsets.UTF_8
|
||||
.newDecoder()
|
||||
.onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
|
||||
.decode(java.nio.ByteBuffer.wrap(output.toByteArray()))
|
||||
.toString();
|
||||
RentalJson.bounded(body);
|
||||
Map<String, Object> credential =
|
||||
identity.authenticate(
|
||||
request.getHeader("X-Rent-Key"),
|
||||
"APP",
|
||||
"API",
|
||||
Long.parseLong(request.getHeader("X-Rent-Timestamp")),
|
||||
request.getHeader("X-Rent-Nonce"),
|
||||
"POST",
|
||||
request.getRequestURI(),
|
||||
body,
|
||||
request.getHeader("X-Rent-Signature"));
|
||||
Map<String, Object> app = store.get("app", number(credential, "owner_id"), false);
|
||||
require("ACTIVE".equals(text(app, "status")), "应用已禁用");
|
||||
Map<String, Object> data =
|
||||
json.readValue(body, new TypeReference<Map<String, Object>>() {});
|
||||
if ("packages".equals(operation)) {
|
||||
List<Map<String, Object>> products =
|
||||
store.rows(
|
||||
"SELECT"
|
||||
+ " id,package_code,revision,name,network,resource_type,resource_quantity,duration_seconds,sale_amount"
|
||||
+ " FROM rent_package WHERE status='ACTIVE' AND network=? ORDER BY"
|
||||
+ " id",
|
||||
network(input(data, "network", 16)));
|
||||
return AjaxResult.success(products);
|
||||
}
|
||||
Map<String, Object> order;
|
||||
if ("create".equals(operation)) {
|
||||
order = orders.create(number(app, "id"), number(app, "user_id"), data);
|
||||
} else {
|
||||
order =
|
||||
store.one(
|
||||
"SELECT * FROM rent_order WHERE app_id=? AND merchant_order_no=?",
|
||||
app.get("id"),
|
||||
input(data, "merchant_order_no", 64));
|
||||
require(order != null, "订单不存在");
|
||||
}
|
||||
return AjaxResult.success(
|
||||
map(
|
||||
"order_no",
|
||||
order.get("order_no"),
|
||||
"merchant_order_no",
|
||||
order.get("merchant_order_no"),
|
||||
"network",
|
||||
order.get("network"),
|
||||
"resource_type",
|
||||
order.get("resource_type"),
|
||||
"resource_quantity",
|
||||
order.get("resource_quantity"),
|
||||
"receiver_address",
|
||||
order.get("receiver_address"),
|
||||
"status",
|
||||
order.get("status"),
|
||||
"reclaim_status",
|
||||
order.get("reclaim_status"),
|
||||
"amount",
|
||||
order.get("sale_amount"),
|
||||
"refunded_amount",
|
||||
order.get("refunded_amount")));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/** 登录业务入口。输入仅提取命令字段,不把客户端对象直接映射为数据库实体。 */
|
||||
@RestController
|
||||
@RequestMapping("/rental")
|
||||
public class RentalController {
|
||||
private final RentalStore store;
|
||||
private final RentalProvisioning provisioning;
|
||||
private final RentalIdentity identity;
|
||||
private final RentalOrders orders;
|
||||
private final RentalFunds funds;
|
||||
private final RentalReviews reviews;
|
||||
private final RentalTasks tasks;
|
||||
private final RentalChain chain;
|
||||
private final RentalQueries queries;
|
||||
|
||||
@Value("${rental.deposit-address.nile:}")
|
||||
private String nileDeposit;
|
||||
|
||||
@Value("${rental.deposit-address.mainnet:}")
|
||||
private String mainDeposit;
|
||||
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private RentalReconciliation reconciliation;
|
||||
|
||||
public RentalController(
|
||||
RentalStore store,
|
||||
RentalProvisioning provisioning,
|
||||
RentalIdentity identity,
|
||||
RentalOrders orders,
|
||||
RentalFunds funds,
|
||||
RentalReviews reviews,
|
||||
RentalTasks tasks,
|
||||
RentalChain chain,
|
||||
RentalQueries queries) {
|
||||
this.store = store;
|
||||
this.provisioning = provisioning;
|
||||
this.identity = identity;
|
||||
this.orders = orders;
|
||||
this.funds = funds;
|
||||
this.reviews = reviews;
|
||||
this.tasks = tasks;
|
||||
this.chain = chain;
|
||||
this.queries = queries;
|
||||
}
|
||||
|
||||
private long user() {
|
||||
Long user = SecurityUtils.getUserId();
|
||||
require(user != null, "请先登录");
|
||||
return user;
|
||||
}
|
||||
|
||||
@GetMapping("/mine/{resource}")
|
||||
@PreAuthorize("@ss.hasPermi('rent:portal:view')")
|
||||
public AjaxResult mine(
|
||||
@PathVariable String resource, @RequestParam(defaultValue = "1") int page) {
|
||||
return AjaxResult.success(queries.list(resource, user(), page));
|
||||
}
|
||||
|
||||
@GetMapping("/manage/{resource}")
|
||||
@PreAuthorize("@ss.hasPermi('rent:manage:list')")
|
||||
public AjaxResult manage(
|
||||
@PathVariable String resource, @RequestParam(defaultValue = "1") int page) {
|
||||
return AjaxResult.success(queries.list(resource, null, page));
|
||||
}
|
||||
|
||||
@PostMapping("/register/{resource}")
|
||||
@PreAuthorize("@ss.hasPermi('rent:portal:register')")
|
||||
public AjaxResult register(
|
||||
@PathVariable String resource, @RequestBody Map<String, Object> body) {
|
||||
return AjaxResult.success(provisioning.create(resource, body, user()));
|
||||
}
|
||||
|
||||
@PostMapping("/credential/issue")
|
||||
@PreAuthorize("@ss.hasPermi('rent:credential:issue')")
|
||||
public AjaxResult issue(@RequestBody Map<String, Object> body) {
|
||||
return AjaxResult.success(
|
||||
identity.issue(input(body, "owner_type", 8), number(body, "owner_id"), user()));
|
||||
}
|
||||
|
||||
@PostMapping("/credential/{id}/revoke")
|
||||
@PreAuthorize("@ss.hasPermi('rent:credential:issue')")
|
||||
public AjaxResult revoke(@PathVariable long id) {
|
||||
identity.revoke(id, user());
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
@PostMapping("/wallet/{id}/challenge")
|
||||
@PreAuthorize("@ss.hasPermi('rent:wallet:bind')")
|
||||
public AjaxResult challenge(@PathVariable long id) {
|
||||
return AjaxResult.success(provisioning.challenge(id, user()));
|
||||
}
|
||||
|
||||
@PostMapping("/wallet/{id}/prove")
|
||||
@PreAuthorize("@ss.hasPermi('rent:wallet:bind')")
|
||||
public AjaxResult prove(@PathVariable long id, @RequestBody Map<String, Object> body) {
|
||||
provisioning.prove(id, input(body, "nonce", 64), input(body, "signature", 256), user());
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
@PostMapping("/wallet/{id}/policy")
|
||||
@PreAuthorize("@ss.hasPermi('rent:wallet:bind')")
|
||||
public AjaxResult policy(@PathVariable long id, @RequestBody Map<String, Object> body) {
|
||||
provisioning.policy(id, body, user());
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
@PostMapping("/package")
|
||||
@PreAuthorize("@ss.hasPermi('rent:package:edit')")
|
||||
public AjaxResult product(@RequestBody Map<String, Object> body) {
|
||||
return AjaxResult.success(provisioning.product(body, user()));
|
||||
}
|
||||
|
||||
@PostMapping("/status/{resource}/{id}")
|
||||
@PreAuthorize("@ss.hasPermi('rent:manage:audit')")
|
||||
public AjaxResult status(
|
||||
@PathVariable String resource,
|
||||
@PathVariable long id,
|
||||
@RequestBody Map<String, Object> body) {
|
||||
provisioning.status(
|
||||
resource, id, input(body, "status", 32), user(), input(body, "reason", 512));
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
@PostMapping("/order")
|
||||
@PreAuthorize("@ss.hasPermi('rent:order:create')")
|
||||
public AjaxResult order(@RequestBody Map<String, Object> body) {
|
||||
Map<String, Object> order = orders.create(number(body, "app_id"), user(), body);
|
||||
return AjaxResult.success(
|
||||
map(
|
||||
"id",
|
||||
order.get("id"),
|
||||
"order_no",
|
||||
order.get("order_no"),
|
||||
"status",
|
||||
order.get("status")));
|
||||
}
|
||||
|
||||
@PostMapping("/order/{id}/cancel")
|
||||
@PreAuthorize("@ss.hasPermi('rent:order:create')")
|
||||
public AjaxResult cancel(@PathVariable long id) {
|
||||
orders.cancel(id, user());
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
@PostMapping("/account/open")
|
||||
@PreAuthorize("@ss.hasPermi('rent:portal:register')")
|
||||
public AjaxResult account(@RequestBody Map<String, Object> body) {
|
||||
return AjaxResult.success(funds.account(user(), input(body, "network", 16)));
|
||||
}
|
||||
|
||||
@PostMapping("/account/{id}/topup")
|
||||
@PreAuthorize("@ss.hasPermi('rent:account:topup')")
|
||||
public AjaxResult topup(@PathVariable long id, @RequestBody Map<String, Object> body) {
|
||||
Map<String, Object> account = store.get("account", id, false);
|
||||
String network = text(account, "network");
|
||||
String deposit = "NILE".equals(network) ? nileDeposit : mainDeposit;
|
||||
require(!deposit.isEmpty(), "尚未配置该网络租赁充值收款地址");
|
||||
java.math.BigDecimal amount = money(body.get("amount"));
|
||||
require(amount.signum() > 0, "充值金额必须大于0");
|
||||
Map<String, Object> proof =
|
||||
chain.transfer(
|
||||
network,
|
||||
input(body, "tx_id", 64),
|
||||
(int) number(body, "log_index"),
|
||||
deposit,
|
||||
amount);
|
||||
String reason = input(body, "reason", 512);
|
||||
long actor = user();
|
||||
tasks.tx(
|
||||
() -> {
|
||||
funds.post(
|
||||
id,
|
||||
"TOPUP:" + text(proof, "reference"),
|
||||
"TOPUP",
|
||||
amount,
|
||||
ZERO,
|
||||
ZERO,
|
||||
ZERO,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
actor,
|
||||
text(proof, "reference"),
|
||||
reason);
|
||||
store.event("ACCOUNT", id, "TOPUP", actor, reason);
|
||||
return null;
|
||||
});
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
@PostMapping("/order/{id}/refund")
|
||||
@PreAuthorize("@ss.hasPermi('rent:refund:create')")
|
||||
public AjaxResult refund(@PathVariable long id, @RequestBody Map<String, Object> body) {
|
||||
return AjaxResult.success(reviews.refund(id, body, user()));
|
||||
}
|
||||
|
||||
@PostMapping("/refund/{id}/review")
|
||||
@PreAuthorize("@ss.hasPermi('rent:refund:approve')")
|
||||
public AjaxResult reviewRefund(@PathVariable long id, @RequestBody Map<String, Object> body) {
|
||||
require(body.get("approve") instanceof Boolean, "必须明确审批结果");
|
||||
reviews.approveRefund(id, Boolean.TRUE.equals(body.get("approve")), user());
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
@PostMapping("/settlement")
|
||||
@PreAuthorize("@ss.hasPermi('rent:settlement:create')")
|
||||
public AjaxResult settlement(@RequestBody Map<String, Object> body) {
|
||||
require(body.get("order_ids") instanceof List, "缺少来源订单");
|
||||
List<Long> ids = new ArrayList<>();
|
||||
for (Object value : (List<?>) body.get("order_ids")) {
|
||||
ids.add(Long.valueOf(value.toString()));
|
||||
}
|
||||
return AjaxResult.success(reviews.settlement(ids, user()));
|
||||
}
|
||||
|
||||
@PostMapping("/settlement/{id}/{action}")
|
||||
@PreAuthorize("@ss.hasPermi('rent:settlement:approve')")
|
||||
public AjaxResult settlementAction(
|
||||
@PathVariable long id,
|
||||
@PathVariable String action,
|
||||
@RequestBody Map<String, Object> body) {
|
||||
String reason = input(body, "reason", 512);
|
||||
long actor = user();
|
||||
if ("confirm".equals(action)) {
|
||||
Map<String, Object> row = store.get("settlement", id, false),
|
||||
account = store.get("account", number(row, "account_id"), false);
|
||||
Map<String, Object> authorization;
|
||||
try {
|
||||
authorization =
|
||||
new com.fasterxml.jackson.databind.ObjectMapper()
|
||||
.readValue(text(row, "payment_evidence"), Map.class);
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalArgumentException("缺少原付款授权收款地址");
|
||||
}
|
||||
Map<String, Object> proof =
|
||||
chain.transfer(
|
||||
text(account, "network"),
|
||||
input(body, "tx_id", 64),
|
||||
(int) number(body, "log_index"),
|
||||
text(authorization, "receiver_address"),
|
||||
amount(row, "amount"));
|
||||
reviews.paid(id, text(proof, "reference"), orders.encode(proof), actor);
|
||||
return AjaxResult.success();
|
||||
}
|
||||
return AjaxResult.success(
|
||||
tasks.tx(
|
||||
() -> {
|
||||
Map<String, Object> row = reviews.transition(id, action, actor, reason);
|
||||
if ("pay".equals(action) && row.get("payment_evidence") == null) {
|
||||
String receiver = input(body, "receiver_address", 64);
|
||||
RentalOrders.address(receiver);
|
||||
store.update(
|
||||
"settlement",
|
||||
id,
|
||||
map(
|
||||
"payment_evidence",
|
||||
orders.encode(
|
||||
map(
|
||||
"receiver_address",
|
||||
receiver,
|
||||
"payout_no",
|
||||
text(row, "payout_no")))));
|
||||
row = store.get("settlement", id, false);
|
||||
}
|
||||
return row;
|
||||
}));
|
||||
}
|
||||
|
||||
@PostMapping("/wallet/{id}/refresh")
|
||||
@PreAuthorize("@ss.hasPermi('rent:manage:audit')")
|
||||
public AjaxResult refresh(@PathVariable long id) {
|
||||
tasks.refresh(id);
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
@PostMapping("/task/{id}/verify")
|
||||
@PreAuthorize("@ss.hasPermi('rent:manage:audit')")
|
||||
public AjaxResult verify(@PathVariable long id) {
|
||||
tasks.verify(id);
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
@PostMapping("/task/{id}/attach")
|
||||
@PreAuthorize("@ss.hasPermi('rent:manage:audit')")
|
||||
public AjaxResult attach(@PathVariable long id, @RequestBody Map<String, Object> body) {
|
||||
tasks.attach(id, input(body, "tx_id", 64), user(), input(body, "reason", 512));
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
@PostMapping("/order/{id}/resolve")
|
||||
@PreAuthorize("@ss.hasPermi('rent:manage:audit')")
|
||||
public AjaxResult resolve(@PathVariable long id, @RequestBody Map<String, Object> body) {
|
||||
tasks.resolveRecovered(id, user(), input(body, "reason", 512));
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
@PostMapping("/webhook/{id}/retry")
|
||||
@PreAuthorize("@ss.hasPermi('rent:manage:audit')")
|
||||
public AjaxResult retryWebhook(@PathVariable long id, @RequestBody Map<String, Object> body) {
|
||||
String reason = input(body, "reason", 512);
|
||||
long actor = user();
|
||||
tasks.tx(
|
||||
() -> {
|
||||
Map<String, Object> row = store.get("webhook", id, true);
|
||||
require("DEAD".equals(text(row, "status")), "只允许人工重新投递已终止的事件");
|
||||
store.event(
|
||||
"ORDER",
|
||||
number(row, "order_id"),
|
||||
"RETRY_WEBHOOK",
|
||||
actor,
|
||||
reason + ";原重试次数=" + text(row, "attempt_count"));
|
||||
store.update(
|
||||
"webhook",
|
||||
id,
|
||||
map(
|
||||
"status",
|
||||
"PENDING",
|
||||
"attempt_count",
|
||||
0,
|
||||
"next_attempt_at",
|
||||
now(),
|
||||
"lock_owner",
|
||||
null,
|
||||
"lock_until",
|
||||
null));
|
||||
return null;
|
||||
});
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
@GetMapping("/reconcile")
|
||||
@PreAuthorize("@ss.hasPermi('rent:manage:audit')")
|
||||
public AjaxResult reconcile(@RequestParam(defaultValue = "0") long afterId) {
|
||||
require(afterId >= 0, "核对游标不能为负");
|
||||
return AjaxResult.success(
|
||||
map(
|
||||
"accounts",
|
||||
reconciliation.check(afterId),
|
||||
"reservations",
|
||||
reconciliation.reservations()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
/** HMAC四域隔离和Secret信封加密。主密钥仅通过外部配置注入,缺失时拒绝签发。 */
|
||||
@Component
|
||||
public class RentalCrypto {
|
||||
@Value("${rental.master-key:}")
|
||||
private String masterKey;
|
||||
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
public static String sha256(String body) {
|
||||
try {
|
||||
return hex(
|
||||
MessageDigest.getInstance("SHA-256")
|
||||
.digest(body.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalStateException("摘要计算失败");
|
||||
}
|
||||
}
|
||||
|
||||
public static String sign(
|
||||
String secret,
|
||||
String scope,
|
||||
String key,
|
||||
long timestamp,
|
||||
String nonce,
|
||||
String method,
|
||||
String path,
|
||||
String body) {
|
||||
for (String value : new String[] {scope, key, nonce, method, path}) {
|
||||
require(value != null && !value.contains("\n") && !value.contains("\r"), "签名字段非法");
|
||||
}
|
||||
String plain =
|
||||
String.join(
|
||||
"\n",
|
||||
"RENT_HMAC_SHA256_V1",
|
||||
scope,
|
||||
key,
|
||||
Long.toString(timestamp),
|
||||
nonce,
|
||||
method,
|
||||
path,
|
||||
sha256(body));
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
|
||||
return hex(mac.doFinal(plain.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalStateException("签名计算失败");
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean equal(String expected, String actual) {
|
||||
return actual != null
|
||||
&& MessageDigest.isEqual(
|
||||
expected.getBytes(StandardCharsets.US_ASCII),
|
||||
actual.getBytes(StandardCharsets.US_ASCII));
|
||||
}
|
||||
|
||||
public static String random() {
|
||||
byte[] bytes = new byte[32];
|
||||
RANDOM.nextBytes(bytes);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
|
||||
public String encrypt(String secret) {
|
||||
return crypt(secret, true);
|
||||
}
|
||||
|
||||
public String decrypt(String value) {
|
||||
return crypt(value, false);
|
||||
}
|
||||
|
||||
private String crypt(String value, boolean encrypt) {
|
||||
try {
|
||||
byte[] key = Base64.getDecoder().decode(masterKey);
|
||||
require(key.length == 32, "租赁主密钥必须是Base64编码的32字节密钥");
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
if (encrypt) {
|
||||
byte[] iv = new byte[12];
|
||||
RANDOM.nextBytes(iv);
|
||||
cipher.init(
|
||||
Cipher.ENCRYPT_MODE,
|
||||
new SecretKeySpec(key, "AES"),
|
||||
new GCMParameterSpec(128, iv));
|
||||
return Base64.getEncoder().encodeToString(iv)
|
||||
+ "."
|
||||
+ Base64.getEncoder()
|
||||
.encodeToString(
|
||||
cipher.doFinal(value.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
String[] parts = value.split("\\.");
|
||||
require(parts.length == 2, "凭证格式错误");
|
||||
cipher.init(
|
||||
Cipher.DECRYPT_MODE,
|
||||
new SecretKeySpec(key, "AES"),
|
||||
new GCMParameterSpec(128, Base64.getDecoder().decode(parts[0])));
|
||||
return new String(
|
||||
cipher.doFinal(Base64.getDecoder().decode(parts[1])), StandardCharsets.UTF_8);
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalStateException("租赁凭证加解密失败,请检查外部主密钥配置");
|
||||
}
|
||||
}
|
||||
|
||||
private static String hex(byte[] bytes) {
|
||||
StringBuilder result = new StringBuilder(bytes.length * 2);
|
||||
for (byte value : bytes) {
|
||||
result.append(String.format("%02x", value & 255));
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
/** 租赁错误不包含SQL、Secret、认证原文或底层RPC响应。 */
|
||||
@RestControllerAdvice(basePackageClasses = RentalController.class)
|
||||
@org.springframework.core.annotation.Order(org.springframework.core.Ordered.HIGHEST_PRECEDENCE)
|
||||
public class RentalErrors {
|
||||
@ExceptionHandler(IllegalArgumentException.class)
|
||||
public AjaxResult invalid(IllegalArgumentException exception) {
|
||||
return AjaxResult.error(400, exception.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(IllegalStateException.class)
|
||||
public AjaxResult state(IllegalStateException exception) {
|
||||
return AjaxResult.error(409, exception.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(DataAccessException.class)
|
||||
public AjaxResult database(DataAccessException exception) {
|
||||
return AjaxResult.error(409, "租赁记录冲突或数据库结构未就绪,请核对状态后重试");
|
||||
}
|
||||
|
||||
@ExceptionHandler(org.springframework.security.access.AccessDeniedException.class)
|
||||
public AjaxResult denied(org.springframework.security.access.AccessDeniedException exception) {
|
||||
return AjaxResult.error(403, "缺少租赁操作权限");
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public AjaxResult unexpected(Exception exception) {
|
||||
return AjaxResult.error(500, "租赁操作暂未完成,请保留业务编号并检查配置或运行状态");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Map;
|
||||
|
||||
/** 资金统一入口。所有余额变化与不可变流水同事务;不提供任意金额覆盖接口。 调用方先锁业务主记录,再按账户ID升序加锁,避免商户同时也是供应商时反向锁死。 */
|
||||
@Service
|
||||
public class RentalFunds {
|
||||
private final RentalStore store;
|
||||
|
||||
public RentalFunds(RentalStore store) {
|
||||
this.store = store;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Map<String, Object> account(long user, String network) {
|
||||
network(network);
|
||||
store.execute(
|
||||
"INSERT INTO"
|
||||
+ " rent_account(user_id,network,available_amount,frozen_amount,supplier_pending_amount,status,version,created_at,updated_at)"
|
||||
+ " VALUES(?,?,0,0,0,'ACTIVE',0,?,?) ON DUPLICATE KEY UPDATE id=id",
|
||||
user,
|
||||
network,
|
||||
now(),
|
||||
now());
|
||||
return store.one("SELECT * FROM rent_account WHERE user_id=? AND network=?", user, network);
|
||||
}
|
||||
|
||||
public void lock(long first, long second) {
|
||||
store.get("account", Math.min(first, second), true);
|
||||
if (first != second) {
|
||||
store.get("account", Math.max(first, second), true);
|
||||
}
|
||||
}
|
||||
|
||||
/** 全局business_key先去重,并校验同键的账户、事件与金额,不吞掉不同参数的重放。 */
|
||||
public void post(
|
||||
long account,
|
||||
String key,
|
||||
String type,
|
||||
BigDecimal available,
|
||||
BigDecimal frozen,
|
||||
BigDecimal pending,
|
||||
BigDecimal fee,
|
||||
Long order,
|
||||
Long settlement,
|
||||
Long refund,
|
||||
long actor,
|
||||
String evidence,
|
||||
String reason) {
|
||||
Map<String, Object> row = store.get("account", account, true);
|
||||
Map<String, Object> old = store.one("SELECT * FROM rent_ledger WHERE business_key=?", key);
|
||||
if (old != null) {
|
||||
require(
|
||||
number(old, "account_id") == account
|
||||
&& type.equals(text(old, "event_type"))
|
||||
&& amount(old, "delta_available").compareTo(available) == 0
|
||||
&& amount(old, "delta_frozen").compareTo(frozen) == 0
|
||||
&& amount(old, "delta_supplier_pending").compareTo(pending) == 0
|
||||
&& amount(old, "delta_platform_fee").compareTo(fee) == 0,
|
||||
"记账键已被不同业务占用");
|
||||
return;
|
||||
}
|
||||
BigDecimal a = amount(row, "available_amount").add(available);
|
||||
BigDecimal f = amount(row, "frozen_amount").add(frozen);
|
||||
BigDecimal p = amount(row, "supplier_pending_amount").add(pending);
|
||||
require(a.signum() >= 0 && f.signum() >= 0 && p.signum() >= 0, "余额不足或资金状态冲突");
|
||||
store.update(
|
||||
"account",
|
||||
account,
|
||||
map("available_amount", a, "frozen_amount", f, "supplier_pending_amount", p));
|
||||
Long reversalOf = null;
|
||||
if ("REVERSAL".equals(type) && order != null) {
|
||||
Map<String, Object> original =
|
||||
store.one(
|
||||
"SELECT id FROM rent_ledger WHERE business_key=?",
|
||||
(key.endsWith(":FEE") ? "FEE:" : "EARN:") + order);
|
||||
require(original != null, "冲正缺少原记账来源");
|
||||
reversalOf = number(original, "id");
|
||||
}
|
||||
store.insert(
|
||||
"ledger",
|
||||
map(
|
||||
"account_id",
|
||||
account,
|
||||
"business_key",
|
||||
key,
|
||||
"event_type",
|
||||
type,
|
||||
"delta_available",
|
||||
available,
|
||||
"delta_frozen",
|
||||
frozen,
|
||||
"delta_supplier_pending",
|
||||
pending,
|
||||
"delta_platform_fee",
|
||||
fee,
|
||||
"after_available",
|
||||
a,
|
||||
"after_frozen",
|
||||
f,
|
||||
"after_supplier_pending",
|
||||
p,
|
||||
"order_id",
|
||||
order,
|
||||
"settlement_id",
|
||||
settlement,
|
||||
"refund_id",
|
||||
refund,
|
||||
"reversal_of_id",
|
||||
reversalOf,
|
||||
"operator_user_id",
|
||||
actor,
|
||||
"evidence_ref",
|
||||
evidence,
|
||||
"reason",
|
||||
reason));
|
||||
}
|
||||
|
||||
public void hold(Map<String, Object> order) {
|
||||
long id = number(order, "id");
|
||||
BigDecimal price = amount(order, "sale_amount");
|
||||
post(
|
||||
number(order, "payer_account_id"),
|
||||
"HOLD:" + id,
|
||||
"HOLD",
|
||||
price.negate(),
|
||||
price,
|
||||
ZERO,
|
||||
ZERO,
|
||||
id,
|
||||
null,
|
||||
null,
|
||||
0,
|
||||
null,
|
||||
"租赁订单冻结");
|
||||
}
|
||||
|
||||
public void release(Map<String, Object> order) {
|
||||
require("HELD".equals(text(order, "fund_status")), "订单不处于冻结状态");
|
||||
long id = number(order, "id");
|
||||
BigDecimal price = amount(order, "sale_amount");
|
||||
post(
|
||||
number(order, "payer_account_id"),
|
||||
"RELEASE:" + id,
|
||||
"RELEASE",
|
||||
price,
|
||||
price.negate(),
|
||||
ZERO,
|
||||
ZERO,
|
||||
id,
|
||||
null,
|
||||
null,
|
||||
0,
|
||||
null,
|
||||
"明确未执行,释放冻结");
|
||||
store.update("order", id, map("fund_status", "RELEASED"));
|
||||
}
|
||||
|
||||
public void charge(Map<String, Object> order) {
|
||||
require("HELD".equals(text(order, "fund_status")), "订单资金不可重复扣款");
|
||||
long id = number(order, "id");
|
||||
long payer = number(order, "payer_account_id");
|
||||
long supplier = number(order, "supplier_account_id");
|
||||
lock(payer, supplier);
|
||||
post(
|
||||
payer,
|
||||
"CHARGE:" + id,
|
||||
"CHARGE",
|
||||
ZERO,
|
||||
amount(order, "sale_amount").negate(),
|
||||
ZERO,
|
||||
ZERO,
|
||||
id,
|
||||
null,
|
||||
null,
|
||||
0,
|
||||
null,
|
||||
"独立链上核验通过,确认扣款");
|
||||
post(
|
||||
supplier,
|
||||
"EARN:" + id,
|
||||
"SUPPLIER_EARN",
|
||||
ZERO,
|
||||
ZERO,
|
||||
amount(order, "supplier_amount"),
|
||||
ZERO,
|
||||
id,
|
||||
null,
|
||||
null,
|
||||
0,
|
||||
null,
|
||||
"供应商履约毛收入");
|
||||
BigDecimal fee = amount(order, "supplier_fee_amount");
|
||||
post(
|
||||
supplier,
|
||||
"FEE:" + id,
|
||||
"SUPPLIER_FEE",
|
||||
ZERO,
|
||||
ZERO,
|
||||
fee.negate(),
|
||||
fee,
|
||||
id,
|
||||
null,
|
||||
null,
|
||||
0,
|
||||
null,
|
||||
"按订单锁定费率扣取手续费");
|
||||
store.update("order", id, map("fund_status", "CHARGED"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
|
||||
import okhttp3.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.URI;
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/** 回调专用HTTP客户端:HTTPS、解析结果逐一检查、实际连接复用该DNS结果、拒绝重定向。 */
|
||||
public final class RentalHttp {
|
||||
private RentalHttp() {}
|
||||
|
||||
public static void checkUrl(String url) {
|
||||
URI uri = URI.create(url);
|
||||
require(
|
||||
"https".equalsIgnoreCase(uri.getScheme())
|
||||
&& uri.getHost() != null
|
||||
&& uri.getUserInfo() == null
|
||||
&& uri.getFragment() == null
|
||||
&& uri.getQuery() == null
|
||||
&& (uri.getPort() == -1 || uri.getPort() == 443)
|
||||
&& url.length() <= 512,
|
||||
"回调仅允许标准HTTPS地址");
|
||||
}
|
||||
|
||||
public static boolean publicAddress(InetAddress address) {
|
||||
byte[] bytes = address.getAddress();
|
||||
if (address.isAnyLocalAddress()
|
||||
|| address.isLoopbackAddress()
|
||||
|| address.isLinkLocalAddress()
|
||||
|| address.isSiteLocalAddress()
|
||||
|| address.isMulticastAddress()) {
|
||||
return false;
|
||||
}
|
||||
if (bytes.length == 16) {
|
||||
return (bytes[0] & 0xe0) == 0x20;
|
||||
}
|
||||
int a = bytes[0] & 255;
|
||||
int b = bytes[1] & 255;
|
||||
return a != 0
|
||||
&& a != 10
|
||||
&& a != 127
|
||||
&& a < 224
|
||||
&& !(a == 100 && b >= 64 && b <= 127)
|
||||
&& !(a == 169 && b == 254)
|
||||
&& !(a == 172 && b >= 16 && b <= 31)
|
||||
&& !(a == 192 && b == 168)
|
||||
&& !(a == 198 && (b == 18 || b == 19))
|
||||
&& !(a == 192 && b == 0);
|
||||
}
|
||||
|
||||
public static OkHttpClient callbackClient() {
|
||||
return new OkHttpClient.Builder()
|
||||
.connectTimeout(5, TimeUnit.SECONDS)
|
||||
.readTimeout(5, TimeUnit.SECONDS)
|
||||
.callTimeout(10, TimeUnit.SECONDS)
|
||||
.followRedirects(false)
|
||||
.followSslRedirects(false)
|
||||
.retryOnConnectionFailure(false)
|
||||
.dns(
|
||||
host -> {
|
||||
InetAddress[] addresses = InetAddress.getAllByName(host);
|
||||
for (InetAddress address : addresses) {
|
||||
if (!publicAddress(address)) {
|
||||
throw new java.net.UnknownHostException("回调目标非公网地址");
|
||||
}
|
||||
}
|
||||
return Arrays.asList(addresses);
|
||||
})
|
||||
.build();
|
||||
}
|
||||
|
||||
public static String body(Response response) throws IOException {
|
||||
require(response.isSuccessful() && response.body() != null, "RPC响应失败");
|
||||
java.io.InputStream stream = response.body().byteStream();
|
||||
java.io.ByteArrayOutputStream output = new java.io.ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[4096];
|
||||
int count;
|
||||
while ((count = stream.read(buffer)) != -1) {
|
||||
require(output.size() + count <= 1024 * 1024, "RPC响应超过限制");
|
||||
output.write(buffer, 0, count);
|
||||
}
|
||||
return new String(output.toByteArray(), java.nio.charset.StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
/** 外部APP和本地NODE共用凭证认证,登录用户归属仍由sys_user及RBAC决定。 */
|
||||
@Service
|
||||
public class RentalIdentity {
|
||||
private final RentalStore store;
|
||||
private final RentalCrypto crypto;
|
||||
|
||||
@Value("${rental.master-key-version:v1}")
|
||||
private String masterVersion;
|
||||
|
||||
public RentalIdentity(RentalStore store, RentalCrypto crypto) {
|
||||
this.store = store;
|
||||
this.crypto = crypto;
|
||||
}
|
||||
|
||||
public Map<String, Object> credential(String key) {
|
||||
Map<String, Object> row = store.one("SELECT * FROM rent_credential WHERE api_key=?", key);
|
||||
require(
|
||||
row != null
|
||||
&& "ACTIVE".equals(text(row, "status"))
|
||||
&& (row.get("expires_at") == null
|
||||
|| time(row.get("expires_at")).isAfter(Instant.now())),
|
||||
"租赁凭证无效");
|
||||
return row;
|
||||
}
|
||||
|
||||
public String secret(Map<String, Object> credential) {
|
||||
return crypto.decrypt(text(credential, "api_secret"));
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Map<String, Object> authenticate(
|
||||
String key,
|
||||
String ownerType,
|
||||
String scope,
|
||||
long timestamp,
|
||||
String nonce,
|
||||
String method,
|
||||
String path,
|
||||
String body,
|
||||
String signature) {
|
||||
require(
|
||||
key != null
|
||||
&& key.length() <= 64
|
||||
&& nonce != null
|
||||
&& nonce.matches("[A-Za-z0-9_-]{16,64}")
|
||||
&& timestamp > System.currentTimeMillis() - 60000
|
||||
&& timestamp < System.currentTimeMillis() + 60000,
|
||||
"认证时间或随机数无效");
|
||||
Map<String, Object> row = credential(key);
|
||||
require(
|
||||
ownerType.equals(text(row, "owner_type"))
|
||||
&& RentalCrypto.equal(
|
||||
RentalCrypto.sign(
|
||||
secret(row),
|
||||
scope,
|
||||
key,
|
||||
timestamp,
|
||||
nonce,
|
||||
method,
|
||||
path,
|
||||
body),
|
||||
signature),
|
||||
"租赁签名无效");
|
||||
store.insert(
|
||||
"nonce",
|
||||
map("api_key", key, "scope", scope, "nonce", nonce, "expires_at", after(180)));
|
||||
return row;
|
||||
}
|
||||
|
||||
/** 轮换保留历史Secret,仅明确在途任务可以使用VERIFY_ONLY,不能签发新任务。 */
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Map<String, Object> issue(String type, long owner, long actor) {
|
||||
require("APP".equals(type) || "NODE".equals(type), "凭证主体非法");
|
||||
Map<String, Object> row = store.get(type.toLowerCase(Locale.ROOT), owner, true);
|
||||
require(number(row, "user_id") == actor, "无主体权限");
|
||||
String secret = RentalCrypto.random();
|
||||
String encrypted = crypto.encrypt(secret);
|
||||
String key = id("RK");
|
||||
store.execute(
|
||||
"UPDATE rent_credential SET status='VERIFY_ONLY',version=version+1,updated_at=?"
|
||||
+ " WHERE owner_type=? AND owner_id=? AND status='ACTIVE'",
|
||||
now(),
|
||||
type,
|
||||
owner);
|
||||
long id =
|
||||
store.insert(
|
||||
"credential",
|
||||
map(
|
||||
"owner_type",
|
||||
type,
|
||||
"owner_id",
|
||||
owner,
|
||||
"api_key",
|
||||
key,
|
||||
"api_secret",
|
||||
encrypted,
|
||||
"master_key_version",
|
||||
masterVersion,
|
||||
"status",
|
||||
"ACTIVE"));
|
||||
store.event(type, owner, "ROTATE_CREDENTIAL", actor, "新Secret仅通过本次TLS响应展示,旧凭证仅核对在途");
|
||||
return map("id", id, "api_key", key, "api_secret", secret);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void revoke(long id, long actor) {
|
||||
Map<String, Object> credential = store.get("credential", id, true);
|
||||
Map<String, Object> owner =
|
||||
store.get(
|
||||
text(credential, "owner_type").toLowerCase(Locale.ROOT),
|
||||
number(credential, "owner_id"),
|
||||
false);
|
||||
require(number(owner, "user_id") == actor, "无主体权限");
|
||||
store.update("credential", id, map("status", "REVOKED", "revoked_at", now()));
|
||||
store.event(
|
||||
"APP".equals(text(credential, "owner_type")) ? "APP" : "NODE",
|
||||
number(credential, "owner_id"),
|
||||
"REVOKE_CREDENTIAL",
|
||||
actor,
|
||||
"主动吊销凭证");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import static com.ruoyi.system.rental.RentalValues.require;
|
||||
|
||||
/** Jackson2.10没有流深度限制,解析前先检查结构深度;字符串内括号不计入。 */
|
||||
public final class RentalJson {
|
||||
private RentalJson() {}
|
||||
|
||||
public static void bounded(String value) {
|
||||
require(value != null && value.length() <= 65536, "JSON消息超限");
|
||||
int depth = 0;
|
||||
boolean quoted = false;
|
||||
boolean escaped = false;
|
||||
for (int i = 0; i < value.length(); i++) {
|
||||
char character = value.charAt(i);
|
||||
if (quoted) {
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
} else if (character == '\\') {
|
||||
escaped = true;
|
||||
} else if (character == '"') {
|
||||
quoted = false;
|
||||
}
|
||||
} else if (character == '"') {
|
||||
quoted = true;
|
||||
} else if (character == '{' || character == '[') {
|
||||
require(++depth <= 32, "JSON嵌套超过32层");
|
||||
} else if (character == '}' || character == ']') {
|
||||
require(--depth >= 0, "JSON结构无效");
|
||||
}
|
||||
}
|
||||
require(depth == 0 && !quoted, "JSON结构不完整");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/** 禁用生成器直接操作16张业务表的旧入口,包括余额覆盖、流水删除和Secret导出。 旧菜单组件仍可保留,页面统一转向/rental业务接口;不是依赖隐藏按钮防越权。 */
|
||||
@Configuration
|
||||
public class RentalLegacyGuard implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(
|
||||
new HandlerInterceptor() {
|
||||
@Override
|
||||
public boolean preHandle(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
Object handler)
|
||||
throws Exception {
|
||||
String path =
|
||||
request.getRequestURI()
|
||||
.substring(request.getContextPath().length());
|
||||
if (path.matches(
|
||||
"/system/rent(App|Credential|Nonce|Node|Wallet|Package|Account|Order|Task|Transaction|Ledger|Settlement|SettlementItem|Refund|Webhook|Event)(/.*)?")) {
|
||||
response.setStatus(409);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter()
|
||||
.write("{\"code\":409,\"msg\":\"请使用租赁业务接口,禁止直接修改或导出底层业务记录\"}");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.tron.trident.core.ApiWrapper;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.Map;
|
||||
|
||||
/** 下单、冻结、取消与业务回调入队;外部接口与登录接口复用同一套事务规则。 */
|
||||
@Service
|
||||
public class RentalOrders {
|
||||
private final RentalStore store;
|
||||
private final RentalFunds funds;
|
||||
private final ObjectMapper json;
|
||||
|
||||
public RentalOrders(RentalStore store, RentalFunds funds, ObjectMapper json) {
|
||||
this.store = store;
|
||||
this.funds = funds;
|
||||
this.json = json;
|
||||
}
|
||||
|
||||
public static void address(String address) {
|
||||
try {
|
||||
require(
|
||||
address.startsWith("T") && ApiWrapper.parseAddress(address).size() == 21,
|
||||
"地址不合法");
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalArgumentException("TRON地址校验失败");
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Map<String, Object> create(long appId, long user, Map<String, Object> request) {
|
||||
// 锁应用行使同应用幂等竞争顺序化;不能仅依靠先查后插。
|
||||
Map<String, Object> app = store.get("app", appId, true);
|
||||
require(
|
||||
number(app, "user_id") == user && "ACTIVE".equals(text(app, "status")),
|
||||
"应用无权限或已禁用");
|
||||
String merchant = input(request, "merchant_order_no", 64);
|
||||
String receiver = input(request, "receiver_address", 64);
|
||||
address(receiver);
|
||||
long packageId = number(request, "package_id");
|
||||
String notify = text(request, "notify_url").trim();
|
||||
if (notify.isEmpty()) {
|
||||
notify = text(app, "notify_url");
|
||||
}
|
||||
if (!notify.isEmpty()) {
|
||||
RentalHttp.checkUrl(notify);
|
||||
}
|
||||
String hash =
|
||||
RentalCrypto.sha256(
|
||||
encode(
|
||||
map(
|
||||
"package_id",
|
||||
packageId,
|
||||
"receiver_address",
|
||||
receiver,
|
||||
"notify_url",
|
||||
notify)));
|
||||
Map<String, Object> existing =
|
||||
store.one(
|
||||
"SELECT * FROM rent_order WHERE app_id=? AND merchant_order_no=?",
|
||||
appId,
|
||||
merchant);
|
||||
if (existing != null) {
|
||||
require(hash.equals(text(existing, "request_hash")), "同一商户订单号参数不一致");
|
||||
return existing;
|
||||
}
|
||||
Map<String, Object> product = store.get("package", packageId, true);
|
||||
validatePackage(product);
|
||||
require("ACTIVE".equals(text(product, "status")), "套餐未上架");
|
||||
if (request.containsKey("resource_type")) {
|
||||
require(
|
||||
text(product, "resource_type").equals(text(request, "resource_type")),
|
||||
"资源类型与套餐不符");
|
||||
}
|
||||
Map<String, Object> account = funds.account(user, network(text(product, "network")));
|
||||
account = store.get("account", number(account, "id"), true);
|
||||
require("ACTIVE".equals(text(account, "status")), "租赁账户已冻结");
|
||||
BigDecimal gross = amount(product, "supplier_amount");
|
||||
BigDecimal fee =
|
||||
gross.multiply(new BigDecimal(text(product, "supplier_fee_percent")))
|
||||
.movePointLeft(2)
|
||||
.setScale(6, RoundingMode.HALF_UP);
|
||||
Map<String, Object> order =
|
||||
map(
|
||||
"order_no",
|
||||
id("RO"),
|
||||
"app_id",
|
||||
appId,
|
||||
"merchant_order_no",
|
||||
merchant,
|
||||
"request_hash",
|
||||
hash,
|
||||
"package_id",
|
||||
packageId,
|
||||
"network",
|
||||
text(product, "network"),
|
||||
"receiver_address",
|
||||
receiver,
|
||||
"resource_type",
|
||||
text(product, "resource_type"),
|
||||
"resource_quantity",
|
||||
number(product, "resource_quantity"),
|
||||
"redundancy_percent",
|
||||
product.get("redundancy_percent"),
|
||||
"target_resource_quantity",
|
||||
target(
|
||||
number(product, "resource_quantity"),
|
||||
new BigDecimal(text(product, "redundancy_percent"))),
|
||||
"duration_seconds",
|
||||
number(product, "duration_seconds"),
|
||||
"sale_amount",
|
||||
amount(product, "sale_amount"),
|
||||
"supplier_amount",
|
||||
gross,
|
||||
"supplier_fee_percent",
|
||||
product.get("supplier_fee_percent"),
|
||||
"supplier_fee_amount",
|
||||
fee,
|
||||
"supplier_net_amount",
|
||||
gross.subtract(fee),
|
||||
"package_snapshot",
|
||||
encode(product),
|
||||
"status",
|
||||
"WAITING",
|
||||
"payer_account_id",
|
||||
number(account, "id"),
|
||||
"fund_status",
|
||||
"HELD",
|
||||
"dispatch_deadline",
|
||||
after(300),
|
||||
"reclaim_status",
|
||||
"NOT_STARTED",
|
||||
"notify_url",
|
||||
notify.isEmpty() ? null : notify);
|
||||
long id = store.insert("order", order);
|
||||
order.put("id", id);
|
||||
funds.hold(order);
|
||||
store.event("ORDER", id, "CREATE", user, "创建订单并冻结内部USDT");
|
||||
return store.get("order", id, false);
|
||||
}
|
||||
|
||||
public static void validatePackage(Map<String, Object> row) {
|
||||
network(text(row, "network"));
|
||||
resource(text(row, "resource_type"));
|
||||
target(number(row, "resource_quantity"), new BigDecimal(text(row, "redundancy_percent")));
|
||||
BigDecimal sale = amount(row, "sale_amount");
|
||||
BigDecimal gross = amount(row, "supplier_amount");
|
||||
BigDecimal percent = new BigDecimal(text(row, "supplier_fee_percent"));
|
||||
BigDecimal fee = gross.multiply(percent).movePointLeft(2).setScale(6, RoundingMode.HALF_UP);
|
||||
require(
|
||||
sale.signum() > 0
|
||||
&& gross.signum() > 0
|
||||
&& gross.compareTo(sale) <= 0
|
||||
&& percent.signum() > 0
|
||||
&& percent.compareTo(new BigDecimal("100")) < 0
|
||||
&& fee.signum() > 0
|
||||
&& fee.compareTo(gross) < 0,
|
||||
"套餐售价或供应商费率无效");
|
||||
require(
|
||||
number(row, "duration_seconds") > 0
|
||||
&& number(row, "fee_limit_sun") > 0
|
||||
&& number(row, "delegate_lock") == 0,
|
||||
"首版仅支持非锁定委托,租期和本地费用预算必须为正");
|
||||
require(row.get("rules") != null && !text(row, "rules").isEmpty(), "必须配置套餐规则");
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void cancel(long orderId, long user) {
|
||||
Map<String, Object> order = store.get("order", orderId, true);
|
||||
Map<String, Object> app = store.get("app", number(order, "app_id"), false);
|
||||
require(number(app, "user_id") == user, "无订单权限");
|
||||
if ("CANCELLED".equals(text(order, "status"))) {
|
||||
return;
|
||||
}
|
||||
require(
|
||||
"WAITING".equals(text(order, "status"))
|
||||
&& store.one("SELECT id FROM rent_task WHERE order_id=? LIMIT 1", orderId)
|
||||
== null,
|
||||
"已创建执行任务,不可取消或重派");
|
||||
funds.release(order);
|
||||
store.update("order", orderId, map("status", "CANCELLED"));
|
||||
webhook(order, "CANCELLED", "ORDER:" + orderId + ":CANCELLED");
|
||||
store.event("ORDER", orderId, "CANCEL", user, "未派单取消");
|
||||
}
|
||||
|
||||
public void webhook(Map<String, Object> order, String type, String key) {
|
||||
long orderId = number(order, "id");
|
||||
if (store.one("SELECT id FROM rent_webhook WHERE event_key=?", key) != null) {
|
||||
return;
|
||||
}
|
||||
Map<String, Object> last =
|
||||
store.one(
|
||||
"SELECT COALESCE(MAX(order_event_sequence),0) AS seq FROM rent_webhook"
|
||||
+ " WHERE order_id=?",
|
||||
orderId);
|
||||
long seq = number(last, "seq") + 1;
|
||||
String event = id("WH");
|
||||
store.insert(
|
||||
"webhook",
|
||||
map(
|
||||
"event_no",
|
||||
event,
|
||||
"order_id",
|
||||
orderId,
|
||||
"event_type",
|
||||
type,
|
||||
"event_key",
|
||||
key,
|
||||
"order_event_sequence",
|
||||
seq,
|
||||
"payload",
|
||||
encode(
|
||||
map(
|
||||
"event_no",
|
||||
event,
|
||||
"event_type",
|
||||
type,
|
||||
"order_event_sequence",
|
||||
seq,
|
||||
"order_no",
|
||||
text(order, "order_no"),
|
||||
"merchant_order_no",
|
||||
text(order, "merchant_order_no"),
|
||||
"network",
|
||||
text(order, "network"),
|
||||
"resource_type",
|
||||
text(order, "resource_type"),
|
||||
"resource_quantity",
|
||||
number(order, "resource_quantity"),
|
||||
"amount",
|
||||
text(order, "sale_amount"),
|
||||
"refunded_amount",
|
||||
text(order, "refunded_amount"))),
|
||||
"status",
|
||||
"PENDING",
|
||||
"next_attempt_at",
|
||||
now()));
|
||||
}
|
||||
|
||||
public String encode(Object value) {
|
||||
try {
|
||||
return json.writeValueAsString(value);
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalArgumentException("业务数据序列化失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.tron.common.crypto.ECKey;
|
||||
import org.tron.trident.crypto.Hash;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
|
||||
/** 应用、节点、公开钱包和不可变套餐版本的生命周期。绝不接收TRON私钥。 */
|
||||
@Service
|
||||
public class RentalProvisioning {
|
||||
private final RentalStore store;
|
||||
private final RentalOrders orders;
|
||||
|
||||
@Value("${rental.domain:localhost}")
|
||||
private String domain;
|
||||
|
||||
public RentalProvisioning(RentalStore store, RentalOrders orders) {
|
||||
this.store = store;
|
||||
this.orders = orders;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public long create(String type, Map<String, Object> request, long actor) {
|
||||
Map<String, Object> row;
|
||||
if ("app".equals(type)) {
|
||||
String url = text(request, "notify_url");
|
||||
if (!url.isEmpty()) {
|
||||
RentalHttp.checkUrl(url);
|
||||
}
|
||||
row =
|
||||
map(
|
||||
"user_id",
|
||||
actor,
|
||||
"name",
|
||||
input(request, "name", 100),
|
||||
"status",
|
||||
"ACTIVE",
|
||||
"notify_url",
|
||||
url.isEmpty() ? null : url);
|
||||
} else if ("node".equals(type)) {
|
||||
row =
|
||||
map(
|
||||
"user_id",
|
||||
actor,
|
||||
"node_no",
|
||||
id("NODE"),
|
||||
"name",
|
||||
input(request, "name", 100),
|
||||
"agent_version",
|
||||
"1.0.0",
|
||||
"status",
|
||||
"PENDING",
|
||||
"created_by",
|
||||
actor);
|
||||
} else if ("wallet".equals(type)) {
|
||||
long nodeId = number(request, "node_id");
|
||||
Map<String, Object> node = store.get("node", nodeId, true);
|
||||
require(
|
||||
number(node, "user_id") == actor && !"REVOKED".equals(text(node, "status")),
|
||||
"无节点权限");
|
||||
String address = input(request, "address", 64);
|
||||
RentalOrders.address(address);
|
||||
row =
|
||||
map(
|
||||
"node_id",
|
||||
nodeId,
|
||||
"network",
|
||||
network(input(request, "network", 16)),
|
||||
"address",
|
||||
address,
|
||||
"status",
|
||||
"PENDING");
|
||||
} else {
|
||||
throw new IllegalArgumentException("未知创建类型");
|
||||
}
|
||||
long id = store.insert(type, row);
|
||||
store.event(type.toUpperCase(Locale.ROOT), id, "CREATE", actor, "租赁业务注册");
|
||||
return id;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public long product(Map<String, Object> request, long actor) {
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
for (String key :
|
||||
Arrays.asList(
|
||||
"package_code",
|
||||
"revision",
|
||||
"name",
|
||||
"network",
|
||||
"resource_type",
|
||||
"resource_quantity",
|
||||
"redundancy_percent",
|
||||
"duration_seconds",
|
||||
"sale_amount",
|
||||
"supplier_amount",
|
||||
"supplier_fee_percent",
|
||||
"fee_limit_sun",
|
||||
"rules")) {
|
||||
require(request.containsKey(key), "缺少套餐字段:" + key);
|
||||
row.put(key, request.get(key));
|
||||
}
|
||||
input(row, "package_code", 32);
|
||||
input(row, "name", 100);
|
||||
require(number(row, "revision") > 0, "版本必须为正整数");
|
||||
if (!(row.get("rules") instanceof String)) {
|
||||
row.put("rules", orders.encode(row.get("rules")));
|
||||
}
|
||||
row.put("delegate_lock", 0);
|
||||
row.put("status", "DISABLED");
|
||||
RentalOrders.validatePackage(row);
|
||||
Map<String, Object> previous =
|
||||
store.one(
|
||||
"SELECT * FROM rent_package WHERE package_code=? ORDER BY revision DESC"
|
||||
+ " LIMIT 1 FOR UPDATE",
|
||||
row.get("package_code"));
|
||||
if (previous != null) {
|
||||
require(
|
||||
text(previous, "resource_type").equals(text(row, "resource_type"))
|
||||
&& number(row, "revision") > number(previous, "revision"),
|
||||
"同套餐资源类型不可变且版本必须递增");
|
||||
}
|
||||
long id = store.insert("package", row);
|
||||
store.event("PACKAGE", id, "CREATE_VERSION", actor, "新增不可变价格版本");
|
||||
return id;
|
||||
}
|
||||
|
||||
public Map<String, Object> ownedWallet(long id, long actor, boolean lock) {
|
||||
Map<String, Object> wallet = store.get("wallet", id, lock);
|
||||
Map<String, Object> node = store.get("node", number(wallet, "node_id"), false);
|
||||
require(number(node, "user_id") == actor, "无钱包权限");
|
||||
return wallet;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Map<String, Object> challenge(long id, long actor) {
|
||||
Map<String, Object> wallet = ownedWallet(id, actor, true);
|
||||
String nonce = RentalCrypto.random();
|
||||
String message =
|
||||
"TRON RENTAL WALLET OWNERSHIP V1\nDomain: "
|
||||
+ domain
|
||||
+ "\nPurpose: bind rental wallet only; not a transaction"
|
||||
+ "\nUser: "
|
||||
+ actor
|
||||
+ "\nWallet: "
|
||||
+ id
|
||||
+ "\nNetwork: "
|
||||
+ text(wallet, "network")
|
||||
+ "\nAddress: "
|
||||
+ text(wallet, "address")
|
||||
+ "\nNonce: "
|
||||
+ nonce
|
||||
+ "\nIssued: "
|
||||
+ now()
|
||||
+ "Z\nExpires: "
|
||||
+ after(300)
|
||||
+ "Z";
|
||||
store.update(
|
||||
"wallet",
|
||||
id,
|
||||
map(
|
||||
"ownership_method",
|
||||
"TRONLINK_SIGN_MESSAGE_V2",
|
||||
"ownership_challenge",
|
||||
nonce,
|
||||
"ownership_message",
|
||||
message,
|
||||
"challenge_issued_at",
|
||||
now(),
|
||||
"challenge_expires_at",
|
||||
after(300),
|
||||
"challenge_consumed_at",
|
||||
null));
|
||||
return map("message", message, "nonce", nonce);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void prove(long id, String nonce, String signature, long actor) {
|
||||
Map<String, Object> wallet = ownedWallet(id, actor, true);
|
||||
require(
|
||||
nonce.equals(text(wallet, "ownership_challenge"))
|
||||
&& wallet.get("challenge_consumed_at") == null
|
||||
&& wallet.get("challenge_expires_at") != null
|
||||
&& time(wallet.get("challenge_expires_at"))
|
||||
.isAfter(java.time.Instant.now()),
|
||||
"挑战已过期或已消费");
|
||||
require(signature.matches("(0x)?[0-9a-fA-F]{130}"), "TronLink消息签名格式无效");
|
||||
try {
|
||||
byte[] message = text(wallet, "ownership_message").getBytes(StandardCharsets.UTF_8);
|
||||
byte[] prefix =
|
||||
("\u0019TRON Signed Message:\n" + message.length)
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
byte[] plain = new byte[prefix.length + message.length];
|
||||
System.arraycopy(prefix, 0, plain, 0, prefix.length);
|
||||
System.arraycopy(message, 0, plain, prefix.length, message.length);
|
||||
byte[] sig =
|
||||
org.bouncycastle.util.encoders.Hex.decode(signature.replaceFirst("^0x", ""));
|
||||
int v = sig[64] & 255;
|
||||
if (v < 27) {
|
||||
v += 27;
|
||||
}
|
||||
byte[] compact = new byte[65];
|
||||
compact[0] = (byte) v;
|
||||
System.arraycopy(sig, 0, compact, 1, 64);
|
||||
byte[] address =
|
||||
ECKey.signatureToAddress(
|
||||
Hash.sha3(plain),
|
||||
java.util.Base64.getEncoder().encodeToString(compact));
|
||||
String recovered = org.tron.trident.utils.Base58Check.bytesToBase58(address);
|
||||
require(text(wallet, "address").equals(recovered), "恢复地址与钱包不符");
|
||||
store.update(
|
||||
"wallet",
|
||||
id,
|
||||
map(
|
||||
"ownership_signature",
|
||||
signature,
|
||||
"ownership_verified_address",
|
||||
recovered,
|
||||
"ownership_verified_at",
|
||||
now(),
|
||||
"challenge_consumed_at",
|
||||
now(),
|
||||
"ownership_evidence",
|
||||
orders.encode(
|
||||
map(
|
||||
"message_hash",
|
||||
RentalCrypto.sha256(text(wallet, "ownership_message")),
|
||||
"recovered",
|
||||
recovered))));
|
||||
} catch (IllegalArgumentException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalArgumentException("TronLink签名验证失败");
|
||||
}
|
||||
store.event("WALLET", id, "OWNERSHIP_VERIFIED", actor, "一次性离线消息验证成功,尚需审核与链上权限检查");
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void status(String type, long id, String status, long actor, String reason) {
|
||||
Map<String, Object> row = store.get(type, id, true);
|
||||
Map<String, Object> changes = map("status", status);
|
||||
if ("node".equals(type)) {
|
||||
require(Arrays.asList("ACTIVE", "PAUSED", "REVOKED").contains(status), "节点状态非法");
|
||||
if ("ACTIVE".equals(status)) {
|
||||
require(number(row, "created_by") != actor, "节点不能自审");
|
||||
changes.put("approved_by", actor);
|
||||
changes.put("approved_at", now());
|
||||
}
|
||||
} else if ("wallet".equals(type)) {
|
||||
require(Arrays.asList("ACTIVE", "PAUSED").contains(status), "钱包状态非法");
|
||||
require(
|
||||
!"ACTIVE".equals(status) || row.get("ownership_verified_at") != null,
|
||||
"钱包尚未完成TronLink验证");
|
||||
} else if ("package".equals(type)) {
|
||||
require(Arrays.asList("ACTIVE", "DISABLED").contains(status), "套餐状态非法");
|
||||
RentalOrders.validatePackage(row);
|
||||
} else if ("app".equals(type) || "account".equals(type)) {
|
||||
require(
|
||||
("app".equals(type)
|
||||
? Arrays.asList("ACTIVE", "DISABLED")
|
||||
: Arrays.asList("ACTIVE", "FROZEN"))
|
||||
.contains(status),
|
||||
"业务状态非法");
|
||||
} else {
|
||||
throw new IllegalArgumentException("该资源不支持直接修改状态");
|
||||
}
|
||||
store.update(type, id, changes);
|
||||
store.event(type.toUpperCase(Locale.ROOT), id, "STATUS", actor, reason);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void policy(long id, Map<String, Object> request, long actor) {
|
||||
ownedWallet(id, actor, true);
|
||||
Map<String, Object> changes = new LinkedHashMap<>();
|
||||
for (String type : Arrays.asList("energy", "bandwidth")) {
|
||||
long enabled = number(request, type + "_enabled"),
|
||||
retain = number(request, type + "_retain_sun");
|
||||
require((enabled == 0 || enabled == 1) && retain >= 0, "钱包出租开关或留存本金无效");
|
||||
changes.put(type + "_enabled", enabled);
|
||||
changes.put(type + "_retain_sun", retain);
|
||||
}
|
||||
store.update("wallet", id, changes);
|
||||
store.event("WALLET", id, "POLICY", actor, "供应商修改平台侧出租约束;不能替代本地广播授权");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/** 查询层显式沿关联关系确定用户归属,绝不对没有user_id的表直接拼用户过滤。 */
|
||||
@Service
|
||||
public class RentalQueries {
|
||||
private final RentalStore store;
|
||||
|
||||
public RentalQueries(RentalStore store) {
|
||||
this.store = store;
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> list(String type, Long user, int page) {
|
||||
String table = store.table(type);
|
||||
String where = "1=1";
|
||||
List<Object> args = new ArrayList<>();
|
||||
if (user != null) {
|
||||
switch (type) {
|
||||
case "app":
|
||||
case "node":
|
||||
case "account":
|
||||
where = "r.user_id=?";
|
||||
break;
|
||||
case "package":
|
||||
where = "r.status='ACTIVE'";
|
||||
break;
|
||||
case "wallet":
|
||||
where =
|
||||
"EXISTS(SELECT 1 FROM rent_node n WHERE n.id=r.node_id AND"
|
||||
+ " n.user_id=?)";
|
||||
break;
|
||||
case "order":
|
||||
where =
|
||||
"EXISTS(SELECT 1 FROM rent_app a WHERE a.id=r.app_id AND a.user_id=?)"
|
||||
+ " OR r.supplier_user_id=?";
|
||||
break;
|
||||
case "task":
|
||||
where =
|
||||
"EXISTS(SELECT 1 FROM rent_node n WHERE n.id=r.node_id AND"
|
||||
+ " n.user_id=?)";
|
||||
break;
|
||||
case "ledger":
|
||||
case "settlement":
|
||||
where =
|
||||
"EXISTS(SELECT 1 FROM rent_account a WHERE a.id=r.account_id AND"
|
||||
+ " a.user_id=?)";
|
||||
break;
|
||||
case "refund":
|
||||
where =
|
||||
"EXISTS(SELECT 1 FROM rent_order o JOIN rent_app a ON a.id=o.app_id"
|
||||
+ " WHERE o.id=r.order_id AND a.user_id=?)";
|
||||
break;
|
||||
case "credential":
|
||||
where =
|
||||
"(r.owner_type='APP' AND EXISTS(SELECT 1 FROM rent_app a WHERE"
|
||||
+ " a.id=r.owner_id AND a.user_id=?)) OR (r.owner_type='NODE' AND"
|
||||
+ " EXISTS(SELECT 1 FROM rent_node n WHERE n.id=r.owner_id AND"
|
||||
+ " n.user_id=?))";
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException("该资源仅限运营查询");
|
||||
}
|
||||
if (!"package".equals(type)) {
|
||||
args.add(user);
|
||||
}
|
||||
if ("order".equals(type) || "credential".equals(type)) {
|
||||
args.add(user);
|
||||
}
|
||||
}
|
||||
require(page > 0 && page <= 10000, "页码不合法");
|
||||
args.add((page - 1) * 50);
|
||||
List<Map<String, Object>> rows =
|
||||
store.rows(
|
||||
"SELECT r.* FROM "
|
||||
+ table
|
||||
+ " r WHERE ("
|
||||
+ where
|
||||
+ ") ORDER BY r.id DESC LIMIT 50 OFFSET ?",
|
||||
args.toArray());
|
||||
for (Map<String, Object> row : rows) {
|
||||
row.remove("api_secret");
|
||||
row.remove("ownership_signature");
|
||||
row.remove("ownership_challenge");
|
||||
row.remove("ownership_message");
|
||||
row.remove("signature");
|
||||
row.remove("nonce");
|
||||
if (user != null && "order".equals(type)) {
|
||||
for (String field :
|
||||
Arrays.asList(
|
||||
"package_snapshot",
|
||||
"supplier_amount",
|
||||
"supplier_fee_percent",
|
||||
"supplier_fee_amount",
|
||||
"supplier_net_amount")) {
|
||||
row.remove(field);
|
||||
}
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Isolation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/** 账账核对只报告差异,不自动改余额或释放未知本金;同一可重复读快照避免正常并发误报。 */
|
||||
@Service
|
||||
public class RentalReconciliation {
|
||||
private final RentalStore store;
|
||||
|
||||
public RentalReconciliation(RentalStore store) {
|
||||
this.store = store;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
|
||||
public Map<String, Object> check(long afterId) {
|
||||
List<Map<String, Object>> accounts =
|
||||
store.rows("SELECT * FROM rent_account WHERE id>? ORDER BY id LIMIT 100", afterId);
|
||||
List<Map<String, Object>> differences = new ArrayList<>();
|
||||
long last = afterId;
|
||||
for (Map<String, Object> account : accounts) {
|
||||
last = number(account, "id");
|
||||
Map<String, Object> sum =
|
||||
store.one(
|
||||
"SELECT COALESCE(SUM(delta_available),0) AS"
|
||||
+ " available_amount,COALESCE(SUM(delta_frozen),0) AS"
|
||||
+ " frozen_amount,COALESCE(SUM(delta_supplier_pending),0) AS"
|
||||
+ " supplier_pending_amount FROM rent_ledger WHERE account_id=?",
|
||||
last);
|
||||
for (String column :
|
||||
Arrays.asList("available_amount", "frozen_amount", "supplier_pending_amount")) {
|
||||
if (amount(account, column).compareTo(amount(sum, column)) != 0
|
||||
|| amount(account, column).signum() < 0) {
|
||||
differences.add(
|
||||
map(
|
||||
"type",
|
||||
"ACCOUNT_LEDGER",
|
||||
"id",
|
||||
last,
|
||||
"field",
|
||||
column,
|
||||
"balance",
|
||||
account.get(column),
|
||||
"ledger_total",
|
||||
sum.get(column)));
|
||||
}
|
||||
}
|
||||
}
|
||||
return map(
|
||||
"checked",
|
||||
accounts.size(),
|
||||
"next_after_id",
|
||||
last,
|
||||
"has_more",
|
||||
accounts.size() == 100,
|
||||
"differences",
|
||||
differences);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
|
||||
public List<Map<String, Object>> reservations() {
|
||||
return store.rows(
|
||||
"SELECT w.id,w.energy_reserved_sun,w.bandwidth_reserved_sun,COALESCE(SUM(CASE WHEN"
|
||||
+ " t.resource_type='ENERGY' THEN t.delegate_sun ELSE 0 END),0) AS"
|
||||
+ " expected_energy,COALESCE(SUM(CASE WHEN t.resource_type='BANDWIDTH' THEN"
|
||||
+ " t.delegate_sun ELSE 0 END),0) AS expected_bandwidth FROM rent_wallet w LEFT"
|
||||
+ " JOIN rent_task t ON t.wallet_id=w.id AND t.reservation_status='HELD' GROUP"
|
||||
+ " BY w.id,w.energy_reserved_sun,w.bandwidth_reserved_sun HAVING"
|
||||
+ " w.energy_reserved_sun<>expected_energy OR"
|
||||
+ " w.bandwidth_reserved_sun<>expected_bandwidth LIMIT 100");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.server.ServerHttpRequest;
|
||||
import org.springframework.http.server.ServerHttpResponse;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
|
||||
/** 租赁响应保留BIGINT/USDT精度,DATETIME按UTC输出,避免浏览器Number和全局支付时区影响。 */
|
||||
@ControllerAdvice(basePackageClasses = RentalController.class)
|
||||
public class RentalResponse implements ResponseBodyAdvice<Object> {
|
||||
@Override
|
||||
public boolean supports(
|
||||
MethodParameter method, Class<? extends HttpMessageConverter<?>> converter) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object beforeBodyWrite(
|
||||
Object body,
|
||||
MethodParameter method,
|
||||
MediaType mediaType,
|
||||
Class<? extends HttpMessageConverter<?>> converter,
|
||||
ServerHttpRequest request,
|
||||
ServerHttpResponse response) {
|
||||
// 凭证只展示一次;同时禁止浏览器、代理和中间缓存保存资金及密钥响应。
|
||||
response.getHeaders().set("Cache-Control", "no-store");
|
||||
return convert(body);
|
||||
}
|
||||
|
||||
private Object convert(Object value) {
|
||||
if (value instanceof Long || value instanceof BigDecimal) {
|
||||
return value.toString();
|
||||
}
|
||||
if (value instanceof Timestamp || value instanceof LocalDateTime) {
|
||||
return RentalValues.time(value).toString();
|
||||
}
|
||||
if (value instanceof Map) {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
((Map<?, ?>) value).forEach((key, item) -> result.put(key.toString(), convert(item)));
|
||||
return result;
|
||||
}
|
||||
if (value instanceof Collection) {
|
||||
List<Object> result = new ArrayList<>();
|
||||
for (Object item : (Collection<?>) value) {
|
||||
result.add(convert(item));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
|
||||
/** 人工退款及结算审批;审批者与发起者分离,付款未知绝不释放来源。 */
|
||||
@Service
|
||||
public class RentalReviews {
|
||||
private final RentalStore store;
|
||||
private final RentalFunds funds;
|
||||
private final RentalOrders orders;
|
||||
|
||||
public RentalReviews(RentalStore store, RentalFunds funds, RentalOrders orders) {
|
||||
this.store = store;
|
||||
this.funds = funds;
|
||||
this.orders = orders;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public long refund(long orderId, Map<String, Object> request, long actor) {
|
||||
Map<String, Object> order = store.get("order", orderId, true);
|
||||
require("CHARGED".equals(text(order, "fund_status")), "冻结订单只能释放,不能退款");
|
||||
String requestNo = input(request, "request_no", 64);
|
||||
String reason = input(request, "reason", 512);
|
||||
BigDecimal refund = money(request.get("refund_amount"));
|
||||
BigDecimal reverse = money(request.get("supplier_reverse_amount"));
|
||||
BigDecimal fee = money(request.get("platform_fee_reverse_amount"));
|
||||
String target = input(request, "fee_return_to", 16);
|
||||
require(
|
||||
refund.signum() > 0
|
||||
&& reverse.signum() >= 0
|
||||
&& fee.signum() >= 0
|
||||
&& Arrays.asList("NONE", "MERCHANT", "SUPPLIER").contains(target)
|
||||
&& ((fee.signum() == 0 && "NONE".equals(target))
|
||||
|| (fee.signum() > 0 && !"NONE".equals(target)))
|
||||
&& (!"MERCHANT".equals(target) || fee.compareTo(refund) <= 0),
|
||||
"退款或费用承担参数无效");
|
||||
String hash =
|
||||
RentalCrypto.sha256(
|
||||
orders.encode(
|
||||
map(
|
||||
"amount", refund, "reverse", reverse, "fee", fee, "to",
|
||||
target, "reason", reason)));
|
||||
Map<String, Object> existing =
|
||||
store.one(
|
||||
"SELECT * FROM rent_refund WHERE order_id=? AND request_no=?",
|
||||
orderId,
|
||||
requestNo);
|
||||
if (existing != null) {
|
||||
require(hash.equals(text(existing, "request_hash")), "退款幂等参数冲突");
|
||||
return number(existing, "id");
|
||||
}
|
||||
return store.insert(
|
||||
"refund",
|
||||
map(
|
||||
"refund_no",
|
||||
id("RF"),
|
||||
"order_id",
|
||||
orderId,
|
||||
"request_no",
|
||||
requestNo,
|
||||
"request_hash",
|
||||
hash,
|
||||
"refund_amount",
|
||||
refund,
|
||||
"supplier_reverse_amount",
|
||||
reverse,
|
||||
"platform_fee_reverse_amount",
|
||||
fee,
|
||||
"fee_return_to",
|
||||
target,
|
||||
"created_by",
|
||||
actor,
|
||||
"status",
|
||||
"PENDING",
|
||||
"reason",
|
||||
reason));
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void approveRefund(long id, boolean approve, long actor) {
|
||||
// 先订单后退款,统一与结算来源的锁顺序;不先持有退款锁等待订单。
|
||||
Map<String, Object> initial = store.get("refund", id, false);
|
||||
long orderId = number(initial, "order_id");
|
||||
Map<String, Object> order = store.get("order", orderId, true);
|
||||
Map<String, Object> refund = store.get("refund", id, true);
|
||||
if ("APPLIED".equals(text(refund, "status")) && approve) {
|
||||
return;
|
||||
}
|
||||
require(
|
||||
"PENDING".equals(text(refund, "status")) && number(refund, "created_by") != actor,
|
||||
"退款状态或审批人不合法");
|
||||
if (!approve) {
|
||||
store.update("refund", id, map("status", "REJECTED", "approved_by", actor));
|
||||
return;
|
||||
}
|
||||
require("CHARGED".equals(text(order, "fund_status")), "订单尚未确认收入");
|
||||
BigDecimal value = amount(refund, "refund_amount");
|
||||
BigDecimal reverse = amount(refund, "supplier_reverse_amount");
|
||||
BigDecimal fee = amount(refund, "platform_fee_reverse_amount");
|
||||
BigDecimal refunded = amount(order, "refunded_amount").add(value);
|
||||
BigDecimal reversed = amount(order, "supplier_reversed_amount").add(reverse);
|
||||
BigDecimal feeReversed = amount(order, "supplier_fee_reversed_amount").add(fee);
|
||||
require(
|
||||
refunded.compareTo(amount(order, "sale_amount")) <= 0
|
||||
&& reversed.compareTo(amount(order, "supplier_net_amount")) <= 0
|
||||
&& feeReversed.compareTo(amount(order, "supplier_fee_amount")) <= 0,
|
||||
"累计退款或冲正超限");
|
||||
BigDecimal returned = "SUPPLIER".equals(text(refund, "fee_return_to")) ? fee : ZERO;
|
||||
if (reverse.signum() > 0 || returned.signum() > 0) {
|
||||
require(
|
||||
store.one(
|
||||
"SELECT id FROM rent_settlement_item WHERE order_id=? AND"
|
||||
+ " active_slot=1",
|
||||
orderId)
|
||||
== null,
|
||||
"订单已被结算占用,不能修改供应商来源;需先明确未付款并拒绝结算");
|
||||
}
|
||||
long payer = number(order, "payer_account_id"),
|
||||
supplier = number(order, "supplier_account_id");
|
||||
funds.lock(payer, supplier);
|
||||
funds.post(
|
||||
payer,
|
||||
"REFUND:" + id,
|
||||
"REFUND",
|
||||
value,
|
||||
ZERO,
|
||||
ZERO,
|
||||
ZERO,
|
||||
orderId,
|
||||
null,
|
||||
id,
|
||||
actor,
|
||||
null,
|
||||
text(refund, "reason"));
|
||||
if (reverse.signum() > 0) {
|
||||
funds.post(
|
||||
supplier,
|
||||
"REVERSAL:" + id + ":NET",
|
||||
"REVERSAL",
|
||||
ZERO,
|
||||
ZERO,
|
||||
reverse.negate(),
|
||||
ZERO,
|
||||
orderId,
|
||||
null,
|
||||
id,
|
||||
actor,
|
||||
null,
|
||||
text(refund, "reason"));
|
||||
}
|
||||
if (fee.signum() > 0) {
|
||||
funds.post(
|
||||
supplier,
|
||||
"REVERSAL:" + id + ":FEE",
|
||||
"REVERSAL",
|
||||
ZERO,
|
||||
ZERO,
|
||||
returned,
|
||||
fee.negate(),
|
||||
orderId,
|
||||
null,
|
||||
id,
|
||||
actor,
|
||||
null,
|
||||
text(refund, "reason"));
|
||||
}
|
||||
store.update(
|
||||
"order",
|
||||
orderId,
|
||||
map(
|
||||
"refunded_amount",
|
||||
refunded,
|
||||
"supplier_reversed_amount",
|
||||
reversed,
|
||||
"supplier_fee_reversed_amount",
|
||||
feeReversed,
|
||||
"supplier_fee_returned_amount",
|
||||
amount(order, "supplier_fee_returned_amount").add(returned)));
|
||||
store.update(
|
||||
"refund", id, map("status", "APPLIED", "approved_by", actor, "applied_at", now()));
|
||||
orders.webhook(
|
||||
store.get("order", orderId, false),
|
||||
"REFUNDED",
|
||||
"REFUND:" + text(refund, "refund_no"));
|
||||
store.event("REFUND", id, "APPLY", actor, text(refund, "reason"));
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public long settlement(List<Long> orderIds, long actor) {
|
||||
require(orderIds != null && !orderIds.isEmpty() && orderIds.size() <= 100, "选择1至100笔订单");
|
||||
SortedSet<Long> sorted = new TreeSet<>(orderIds);
|
||||
require(sorted.size() == orderIds.size(), "不能重复选择来源");
|
||||
List<Map<String, Object>> sources = new ArrayList<>();
|
||||
Long account = null;
|
||||
BigDecimal total = ZERO;
|
||||
for (long orderId : sorted) {
|
||||
Map<String, Object> order = store.get("order", orderId, true);
|
||||
require("CHARGED".equals(text(order, "fund_status")), "来源订单尚未确认收入");
|
||||
long current = number(order, "supplier_account_id");
|
||||
require(account == null || account == current, "只允许同一供应商同网络的来源");
|
||||
account = current;
|
||||
BigDecimal net =
|
||||
amount(order, "supplier_net_amount")
|
||||
.subtract(amount(order, "supplier_reversed_amount"))
|
||||
.add(amount(order, "supplier_fee_returned_amount"));
|
||||
require(net.signum() > 0, "来源无可结算金额");
|
||||
sources.add(map("order_id", orderId, "amount", net));
|
||||
total = total.add(net);
|
||||
}
|
||||
long id =
|
||||
store.insert(
|
||||
"settlement",
|
||||
map(
|
||||
"settlement_no",
|
||||
id("ST"),
|
||||
"account_id",
|
||||
account,
|
||||
"amount",
|
||||
total,
|
||||
"status",
|
||||
"PENDING",
|
||||
"created_by",
|
||||
actor));
|
||||
for (Map<String, Object> source : sources) {
|
||||
source.put("settlement_id", id);
|
||||
source.put("active_slot", 1);
|
||||
store.insert("settlement_item", source);
|
||||
}
|
||||
store.event("SETTLEMENT", id, "CREATE", actor, "占用订单净应收来源");
|
||||
return id;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Map<String, Object> transition(long id, String action, long actor, String reason) {
|
||||
Map<String, Object> row = store.get("settlement", id, true);
|
||||
String state = text(row, "status");
|
||||
if ("approve".equals(action)) {
|
||||
require("PENDING".equals(state) && number(row, "created_by") != actor, "审批须职责分离");
|
||||
store.update(
|
||||
"settlement",
|
||||
id,
|
||||
map("status", "APPROVED", "approved_by", actor, "remark", reason));
|
||||
} else if ("pay".equals(action)) {
|
||||
if ("PAYING".equals(state) || "UNKNOWN".equals(state)) {
|
||||
return row;
|
||||
}
|
||||
require("APPROVED".equals(state), "必须先审批再领取付款授权");
|
||||
store.update(
|
||||
"settlement",
|
||||
id,
|
||||
map(
|
||||
"status",
|
||||
"PAYING",
|
||||
"payout_no",
|
||||
RentalValues.id("PAY"),
|
||||
"payment_started_at",
|
||||
now()));
|
||||
} else if ("unknown".equals(action)) {
|
||||
require("PAYING".equals(state), "仅付款中可转待核对");
|
||||
store.update("settlement", id, map("status", "UNKNOWN", "remark", reason));
|
||||
} else if ("reject".equals(action)) {
|
||||
require("PENDING".equals(state) || "APPROVED".equals(state), "付款中或未知不能释放来源");
|
||||
store.update("settlement", id, map("status", "REJECTED", "remark", reason));
|
||||
store.execute(
|
||||
"UPDATE rent_settlement_item SET"
|
||||
+ " active_slot=NULL,version=version+1,updated_at=? WHERE settlement_id=?",
|
||||
now(),
|
||||
id);
|
||||
} else {
|
||||
throw new IllegalArgumentException("未知结算操作");
|
||||
}
|
||||
store.event("SETTLEMENT", id, action.toUpperCase(Locale.ROOT), actor, reason);
|
||||
return store.get("settlement", id, false);
|
||||
}
|
||||
|
||||
/** 由链上只读服务独立核对付款后调用;不接受前端的verified=true作为依据。 */
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void paid(long id, String reference, String evidence, long actor) {
|
||||
Map<String, Object> row = store.get("settlement", id, true);
|
||||
if ("PAID".equals(text(row, "status"))) {
|
||||
require(reference.equals(text(row, "payment_reference")), "付款凭据冲突");
|
||||
return;
|
||||
}
|
||||
require(Arrays.asList("PAYING", "UNKNOWN").contains(text(row, "status")), "未领取付款授权");
|
||||
funds.post(
|
||||
number(row, "account_id"),
|
||||
"SETTLE:" + id,
|
||||
"SETTLE",
|
||||
ZERO,
|
||||
ZERO,
|
||||
amount(row, "amount").negate(),
|
||||
ZERO,
|
||||
null,
|
||||
id,
|
||||
null,
|
||||
actor,
|
||||
reference,
|
||||
"独立核验人工结算付款");
|
||||
store.update(
|
||||
"settlement",
|
||||
id,
|
||||
map(
|
||||
"status",
|
||||
"PAID",
|
||||
"payment_reference",
|
||||
reference,
|
||||
"payment_evidence",
|
||||
evidence,
|
||||
"paid_at",
|
||||
now()));
|
||||
store.event("SETTLEMENT", id, "PAID", actor, reference);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.socket.*;
|
||||
import org.springframework.web.socket.handler.TextWebSocketHandler;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 单入口WSS节点网关。数据库session_epoch为fencing token,旧连接关闭不能覆盖新连接。
|
||||
* Socket只负责可靠交付和线索采集,不执行RPC、不把ACK或RESULT当履约成功。
|
||||
*/
|
||||
@Component
|
||||
@ConditionalOnProperty(name = "rental.enabled", havingValue = "true")
|
||||
public class RentalSocket extends TextWebSocketHandler {
|
||||
private static final String PATH = "/node/v1/socket";
|
||||
private final RentalStore store;
|
||||
private final RentalIdentity identity;
|
||||
private final RentalTasks tasks;
|
||||
private final ObjectMapper json;
|
||||
private final Map<String, Connection> connections = new ConcurrentHashMap<>();
|
||||
private final String instance = id("INSTANCE");
|
||||
|
||||
public RentalSocket(
|
||||
RentalStore store, RentalIdentity identity, RentalTasks tasks, ObjectMapper json) {
|
||||
this.store = store;
|
||||
this.identity = identity;
|
||||
this.tasks = tasks;
|
||||
this.json = json;
|
||||
}
|
||||
|
||||
private static class Connection {
|
||||
WebSocketSession socket;
|
||||
String challenge;
|
||||
String key;
|
||||
String secret;
|
||||
String session;
|
||||
String ping;
|
||||
long node;
|
||||
long epoch;
|
||||
long sent;
|
||||
long received;
|
||||
long pong = System.currentTimeMillis();
|
||||
long opened = System.currentTimeMillis();
|
||||
long window;
|
||||
int count;
|
||||
boolean ready;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
|
||||
if (connections.size() >= 1000) {
|
||||
session.close(CloseStatus.SERVICE_OVERLOAD);
|
||||
return;
|
||||
}
|
||||
session.setTextMessageSizeLimit(65536);
|
||||
Connection c = new Connection();
|
||||
c.socket =
|
||||
new org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator(
|
||||
session, 5000, 262144);
|
||||
c.challenge = RentalCrypto.random();
|
||||
connections.put(session.getId(), c);
|
||||
session.sendMessage(
|
||||
new TextMessage(
|
||||
json.writeValueAsString(
|
||||
map("type", "CHALLENGE", "challenge", c.challenge))));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void handleTextMessage(WebSocketSession socket, TextMessage message)
|
||||
throws Exception {
|
||||
Connection c = connections.get(socket.getId());
|
||||
try {
|
||||
require(c != null && message.getPayloadLength() <= 65536, "连接或帧大小无效");
|
||||
long window = System.currentTimeMillis() / 1000;
|
||||
if (c.window != window) {
|
||||
c.window = window;
|
||||
c.count = 0;
|
||||
}
|
||||
require(++c.count <= 30, "节点发送速率超限");
|
||||
RentalJson.bounded(message.getPayload());
|
||||
Map<String, Object> envelope =
|
||||
json.readValue(
|
||||
message.getPayload(), new TypeReference<Map<String, Object>>() {});
|
||||
String body = input(envelope, "body", 60000);
|
||||
RentalJson.bounded(body);
|
||||
Map<String, Object> frame =
|
||||
json.readValue(body, new TypeReference<Map<String, Object>>() {});
|
||||
String type = input(frame, "type", 24);
|
||||
String key = input(envelope, "api_key", 64);
|
||||
require(
|
||||
c.node != 0
|
||||
|| ("AUTH".equals(type)
|
||||
&& System.currentTimeMillis() - c.opened <= 5000),
|
||||
"未认证连接");
|
||||
Map<String, Object> credential =
|
||||
identity.authenticate(
|
||||
key,
|
||||
"NODE",
|
||||
"NODE",
|
||||
number(envelope, "timestamp"),
|
||||
input(envelope, "nonce", 64),
|
||||
"FRAME",
|
||||
PATH,
|
||||
body,
|
||||
input(envelope, "signature", 64));
|
||||
if (c.node == 0) {
|
||||
require(c.challenge.equals(text(frame, "challenge")), "认证挑战不匹配");
|
||||
long nodeId = number(credential, "owner_id");
|
||||
tasks.tx(
|
||||
() -> {
|
||||
Map<String, Object> node = store.get("node", nodeId, true);
|
||||
require(
|
||||
Arrays.asList("ACTIVE", "PAUSED").contains(text(node, "status"))
|
||||
&& text(node, "node_no").equals(text(frame, "node_no")),
|
||||
"节点未审核或已吊销");
|
||||
c.node = nodeId;
|
||||
c.epoch = Math.addExact(number(node, "session_epoch"), 1);
|
||||
c.session = id("SESSION");
|
||||
c.key = key;
|
||||
c.secret = identity.secret(credential);
|
||||
store.update(
|
||||
"node",
|
||||
nodeId,
|
||||
map(
|
||||
"session_id",
|
||||
c.session,
|
||||
"session_epoch",
|
||||
c.epoch,
|
||||
"server_instance_id",
|
||||
instance,
|
||||
"connection_status",
|
||||
"SYNCING",
|
||||
"connected_at",
|
||||
now(),
|
||||
"heartbeat_at",
|
||||
now(),
|
||||
"heartbeat_expires_at",
|
||||
after(45),
|
||||
"last_client_sequence",
|
||||
0));
|
||||
return null;
|
||||
});
|
||||
for (Connection other : connections.values()) {
|
||||
if (other != c && other.node == c.node) {
|
||||
other.socket.close(CloseStatus.POLICY_VIOLATION);
|
||||
}
|
||||
}
|
||||
send(c, "AUTH_OK", map("challenge", c.challenge, "heartbeat_seconds", 15));
|
||||
return;
|
||||
}
|
||||
require(
|
||||
key.equals(c.key)
|
||||
&& "CLIENT".equals(text(frame, "direction"))
|
||||
&& c.session.equals(text(frame, "session_id"))
|
||||
&& number(frame, "session_epoch") == c.epoch
|
||||
&& number(frame, "sequence") == c.received + 1,
|
||||
"过期会话或帧序号错误");
|
||||
require(
|
||||
store.execute(
|
||||
"UPDATE rent_node SET"
|
||||
+ " last_client_sequence=?,version=version+1,updated_at=?"
|
||||
+ " WHERE id=? AND session_epoch=? AND"
|
||||
+ " last_client_sequence=? AND status<>'REVOKED'",
|
||||
c.received + 1,
|
||||
now(),
|
||||
c.node,
|
||||
c.epoch,
|
||||
c.received)
|
||||
== 1,
|
||||
"会话已被替换");
|
||||
c.received++;
|
||||
Object payloadValue = frame.get("payload");
|
||||
require(payloadValue instanceof Map, "缺少消息内容");
|
||||
Map<String, Object> payload = (Map<String, Object>) payloadValue;
|
||||
if ("PING".equals(type)) {
|
||||
send(c, "PONG", map("ping_id", text(frame, "message_id")));
|
||||
} else if ("PONG".equals(type)) {
|
||||
require(c.ping != null && c.ping.equals(text(payload, "ping_id")), "PONG不匹配");
|
||||
c.ping = null;
|
||||
c.pong = System.currentTimeMillis();
|
||||
store.execute(
|
||||
"UPDATE rent_node SET"
|
||||
+ " heartbeat_at=?,heartbeat_expires_at=?,version=version+1,updated_at=?"
|
||||
+ " WHERE id=? AND session_epoch=?",
|
||||
now(),
|
||||
after(45),
|
||||
now(),
|
||||
c.node,
|
||||
c.epoch);
|
||||
} else if ("SYNC_STATE".equals(type)) {
|
||||
Object events = payload.get("events");
|
||||
if (events instanceof List) {
|
||||
require(((List<?>) events).size() <= 100, "单次恢复事件超限");
|
||||
for (Object event : (List<?>) events) {
|
||||
tasks.report(c.node, (Map<String, Object>) event);
|
||||
}
|
||||
}
|
||||
send(
|
||||
c,
|
||||
"SYNC_ACK",
|
||||
map("events", events == null ? Collections.emptyList() : events));
|
||||
c.ready = !Boolean.TRUE.equals(payload.get("more"));
|
||||
if (c.ready) {
|
||||
store.execute(
|
||||
"UPDATE rent_node SET"
|
||||
+ " connection_status='ONLINE',version=version+1,updated_at=? WHERE"
|
||||
+ " id=? AND session_epoch=?",
|
||||
now(),
|
||||
c.node,
|
||||
c.epoch);
|
||||
}
|
||||
} else if ("TASK_EVENT".equals(type) && c.ready) {
|
||||
tasks.report(c.node, payload);
|
||||
send(c, "RESULT_ACK", map("event_id", text(payload, "event_id")));
|
||||
} else {
|
||||
throw new IllegalArgumentException("消息不允许或尚未同步");
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
// 不回传认证材料、Secret、SQL或原始异常,防止日志与网络泄密。
|
||||
socket.close(CloseStatus.POLICY_VIOLATION);
|
||||
}
|
||||
}
|
||||
|
||||
private String send(Connection c, String type, Map<String, Object> payload) throws Exception {
|
||||
synchronized (c) {
|
||||
require(c.socket.isOpen(), "节点连接已关闭");
|
||||
String message = id("MSG");
|
||||
String body =
|
||||
json.writeValueAsString(
|
||||
map(
|
||||
"type",
|
||||
type,
|
||||
"direction",
|
||||
"SERVER",
|
||||
"session_id",
|
||||
c.session,
|
||||
"session_epoch",
|
||||
Long.toString(c.epoch),
|
||||
"sequence",
|
||||
Long.toString(++c.sent),
|
||||
"message_id",
|
||||
message,
|
||||
"payload",
|
||||
payload));
|
||||
long timestamp = System.currentTimeMillis();
|
||||
String nonce = RentalCrypto.random();
|
||||
if ("PING".equals(type)) {
|
||||
c.ping = message;
|
||||
}
|
||||
c.socket.sendMessage(
|
||||
new TextMessage(
|
||||
json.writeValueAsString(
|
||||
map(
|
||||
"api_key",
|
||||
c.key,
|
||||
"timestamp",
|
||||
timestamp,
|
||||
"nonce",
|
||||
nonce,
|
||||
"body",
|
||||
body,
|
||||
"signature",
|
||||
RentalCrypto.sign(
|
||||
c.secret, "NODE", c.key, timestamp, nonce,
|
||||
"FRAME", PATH, body)))));
|
||||
return message;
|
||||
}
|
||||
}
|
||||
|
||||
/** 由有界后台调度调用,同一逻辑任务始终使用相同delivery_message_id和冻结intent。 */
|
||||
public void tick() {
|
||||
for (Connection c : connections.values()) {
|
||||
try {
|
||||
if (c.node == 0) {
|
||||
if (System.currentTimeMillis() - c.opened > 5000) {
|
||||
c.socket.close(CloseStatus.POLICY_VIOLATION);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (System.currentTimeMillis() - c.pong > 45000) {
|
||||
c.socket.close(CloseStatus.SESSION_NOT_RELIABLE);
|
||||
continue;
|
||||
}
|
||||
Map<String, Object> node = store.get("node", c.node, false);
|
||||
if (number(node, "session_epoch") != c.epoch
|
||||
|| "REVOKED".equals(text(node, "status"))) {
|
||||
c.socket.close(CloseStatus.POLICY_VIOLATION);
|
||||
continue;
|
||||
}
|
||||
if (c.ping == null) {
|
||||
send(c, "PING", map());
|
||||
}
|
||||
if (!c.ready) {
|
||||
continue;
|
||||
}
|
||||
for (Map<String, Object> task :
|
||||
store.rows(
|
||||
"SELECT * FROM rent_task WHERE node_id=? AND status IN"
|
||||
+ " ('PENDING','ACCEPTED','UNKNOWN','BROADCASTED') AND"
|
||||
+ " (last_sent_at IS NULL OR last_sent_at<?) ORDER BY id LIMIT"
|
||||
+ " 10",
|
||||
c.node,
|
||||
after(-15))) {
|
||||
Map<String, Object> credential =
|
||||
store.get("credential", number(task, "credential_id"), false);
|
||||
if ("REVOKED".equals(text(credential, "status"))) {
|
||||
continue;
|
||||
}
|
||||
// PAUSED仍核对历史原任务,但不推送尚未接受的首次任务去执行。
|
||||
if (!"ACTIVE".equals(text(node, "status"))
|
||||
&& "PENDING".equals(text(task, "status"))) {
|
||||
continue;
|
||||
}
|
||||
send(
|
||||
c,
|
||||
"TASK_PUSH",
|
||||
map(
|
||||
"task_no",
|
||||
text(task, "task_no"),
|
||||
"delivery_message_id",
|
||||
text(task, "delivery_message_id"),
|
||||
"api_key",
|
||||
text(credential, "api_key"),
|
||||
"intent",
|
||||
json.writeValueAsString(
|
||||
new TreeMap<>(
|
||||
json.readValue(
|
||||
text(task, "intent"), Map.class))),
|
||||
"signature",
|
||||
text(task, "signature"),
|
||||
"timestamp",
|
||||
time(task.get("signed_at")).toEpochMilli(),
|
||||
"nonce",
|
||||
text(task, "nonce")));
|
||||
store.execute(
|
||||
"UPDATE rent_task SET"
|
||||
+ " delivery_count=delivery_count+1,last_sent_at=?,delivery_session_epoch=?,version=version+1,updated_at=?"
|
||||
+ " WHERE id=?",
|
||||
now(),
|
||||
c.epoch,
|
||||
now(),
|
||||
task.get("id"));
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
try {
|
||||
c.socket.close(CloseStatus.SERVER_ERROR);
|
||||
} catch (Exception ignored) {
|
||||
/* 关闭后由epoch保护离线更新。 */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterConnectionClosed(WebSocketSession socket, CloseStatus status) {
|
||||
Connection c = connections.remove(socket.getId());
|
||||
if (c != null && c.node != 0) {
|
||||
store.execute(
|
||||
"UPDATE rent_node SET"
|
||||
+ " connection_status='OFFLINE',disconnected_at=?,version=version+1,updated_at=?"
|
||||
+ " WHERE id=? AND session_epoch=?",
|
||||
now(),
|
||||
now(),
|
||||
c.node,
|
||||
c.epoch);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import org.springframework.scheduling.annotation.SchedulingConfigurer;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
|
||||
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
|
||||
import org.springframework.web.socket.config.annotation.*;
|
||||
|
||||
/** 启用开关默认关闭;正式环境由HTTPS反向代理提供WSS,节点协议另有HMAC认证。 */
|
||||
@Configuration
|
||||
@EnableWebSocket
|
||||
@EnableScheduling
|
||||
@ConditionalOnProperty(name = "rental.enabled", havingValue = "true")
|
||||
public class RentalSocketConfig implements WebSocketConfigurer, SchedulingConfigurer {
|
||||
private final RentalSocket socket;
|
||||
|
||||
public RentalSocketConfig(RentalSocket socket) {
|
||||
this.socket = socket;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
|
||||
registry.addHandler(socket, "/node/v1/socket");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ThreadPoolTaskScheduler rentalTaskScheduler() {
|
||||
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
|
||||
scheduler.setPoolSize(6);
|
||||
scheduler.setThreadNamePrefix("rental-worker-");
|
||||
scheduler.setWaitForTasksToCompleteOnShutdown(true);
|
||||
scheduler.setAwaitTerminationSeconds(30);
|
||||
return scheduler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureTasks(ScheduledTaskRegistrar registrar) {
|
||||
registrar.setTaskScheduler(rentalTaskScheduler());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.support.GeneratedKeyHolder;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.Statement;
|
||||
import java.util.*;
|
||||
|
||||
/** 租赁事务仓储。动态标识符只接受内部白名单,业务值全部使用占位符。 行锁由调用方事务持有;RPC必须在事务外执行,避免占用数据库连接等待链上响应。 */
|
||||
@Repository
|
||||
public class RentalStore {
|
||||
public static final Set<String> TABLES =
|
||||
Collections.unmodifiableSet(
|
||||
new HashSet<>(
|
||||
Arrays.asList(
|
||||
"app",
|
||||
"credential",
|
||||
"nonce",
|
||||
"node",
|
||||
"wallet",
|
||||
"package",
|
||||
"account",
|
||||
"order",
|
||||
"task",
|
||||
"transaction",
|
||||
"ledger",
|
||||
"settlement",
|
||||
"settlement_item",
|
||||
"refund",
|
||||
"webhook",
|
||||
"event")));
|
||||
private final JdbcTemplate jdbc;
|
||||
|
||||
public RentalStore(JdbcTemplate jdbc) {
|
||||
this.jdbc = jdbc;
|
||||
}
|
||||
|
||||
public String table(String name) {
|
||||
require(TABLES.contains(name), "未知租赁资源");
|
||||
return "`rent_" + name + "`";
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> rows(String sql, Object... args) {
|
||||
return jdbc.queryForList(sql, args);
|
||||
}
|
||||
|
||||
public Map<String, Object> one(String sql, Object... args) {
|
||||
List<Map<String, Object>> rows = rows(sql, args);
|
||||
return rows.isEmpty() ? null : rows.get(0);
|
||||
}
|
||||
|
||||
public Map<String, Object> get(String table, long id, boolean lock) {
|
||||
Map<String, Object> row =
|
||||
one(
|
||||
"SELECT * FROM "
|
||||
+ table(table)
|
||||
+ " WHERE id=?"
|
||||
+ (lock ? " FOR UPDATE" : ""),
|
||||
id);
|
||||
require(row != null, "记录不存在");
|
||||
return row;
|
||||
}
|
||||
|
||||
public int execute(String sql, Object... args) {
|
||||
return jdbc.update(sql, args);
|
||||
}
|
||||
|
||||
public long insert(String table, Map<String, Object> data) {
|
||||
Map<String, Object> values = new LinkedHashMap<>(data);
|
||||
values.put("created_at", now());
|
||||
values.put("updated_at", now());
|
||||
values.put("version", 0L);
|
||||
List<String> columns = new ArrayList<>(values.keySet());
|
||||
columns.forEach(this::column);
|
||||
String sql =
|
||||
"INSERT INTO "
|
||||
+ table(table)
|
||||
+ " (`"
|
||||
+ String.join("`,`", columns)
|
||||
+ "`) VALUES ("
|
||||
+ String.join(",", Collections.nCopies(columns.size(), "?"))
|
||||
+ ")";
|
||||
GeneratedKeyHolder holder = new GeneratedKeyHolder();
|
||||
jdbc.update(
|
||||
connection -> {
|
||||
PreparedStatement ps =
|
||||
connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
|
||||
int index = 1;
|
||||
for (Object value : values.values()) {
|
||||
ps.setObject(index++, value);
|
||||
}
|
||||
return ps;
|
||||
},
|
||||
holder);
|
||||
return Objects.requireNonNull(holder.getKey()).longValue();
|
||||
}
|
||||
|
||||
public void update(String table, long id, Map<String, Object> data) {
|
||||
List<Object> args = new ArrayList<>();
|
||||
List<String> setters = new ArrayList<>();
|
||||
data.forEach(
|
||||
(key, value) -> {
|
||||
column(key);
|
||||
setters.add("`" + key + "`=?");
|
||||
args.add(value);
|
||||
});
|
||||
setters.add("version=version+1");
|
||||
setters.add("updated_at=?");
|
||||
args.add(now());
|
||||
args.add(id);
|
||||
require(
|
||||
execute(
|
||||
"UPDATE "
|
||||
+ table(table)
|
||||
+ " SET "
|
||||
+ String.join(",", setters)
|
||||
+ " WHERE id=?",
|
||||
args.toArray())
|
||||
== 1,
|
||||
"记录更新失败");
|
||||
}
|
||||
|
||||
private void column(String value) {
|
||||
require(value.matches("[a-z][a-z0-9_]*"), "非法列名");
|
||||
}
|
||||
|
||||
public void event(String type, long id, String action, long actor, String reason) {
|
||||
insert(
|
||||
"event",
|
||||
map(
|
||||
"event_no",
|
||||
id("EV"),
|
||||
"object_type",
|
||||
type,
|
||||
"object_id",
|
||||
id,
|
||||
"action",
|
||||
action,
|
||||
"actor_user_id",
|
||||
actor,
|
||||
"reason",
|
||||
reason));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,862 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/** 持久任务状态机。数据库事务仅修改事实,所有RPC在事务外完成。 UNKNOWN保留三个占位和冻结资金;租约、断线、超时均不是未执行证据。 */
|
||||
@Service
|
||||
public class RentalTasks {
|
||||
private final RentalStore store;
|
||||
private final RentalChain chain;
|
||||
private final RentalIdentity identity;
|
||||
private final RentalOrders orders;
|
||||
private final RentalFunds funds;
|
||||
private final TransactionTemplate transaction;
|
||||
|
||||
public RentalTasks(
|
||||
RentalStore store,
|
||||
RentalChain chain,
|
||||
RentalIdentity identity,
|
||||
RentalOrders orders,
|
||||
RentalFunds funds,
|
||||
org.springframework.transaction.PlatformTransactionManager manager) {
|
||||
this.store = store;
|
||||
this.chain = chain;
|
||||
this.identity = identity;
|
||||
this.orders = orders;
|
||||
this.funds = funds;
|
||||
this.transaction = new TransactionTemplate(manager);
|
||||
}
|
||||
|
||||
public <T> T tx(Supplier<T> action) {
|
||||
return transaction.execute(status -> action.get());
|
||||
}
|
||||
|
||||
public void refresh(long id) {
|
||||
Map<String, Object> previous = store.get("wallet", id, false);
|
||||
Map<String, Object> snapshot =
|
||||
chain.snapshot(text(previous, "network"), text(previous, "address"));
|
||||
tx(
|
||||
() -> {
|
||||
Map<String, Object> current = store.get("wallet", id, true);
|
||||
require(
|
||||
number(previous, "version") == number(current, "version")
|
||||
&& number(snapshot, "snapshot_block_height")
|
||||
>= number(current, "snapshot_min_block_height")
|
||||
&& (current.get("snapshot_block_height") == null
|
||||
|| number(snapshot, "snapshot_block_height")
|
||||
>= number(current, "snapshot_block_height")),
|
||||
"快照已过时,丢弃并重新查询");
|
||||
store.update("wallet", id, snapshot);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
public void dispatch(long orderId) {
|
||||
Map<String, Object> initial = store.get("order", orderId, false);
|
||||
if (!"WAITING".equals(text(initial, "status"))) {
|
||||
return;
|
||||
}
|
||||
if (!time(initial.get("dispatch_deadline")).isAfter(Instant.now())) {
|
||||
tx(
|
||||
() -> {
|
||||
Map<String, Object> row = store.get("order", orderId, true);
|
||||
if ("WAITING".equals(text(row, "status"))) {
|
||||
require(
|
||||
store.one(
|
||||
"SELECT id FROM rent_task WHERE order_id=? AND"
|
||||
+ " active_slot=1",
|
||||
orderId)
|
||||
== null,
|
||||
"在途任务不可超时释放");
|
||||
funds.release(row);
|
||||
store.update("order", orderId, map("status", "CANCELLED"));
|
||||
orders.webhook(row, "CANCELLED", "ORDER:" + orderId + ":CANCELLED");
|
||||
}
|
||||
return null;
|
||||
});
|
||||
return;
|
||||
}
|
||||
List<Map<String, Object>> candidates =
|
||||
store.rows(
|
||||
"SELECT w.* FROM rent_wallet w JOIN rent_node n ON n.id=w.node_id WHERE"
|
||||
+ " w.status='ACTIVE' AND w.ownership_verified_at IS NOT NULL AND"
|
||||
+ " w.network=? AND w.snapshot_expires_at>? AND n.status='ACTIVE' AND"
|
||||
+ " n.connection_status='ONLINE' AND n.heartbeat_expires_at>? ORDER BY"
|
||||
+ " w.id LIMIT 20",
|
||||
text(initial, "network"),
|
||||
now(),
|
||||
now());
|
||||
for (Map<String, Object> candidate : candidates) {
|
||||
String type = text(initial, "resource_type"), owner = text(candidate, "address");
|
||||
if (owner.equals(text(initial, "receiver_address"))) {
|
||||
continue;
|
||||
}
|
||||
if (chain.relation(
|
||||
text(initial, "network"),
|
||||
owner,
|
||||
text(initial, "receiver_address"),
|
||||
type)
|
||||
!= 0) {
|
||||
continue;
|
||||
}
|
||||
Boolean assigned =
|
||||
tx(
|
||||
() -> {
|
||||
Map<String, Object> order = store.get("order", orderId, true);
|
||||
if (!"WAITING".equals(text(order, "status"))
|
||||
|| !time(order.get("dispatch_deadline"))
|
||||
.isAfter(Instant.now())) {
|
||||
return false;
|
||||
}
|
||||
Map<String, Object> wallet =
|
||||
store.get("wallet", number(candidate, "id"), true);
|
||||
if (number(wallet, "version") != number(candidate, "version")) {
|
||||
return false;
|
||||
}
|
||||
Map<String, Object> node =
|
||||
store.get("node", number(wallet, "node_id"), true);
|
||||
String prefix = resource(type).toLowerCase(Locale.ROOT);
|
||||
if (!"ACTIVE".equals(text(node, "status"))
|
||||
|| !"ONLINE".equals(text(node, "connection_status"))
|
||||
|| node.get("heartbeat_expires_at") == null
|
||||
|| !time(node.get("heartbeat_expires_at"))
|
||||
.isAfter(Instant.now())
|
||||
|| number(wallet, prefix + "_enabled") != 1
|
||||
|| wallet.get("snapshot_expires_at") == null
|
||||
|| !time(wallet.get("snapshot_expires_at"))
|
||||
.isAfter(Instant.now())
|
||||
|| number(wallet, "snapshot_block_height")
|
||||
< number(wallet, "snapshot_min_block_height")) {
|
||||
return false;
|
||||
}
|
||||
if (store.one(
|
||||
"SELECT id FROM rent_task WHERE wallet_id=?"
|
||||
+ " AND resource_type=? AND"
|
||||
+ " wallet_execution_slot=1",
|
||||
wallet.get("id"),
|
||||
type)
|
||||
!= null
|
||||
|| store.one(
|
||||
"SELECT id FROM rent_order WHERE"
|
||||
+ " wallet_id=? AND receiver_address=?"
|
||||
+ " AND resource_type=? AND"
|
||||
+ " relation_slot=1",
|
||||
wallet.get("id"),
|
||||
order.get("receiver_address"),
|
||||
type)
|
||||
!= null) {
|
||||
return false;
|
||||
}
|
||||
long limit = number(wallet, "total_" + prefix + "_limit"),
|
||||
weight = number(wallet, "total_" + prefix + "_weight");
|
||||
long sun =
|
||||
principal(
|
||||
number(order, "target_resource_quantity"),
|
||||
limit,
|
||||
weight);
|
||||
long available =
|
||||
Math.subtractExact(
|
||||
Math.subtractExact(
|
||||
number(wallet, prefix + "_delegatable_sun"),
|
||||
number(wallet, prefix + "_reserved_sun")),
|
||||
number(wallet, prefix + "_retain_sun"));
|
||||
if (sun > available) {
|
||||
return false;
|
||||
}
|
||||
Map<String, Object> supplier =
|
||||
funds.account(
|
||||
number(node, "user_id"), text(order, "network"));
|
||||
require("ACTIVE".equals(text(supplier, "status")), "供应商资金账户冻结");
|
||||
store.update(
|
||||
"wallet",
|
||||
number(wallet, "id"),
|
||||
map(
|
||||
prefix + "_reserved_sun",
|
||||
Math.addExact(
|
||||
number(wallet, prefix + "_reserved_sun"),
|
||||
sun)));
|
||||
store.update(
|
||||
"order",
|
||||
orderId,
|
||||
map(
|
||||
"status",
|
||||
"EXECUTING",
|
||||
"wallet_id",
|
||||
wallet.get("id"),
|
||||
"supplier_user_id",
|
||||
node.get("user_id"),
|
||||
"supplier_account_id",
|
||||
supplier.get("id"),
|
||||
"relation_slot",
|
||||
1));
|
||||
createTask(order, wallet, "DELEGATE", sun, limit, weight, null);
|
||||
store.event(
|
||||
"ORDER", orderId, "DISPATCH", 0, "预留对应资源SUN并取得地址对和执行占位");
|
||||
return true;
|
||||
});
|
||||
if (Boolean.TRUE.equals(assigned)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void createTask(
|
||||
Map<String, Object> order,
|
||||
Map<String, Object> wallet,
|
||||
String type,
|
||||
long sun,
|
||||
long limit,
|
||||
long weight,
|
||||
Map<String, Object> source) {
|
||||
long nodeId = number(wallet, "node_id"), orderId = number(order, "id");
|
||||
Map<String, Object> credential =
|
||||
store.one(
|
||||
"SELECT * FROM rent_credential WHERE owner_type='NODE' AND owner_id=? AND"
|
||||
+ " status='ACTIVE' AND (expires_at IS NULL OR expires_at>?) ORDER BY"
|
||||
+ " id DESC LIMIT 1",
|
||||
nodeId,
|
||||
now());
|
||||
require(credential != null, "节点缺少有效凭证");
|
||||
Map<String, Object> last =
|
||||
store.one(
|
||||
"SELECT COALESCE(MAX(attempt_no),0) AS attempt FROM rent_task WHERE"
|
||||
+ " order_id=? AND task_type=?",
|
||||
orderId,
|
||||
type);
|
||||
long attempt = number(last, "attempt") + 1;
|
||||
String taskNo = id("RT"), nonce = RentalCrypto.random();
|
||||
long signed = System.currentTimeMillis();
|
||||
java.time.LocalDateTime deadline =
|
||||
"DELEGATE".equals(type)
|
||||
? java.time.LocalDateTime.ofInstant(
|
||||
time(order.get("dispatch_deadline")), java.time.ZoneOffset.UTC)
|
||||
: after(300);
|
||||
Map<String, Object> product;
|
||||
try {
|
||||
product =
|
||||
new com.fasterxml.jackson.databind.ObjectMapper()
|
||||
.readValue(text(order, "package_snapshot"), Map.class);
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalArgumentException("订单规则快照损坏");
|
||||
}
|
||||
long fee = number(product, "fee_limit_sun");
|
||||
Map<String, Object> intent =
|
||||
map(
|
||||
"protocol",
|
||||
"RENT_TASK_V2",
|
||||
"task_no",
|
||||
taskNo,
|
||||
"node_id",
|
||||
Long.toString(nodeId),
|
||||
"network",
|
||||
text(order, "network"),
|
||||
"task_type",
|
||||
type,
|
||||
"resource_type",
|
||||
text(order, "resource_type"),
|
||||
"resource_quantity",
|
||||
text(order, "resource_quantity"),
|
||||
"target_resource_quantity",
|
||||
text(order, "target_resource_quantity"),
|
||||
"owner",
|
||||
text(wallet, "address"),
|
||||
"receiver",
|
||||
text(order, "receiver_address"),
|
||||
"delegate_sun",
|
||||
Long.toString(sun),
|
||||
"total_limit",
|
||||
Long.toString(limit),
|
||||
"total_weight",
|
||||
Long.toString(weight),
|
||||
"baseline_sun",
|
||||
"DELEGATE".equals(type) ? "0" : Long.toString(sun),
|
||||
"conversion_block_height",
|
||||
text(wallet, "snapshot_block_height"),
|
||||
"delegate_lock",
|
||||
false,
|
||||
"fee_limit_sun",
|
||||
Long.toString(fee),
|
||||
"deadline",
|
||||
Long.toString(deadline.toInstant(java.time.ZoneOffset.UTC).toEpochMilli()),
|
||||
"source_tx_id",
|
||||
source == null ? "" : text(source, "tx_id"));
|
||||
// MySQL JSON会规范化键顺序/空格;签名使用排序后的紧凑JSON,投递时按同样规则重建。
|
||||
String body = orders.encode(new TreeMap<>(intent)), key = text(credential, "api_key");
|
||||
store.insert(
|
||||
"task",
|
||||
map(
|
||||
"task_no",
|
||||
taskNo,
|
||||
"order_id",
|
||||
orderId,
|
||||
"wallet_id",
|
||||
wallet.get("id"),
|
||||
"node_id",
|
||||
nodeId,
|
||||
"network",
|
||||
text(order, "network"),
|
||||
"source_transaction_id",
|
||||
source == null ? null : source.get("id"),
|
||||
"task_type",
|
||||
type,
|
||||
"resource_type",
|
||||
text(order, "resource_type"),
|
||||
"resource_quantity",
|
||||
order.get("resource_quantity"),
|
||||
"target_resource_quantity",
|
||||
order.get("target_resource_quantity"),
|
||||
"conversion_total_limit",
|
||||
limit,
|
||||
"conversion_total_weight",
|
||||
weight,
|
||||
"conversion_block_height",
|
||||
wallet.get("snapshot_block_height"),
|
||||
"conversion_at",
|
||||
now(),
|
||||
"estimated_resource_quantity",
|
||||
quantity(sun, limit, weight),
|
||||
"attempt_no",
|
||||
attempt,
|
||||
"active_slot",
|
||||
1,
|
||||
"wallet_execution_slot",
|
||||
1,
|
||||
"delegate_sun",
|
||||
sun,
|
||||
"fee_limit_sun",
|
||||
fee,
|
||||
"credential_id",
|
||||
credential.get("id"),
|
||||
"nonce",
|
||||
nonce,
|
||||
"signed_at",
|
||||
now(),
|
||||
"deadline",
|
||||
deadline,
|
||||
"intent",
|
||||
body,
|
||||
"signature",
|
||||
RentalCrypto.sign(
|
||||
identity.secret(credential),
|
||||
"TASK",
|
||||
key,
|
||||
signed,
|
||||
nonce,
|
||||
"PUSH",
|
||||
"/node/v1/task",
|
||||
body),
|
||||
"status",
|
||||
"PENDING",
|
||||
"reservation_status",
|
||||
"DELEGATE".equals(type) ? "HELD" : "NONE",
|
||||
"delivery_message_id",
|
||||
id("MSG"),
|
||||
"next_check_at",
|
||||
now()));
|
||||
// signed_at参与HMAC必须与毫秒值完全一致,不能用第二次now()。
|
||||
store.execute(
|
||||
"UPDATE rent_task SET signed_at=? WHERE task_no=?",
|
||||
java.time.LocalDateTime.ofInstant(
|
||||
Instant.ofEpochMilli(signed), java.time.ZoneOffset.UTC),
|
||||
taskNo);
|
||||
}
|
||||
|
||||
public void reclaim(long orderId) {
|
||||
tx(
|
||||
() -> {
|
||||
Map<String, Object> order = store.get("order", orderId, true);
|
||||
if (!Arrays.asList("WAITING", "MANUAL_REVIEW")
|
||||
.contains(text(order, "reclaim_status"))
|
||||
|| order.get("next_reclaim_at") == null
|
||||
|| time(order.get("next_reclaim_at")).isAfter(Instant.now())) {
|
||||
return null;
|
||||
}
|
||||
Map<String, Object> source =
|
||||
store.one(
|
||||
"SELECT x.* FROM rent_transaction x JOIN rent_task t ON"
|
||||
+ " t.id=x.task_id WHERE t.order_id=? AND"
|
||||
+ " t.task_type='DELEGATE' AND x.status='CONFIRMED' ORDER"
|
||||
+ " BY x.id LIMIT 1",
|
||||
orderId);
|
||||
require(source != null, "缺少原确认委托");
|
||||
Map<String, Object> wallet =
|
||||
store.get("wallet", number(order, "wallet_id"), true);
|
||||
if (store.one(
|
||||
"SELECT id FROM rent_task WHERE wallet_id=? AND resource_type=?"
|
||||
+ " AND wallet_execution_slot=1",
|
||||
wallet.get("id"),
|
||||
order.get("resource_type"))
|
||||
!= null) {
|
||||
return null;
|
||||
}
|
||||
if (store.one(
|
||||
"SELECT id FROM rent_task WHERE order_id=? AND"
|
||||
+ " task_type='RECLAIM' AND active_slot=1",
|
||||
orderId)
|
||||
!= null) {
|
||||
return null;
|
||||
}
|
||||
Map<String, Object> original =
|
||||
store.get("task", number(source, "task_id"), false);
|
||||
createTask(
|
||||
order,
|
||||
wallet,
|
||||
"RECLAIM",
|
||||
number(source, "amount_sun"),
|
||||
number(original, "conversion_total_limit"),
|
||||
number(original, "conversion_total_weight"),
|
||||
source);
|
||||
store.update(
|
||||
"order",
|
||||
orderId,
|
||||
map("reclaim_status", "RUNNING", "next_reclaim_at", after(30)));
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/** 来自当前认证会话的事件先持久去重;节点自报成功只记录线索,不扣款。 */
|
||||
public void report(long nodeId, Map<String, Object> report) {
|
||||
String taskNo = input(report, "task_no", 64);
|
||||
String eventId = input(report, "event_id", 40);
|
||||
String kind = input(report, "state", 24);
|
||||
require(eventId.matches("[A-Za-z0-9_-]+"), "事件编号非法");
|
||||
Map<String, Object> initial =
|
||||
store.one("SELECT * FROM rent_task WHERE task_no=? AND node_id=?", taskNo, nodeId);
|
||||
require(initial != null, "任务不属于节点");
|
||||
tx(
|
||||
() -> {
|
||||
Map<String, Object> order =
|
||||
store.get("order", number(initial, "order_id"), true);
|
||||
Map<String, Object> wallet =
|
||||
store.get("wallet", number(initial, "wallet_id"), true);
|
||||
Map<String, Object> task = store.get("task", number(initial, "id"), true);
|
||||
String event = "NODE:" + nodeId + ":" + eventId;
|
||||
if (store.one("SELECT id FROM rent_event WHERE event_no=?", event) != null) {
|
||||
return null;
|
||||
}
|
||||
long taskId = number(task, "id");
|
||||
if ("ACK".equals(kind)) {
|
||||
store.update("task", taskId, map("delivery_acked_at", now()));
|
||||
} else if ("ACCEPTED".equals(kind) && "PENDING".equals(text(task, "status"))) {
|
||||
store.update(
|
||||
"task", taskId, map("status", "ACCEPTED", "accepted_at", now()));
|
||||
} else if ("REJECTED".equals(kind)) {
|
||||
require(
|
||||
store.one("SELECT id FROM rent_transaction WHERE task_id=?", taskId)
|
||||
== null
|
||||
&& Arrays.asList("PENDING", "ACCEPTED", "UNKNOWN")
|
||||
.contains(text(task, "status")),
|
||||
"已存在广播线索,不能按未执行释放");
|
||||
fail(task, order, wallet, "REJECTED");
|
||||
} else if (Arrays.asList("BUILT", "BROADCASTED", "UNKNOWN", "RESULT")
|
||||
.contains(kind)) {
|
||||
require(
|
||||
!Arrays.asList("REJECTED", "FAILED").contains(text(task, "status")),
|
||||
"明确终结任务不可重新报告执行,应隔离核对");
|
||||
String txId = text(report, "tx_id");
|
||||
if (!txId.isEmpty()) {
|
||||
require(txId.matches("[0-9a-fA-F]{64}"), "交易哈希无效");
|
||||
Map<String, Object> existing =
|
||||
store.one(
|
||||
"SELECT * FROM rent_transaction WHERE task_id=?",
|
||||
taskId);
|
||||
if (existing != null) {
|
||||
require(
|
||||
txId.equalsIgnoreCase(text(existing, "tx_id")),
|
||||
"一任务只能有一笔原交易");
|
||||
} else {
|
||||
store.insert(
|
||||
"transaction",
|
||||
map(
|
||||
"task_id",
|
||||
taskId,
|
||||
"network",
|
||||
text(task, "network"),
|
||||
"tx_id",
|
||||
txId.toLowerCase(Locale.ROOT),
|
||||
"owner_address",
|
||||
text(wallet, "address"),
|
||||
"receiver_address",
|
||||
text(order, "receiver_address"),
|
||||
"transaction_type",
|
||||
text(task, "task_type"),
|
||||
"resource_type",
|
||||
text(task, "resource_type"),
|
||||
"amount_sun",
|
||||
task.get("delegate_sun"),
|
||||
"baseline_sun",
|
||||
"DELEGATE".equals(text(task, "task_type"))
|
||||
? 0
|
||||
: task.get("delegate_sun"),
|
||||
"status",
|
||||
"REPORTED",
|
||||
"next_check_at",
|
||||
now()));
|
||||
}
|
||||
}
|
||||
if (!"VERIFIED".equals(text(task, "status"))) {
|
||||
store.update(
|
||||
"task",
|
||||
taskId,
|
||||
map(
|
||||
"status",
|
||||
"UNKNOWN".equals(kind) ? "UNKNOWN" : "BROADCASTED",
|
||||
"next_check_at",
|
||||
now()));
|
||||
if ("DELEGATE".equals(text(task, "task_type"))) {
|
||||
store.update(
|
||||
"order", number(order, "id"), map("status", "VERIFYING"));
|
||||
}
|
||||
}
|
||||
} else if (!Arrays.asList("VERIFIED", "FAILED", "REJECTED")
|
||||
.contains(text(task, "status"))) {
|
||||
throw new IllegalArgumentException("未知节点事件");
|
||||
}
|
||||
store.insert(
|
||||
"event",
|
||||
map(
|
||||
"event_no",
|
||||
event,
|
||||
"object_type",
|
||||
"TASK",
|
||||
"object_id",
|
||||
taskId,
|
||||
"action",
|
||||
kind,
|
||||
"actor_user_id",
|
||||
0,
|
||||
"node_id",
|
||||
nodeId,
|
||||
"reason",
|
||||
"已认证节点事件,成功仍须独立链上核验"));
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
public void verify(long taskId) {
|
||||
Map<String, Object> task = store.get("task", taskId, false);
|
||||
Map<String, Object> record =
|
||||
store.one("SELECT * FROM rent_transaction WHERE task_id=?", taskId);
|
||||
if (record == null
|
||||
|| "CONFIRMED".equals(text(record, "status"))
|
||||
|| "FAILED".equals(text(record, "status"))) {
|
||||
return;
|
||||
}
|
||||
Map<String, Object> proof =
|
||||
chain.verify(
|
||||
task,
|
||||
text(record, "tx_id"),
|
||||
text(record, "owner_address"),
|
||||
text(record, "receiver_address"));
|
||||
tx(
|
||||
() -> {
|
||||
Map<String, Object> order = store.get("order", number(task, "order_id"), true);
|
||||
Map<String, Object> wallet =
|
||||
store.get("wallet", number(task, "wallet_id"), true);
|
||||
Map<String, Object> current = store.get("task", taskId, true);
|
||||
Map<String, Object> currentTx =
|
||||
store.get("transaction", number(record, "id"), true);
|
||||
if ("CONFIRMED".equals(text(currentTx, "status"))
|
||||
|| "FAILED".equals(text(currentTx, "status"))) {
|
||||
return null;
|
||||
}
|
||||
if ("FAILED".equals(text(proof, "status"))) {
|
||||
store.update("transaction", number(record, "id"), map("status", "FAILED"));
|
||||
fail(current, order, wallet, "FAILED");
|
||||
return null;
|
||||
}
|
||||
Map<String, Object> fields = new LinkedHashMap<>(proof);
|
||||
fields.remove("delivery_proven");
|
||||
fields.put("evidence", orders.encode(proof));
|
||||
fields.put("confirmed_at", now());
|
||||
store.update("transaction", number(record, "id"), fields);
|
||||
boolean delegate = "DELEGATE".equals(text(current, "task_type"));
|
||||
String prefix = text(current, "resource_type").toLowerCase(Locale.ROOT);
|
||||
Map<String, Object> barrier =
|
||||
map(
|
||||
"snapshot_min_block_height",
|
||||
Math.max(
|
||||
number(wallet, "snapshot_min_block_height"),
|
||||
number(proof, "block_height")),
|
||||
"snapshot_expires_at",
|
||||
null);
|
||||
if (delegate && "HELD".equals(text(current, "reservation_status"))) {
|
||||
long remaining =
|
||||
Math.subtractExact(
|
||||
number(wallet, prefix + "_reserved_sun"),
|
||||
number(current, "delegate_sun"));
|
||||
require(remaining >= 0, "预留账实不一致");
|
||||
barrier.put(prefix + "_reserved_sun", remaining);
|
||||
}
|
||||
store.update("wallet", number(wallet, "id"), barrier);
|
||||
store.update(
|
||||
"task",
|
||||
taskId,
|
||||
map(
|
||||
"status",
|
||||
"VERIFIED",
|
||||
"wallet_execution_slot",
|
||||
null,
|
||||
"reservation_status",
|
||||
delegate ? "COMMITTED" : "NONE"));
|
||||
long orderId = number(order, "id");
|
||||
if (delegate) {
|
||||
Instant start = time(proof.get("block_time")),
|
||||
expires = start.plusSeconds(number(order, "duration_seconds"));
|
||||
boolean delivered =
|
||||
Boolean.TRUE.equals(proof.get("delivery_proven"))
|
||||
&& number(proof, "verified_resource_quantity")
|
||||
>= number(order, "target_resource_quantity")
|
||||
&& expires.isAfter(Instant.now());
|
||||
if (delivered) {
|
||||
funds.charge(order);
|
||||
}
|
||||
store.update(
|
||||
"order",
|
||||
orderId,
|
||||
map(
|
||||
"status",
|
||||
delivered ? "SUCCESS" : "MANUAL_REVIEW",
|
||||
"service_started_at",
|
||||
proof.get("block_time"),
|
||||
"service_expires_at",
|
||||
java.time.LocalDateTime.ofInstant(
|
||||
expires, java.time.ZoneOffset.UTC),
|
||||
"reclaim_status",
|
||||
"WAITING",
|
||||
"next_reclaim_at",
|
||||
java.time.LocalDateTime.ofInstant(
|
||||
expires, java.time.ZoneOffset.UTC),
|
||||
"error_code",
|
||||
delivered ? null : "DELIVERY_EVIDENCE_REVIEW"));
|
||||
if (delivered) {
|
||||
orders.webhook(order, "SUCCESS", "ORDER:" + orderId + ":SUCCESS");
|
||||
}
|
||||
} else {
|
||||
store.update(
|
||||
"order",
|
||||
orderId,
|
||||
map("reclaim_status", "RECOVERING", "next_reclaim_at", after(15)));
|
||||
}
|
||||
store.event("TASK", taskId, "CHAIN_CONFIRMED", 0, "独立核验并同事务提升快照屏障,禁止旧快照重新出租");
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private void fail(
|
||||
Map<String, Object> task,
|
||||
Map<String, Object> order,
|
||||
Map<String, Object> wallet,
|
||||
String state) {
|
||||
boolean delegate = "DELEGATE".equals(text(task, "task_type"));
|
||||
long taskId = number(task, "id"), orderId = number(order, "id");
|
||||
if (delegate && "HELD".equals(text(task, "reservation_status"))) {
|
||||
String column = text(task, "resource_type").toLowerCase(Locale.ROOT) + "_reserved_sun";
|
||||
long remaining =
|
||||
Math.subtractExact(number(wallet, column), number(task, "delegate_sun"));
|
||||
require(remaining >= 0, "资源预留冲突");
|
||||
store.update("wallet", number(wallet, "id"), map(column, remaining));
|
||||
}
|
||||
store.update(
|
||||
"task",
|
||||
taskId,
|
||||
map(
|
||||
"status",
|
||||
state,
|
||||
"active_slot",
|
||||
null,
|
||||
"wallet_execution_slot",
|
||||
null,
|
||||
"reservation_status",
|
||||
delegate ? "RELEASED" : "NONE"));
|
||||
if (delegate) {
|
||||
boolean retry =
|
||||
number(task, "attempt_no") < 4
|
||||
&& time(order.get("dispatch_deadline")).isAfter(Instant.now());
|
||||
if (!retry) {
|
||||
funds.release(order);
|
||||
orders.webhook(order, "FAILED", "ORDER:" + orderId + ":FAILED");
|
||||
}
|
||||
store.update(
|
||||
"order",
|
||||
orderId,
|
||||
map(
|
||||
"status",
|
||||
retry ? "WAITING" : "FAILED",
|
||||
"relation_slot",
|
||||
null,
|
||||
"wallet_id",
|
||||
null));
|
||||
} else {
|
||||
store.update(
|
||||
"order",
|
||||
orderId,
|
||||
map("reclaim_status", "WAITING", "next_reclaim_at", after(60)));
|
||||
}
|
||||
store.event("TASK", taskId, "SAFE_FAILURE", 0, "明确拒绝未构建或链上确认失败;未知不走本分支");
|
||||
}
|
||||
|
||||
public void recoverResource(long orderId) {
|
||||
Map<String, Object> order = store.get("order", orderId, false);
|
||||
if (!"RECOVERING".equals(text(order, "reclaim_status"))) {
|
||||
return;
|
||||
}
|
||||
Map<String, Object> wallet = store.get("wallet", number(order, "wallet_id"), false);
|
||||
Map<String, Object> snapshot =
|
||||
chain.snapshot(text(wallet, "network"), text(wallet, "address"));
|
||||
if (chain.relation(
|
||||
text(wallet, "network"),
|
||||
text(wallet, "address"),
|
||||
text(order, "receiver_address"),
|
||||
text(order, "resource_type"))
|
||||
!= 0) {
|
||||
return;
|
||||
}
|
||||
// 可委托本金>0不代表本单资源已恢复。保守要求原本金可再次委托,减去本地占用和留存。
|
||||
Map<String, Object> source =
|
||||
store.one(
|
||||
"SELECT x.* FROM rent_transaction x JOIN rent_task t ON t.id=x.task_id"
|
||||
+ " WHERE t.order_id=? AND t.task_type='DELEGATE' AND"
|
||||
+ " x.status='CONFIRMED'",
|
||||
orderId);
|
||||
String prefix = text(order, "resource_type").toLowerCase(Locale.ROOT);
|
||||
if (number(snapshot, prefix + "_delegatable_sun")
|
||||
- number(wallet, prefix + "_retain_sun")
|
||||
- number(wallet, prefix + "_reserved_sun")
|
||||
< number(source, "amount_sun")) {
|
||||
return;
|
||||
}
|
||||
tx(
|
||||
() -> {
|
||||
Map<String, Object> current = store.get("order", orderId, true);
|
||||
Map<String, Object> latest = store.get("wallet", number(wallet, "id"), true);
|
||||
if (!"RECOVERING".equals(text(current, "reclaim_status"))) {
|
||||
return null;
|
||||
}
|
||||
require(
|
||||
number(latest, "version") == number(wallet, "version")
|
||||
&& number(snapshot, "snapshot_block_height")
|
||||
>= number(latest, "snapshot_min_block_height"),
|
||||
"资源恢复快照已过时");
|
||||
store.update("wallet", number(wallet, "id"), snapshot);
|
||||
store.update(
|
||||
"order",
|
||||
orderId,
|
||||
map(
|
||||
"reclaim_status",
|
||||
"DONE",
|
||||
"relation_slot",
|
||||
null,
|
||||
"next_reclaim_at",
|
||||
null));
|
||||
orders.webhook(current, "RECLAIMED", "ORDER:" + orderId + ":RECLAIMED");
|
||||
store.event("ORDER", orderId, "RECLAIMED", 0, "原本金已撤销且可委托资源恢复");
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/** 无txId的未知任务只能补充独立核实的原交易,不能直接标失败或重新派单。 */
|
||||
public void attach(long taskId, String txId, long actor, String reason) {
|
||||
Map<String, Object> task = store.get("task", taskId, false);
|
||||
require(
|
||||
task.get("active_slot") != null
|
||||
&& !Arrays.asList("REJECTED", "FAILED").contains(text(task, "status")),
|
||||
"只能补充原在途任务的交易证据");
|
||||
Map<String, Object> wallet = store.get("wallet", number(task, "wallet_id"), false);
|
||||
Map<String, Object> order = store.get("order", number(task, "order_id"), false);
|
||||
chain.verify(task, txId, text(wallet, "address"), text(order, "receiver_address"));
|
||||
report(
|
||||
number(task, "node_id"),
|
||||
map(
|
||||
"task_no",
|
||||
text(task, "task_no"),
|
||||
"event_id",
|
||||
RentalValues.id("ADMIN"),
|
||||
"state",
|
||||
"BUILT",
|
||||
"tx_id",
|
||||
txId));
|
||||
tx(
|
||||
() -> {
|
||||
store.event("TASK", taskId, "ATTACH_ORIGINAL_TX", actor, reason);
|
||||
return null;
|
||||
});
|
||||
verify(taskId);
|
||||
}
|
||||
|
||||
/** 异常委托完成原本金回收后,人工可终结未确认收入的HELD订单,不能释放未知在途。 */
|
||||
public void resolveRecovered(long orderId, long actor, String reason) {
|
||||
tx(
|
||||
() -> {
|
||||
Map<String, Object> order = store.get("order", orderId, true);
|
||||
require(
|
||||
"MANUAL_REVIEW".equals(text(order, "status"))
|
||||
&& "DONE".equals(text(order, "reclaim_status"))
|
||||
&& "HELD".equals(text(order, "fund_status")),
|
||||
"仅本金及资源已确认回收的人工核对冻结单可解冻");
|
||||
funds.release(order);
|
||||
store.update("order", orderId, map("status", "FAILED", "remark", reason));
|
||||
orders.webhook(order, "FAILED", "ORDER:" + orderId + ":FAILED");
|
||||
store.event("ORDER", orderId, "RESOLVE_AFTER_RECLAIM", actor, reason);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/** 在租期间监测外部提前撤销/追加。发现差异只隔离,不擅自撤销他人本金或自动退款。 */
|
||||
public void monitor(long orderId) {
|
||||
Map<String, Object> order = store.get("order", orderId, false);
|
||||
if (!"SUCCESS".equals(text(order, "status"))
|
||||
|| !"WAITING".equals(text(order, "reclaim_status"))) {
|
||||
return;
|
||||
}
|
||||
Map<String, Object> wallet = store.get("wallet", number(order, "wallet_id"), false);
|
||||
Map<String, Object> source =
|
||||
store.one(
|
||||
"SELECT x.* FROM rent_transaction x JOIN rent_task t ON t.id=x.task_id"
|
||||
+ " WHERE t.order_id=? AND t.task_type='DELEGATE' AND"
|
||||
+ " x.status='CONFIRMED'",
|
||||
orderId);
|
||||
require(source != null, "缺少原始委托证据");
|
||||
long current =
|
||||
chain.relation(
|
||||
text(order, "network"),
|
||||
text(wallet, "address"),
|
||||
text(order, "receiver_address"),
|
||||
text(order, "resource_type"));
|
||||
if (current != number(source, "amount_sun")) {
|
||||
tx(
|
||||
() -> {
|
||||
Map<String, Object> latest = store.get("order", orderId, true);
|
||||
if ("SUCCESS".equals(text(latest, "status"))
|
||||
&& "WAITING".equals(text(latest, "reclaim_status"))) {
|
||||
store.update(
|
||||
"order",
|
||||
orderId,
|
||||
map(
|
||||
"status",
|
||||
"MANUAL_REVIEW",
|
||||
"reclaim_status",
|
||||
"MANUAL_REVIEW",
|
||||
"error_code",
|
||||
"DELEGATION_CHANGED",
|
||||
"next_reclaim_at",
|
||||
after(60)));
|
||||
store.event(
|
||||
"ORDER",
|
||||
orderId,
|
||||
"DELEGATION_CHANGED",
|
||||
0,
|
||||
"原地址对委托关系已发生外部变化,隔离并等待人工处理");
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/** 租赁专用精度和输入规则。SUN、资源量使用精确整数,USDT最多六位小数。 */
|
||||
public final class RentalValues {
|
||||
public static final BigDecimal ZERO = new BigDecimal("0.000000");
|
||||
|
||||
private RentalValues() {}
|
||||
|
||||
public static Map<String, Object> map(Object... pairs) {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
for (int i = 0; i < pairs.length; i += 2) {
|
||||
result.put((String) pairs[i], pairs[i + 1]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void require(boolean condition, String message) {
|
||||
if (!condition) {
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
}
|
||||
|
||||
public static String text(Map<String, Object> row, String key) {
|
||||
Object value = row.get(key);
|
||||
return value == null ? "" : value.toString();
|
||||
}
|
||||
|
||||
public static String input(Map<String, Object> row, String key, int max) {
|
||||
String value = text(row, key).trim();
|
||||
require(
|
||||
!value.isEmpty()
|
||||
&& value.length() <= max
|
||||
&& !value.contains("\n")
|
||||
&& !value.contains("\r"),
|
||||
"参数不合法:" + key);
|
||||
return value;
|
||||
}
|
||||
|
||||
public static long number(Map<String, Object> row, String key) {
|
||||
require(
|
||||
!(row.get(key) instanceof Double) && !(row.get(key) instanceof Float),
|
||||
"整数请使用精确整数或字符串:" + key);
|
||||
return new BigDecimal(text(row, key)).longValueExact();
|
||||
}
|
||||
|
||||
public static BigDecimal money(Object value) {
|
||||
require(
|
||||
value != null && !(value instanceof Double) && !(value instanceof Float),
|
||||
"USDT请使用最多6位小数的十进制字符串");
|
||||
return new BigDecimal(value.toString()).setScale(6, RoundingMode.UNNECESSARY);
|
||||
}
|
||||
|
||||
public static BigDecimal amount(Map<String, Object> row, String key) {
|
||||
return money(row.get(key));
|
||||
}
|
||||
|
||||
public static LocalDateTime now() {
|
||||
return LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC);
|
||||
}
|
||||
|
||||
public static LocalDateTime after(long seconds) {
|
||||
return now().plusSeconds(seconds);
|
||||
}
|
||||
|
||||
public static Instant time(Object value) {
|
||||
if (value instanceof Timestamp) {
|
||||
return ((Timestamp) value).toLocalDateTime().toInstant(ZoneOffset.UTC);
|
||||
}
|
||||
return ((LocalDateTime) value).toInstant(ZoneOffset.UTC);
|
||||
}
|
||||
|
||||
public static String id(String prefix) {
|
||||
return prefix + UUID.randomUUID().toString().replace("-", "");
|
||||
}
|
||||
|
||||
public static String network(String value) {
|
||||
require("NILE".equals(value) || "MAINNET".equals(value), "仅支持NILE或MAINNET");
|
||||
return value;
|
||||
}
|
||||
|
||||
public static String resource(String value) {
|
||||
require("ENERGY".equals(value) || "BANDWIDTH".equals(value), "资源类型不合法");
|
||||
return value;
|
||||
}
|
||||
|
||||
/** 用BigDecimal防止中间乘积溢出;所有落库整数都做精确范围检查。 */
|
||||
public static long target(long quantity, BigDecimal percent) {
|
||||
require(quantity > 0 && percent.signum() > 0, "资源数量和冗余必须大于0");
|
||||
return BigDecimal.valueOf(quantity)
|
||||
.multiply(BigDecimal.ONE.add(percent.movePointLeft(2)))
|
||||
.setScale(0, RoundingMode.CEILING)
|
||||
.max(BigDecimal.valueOf(Math.addExact(quantity, 1)))
|
||||
.longValueExact();
|
||||
}
|
||||
|
||||
public static long principal(long target, long limit, long weight) {
|
||||
require(target > 0 && limit > 0 && weight > 0, "链上换算参数无效");
|
||||
return BigDecimal.valueOf(target)
|
||||
.multiply(BigDecimal.valueOf(weight))
|
||||
.divide(BigDecimal.valueOf(limit), 0, RoundingMode.CEILING)
|
||||
.movePointRight(6)
|
||||
.longValueExact();
|
||||
}
|
||||
|
||||
public static long quantity(long sun, long limit, long weight) {
|
||||
require(sun > 0 && limit > 0 && weight > 0, "链上资源参数无效");
|
||||
return BigDecimal.valueOf(sun)
|
||||
.multiply(BigDecimal.valueOf(limit))
|
||||
.divide(BigDecimal.valueOf(weight).movePointRight(6), 0, RoundingMode.FLOOR)
|
||||
.longValueExact();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
|
||||
import okhttp3.*;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** 有界分批扫描持久事实,失败按记录隔离;关闭广播或节点离线仍继续核对原交易。 */
|
||||
@Component
|
||||
@ConditionalOnProperty(name = "rental.enabled", havingValue = "true")
|
||||
public class RentalWorkers {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(RentalWorkers.class);
|
||||
private final RentalStore store;
|
||||
private final RentalTasks tasks;
|
||||
private final RentalSocket socket;
|
||||
private final RentalIdentity identity;
|
||||
private final OkHttpClient callbacks = RentalHttp.callbackClient();
|
||||
private long walletCursor;
|
||||
private long monitoringCursor;
|
||||
private long dispatchCursor;
|
||||
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private RentalReconciliation reconciliation;
|
||||
|
||||
@Scheduled(cron = "0 0 2 * * ?", zone = "UTC")
|
||||
public void reconciliation() {
|
||||
long after = 0;
|
||||
while (true) {
|
||||
Map<String, Object> result = reconciliation.check(after);
|
||||
if (!((List<?>) result.get("differences")).isEmpty()) {
|
||||
LOG.error("租赁账户与不可变流水存在差异,请通过受保护的核对接口检查,afterId={}", after);
|
||||
}
|
||||
if (!Boolean.TRUE.equals(result.get("has_more"))) {
|
||||
break;
|
||||
}
|
||||
after = number(result, "next_after_id");
|
||||
}
|
||||
if (!reconciliation.reservations().isEmpty()) {
|
||||
LOG.error("租赁SUN预留与任务占用存在差异,禁止人工直接覆盖,请核对原任务");
|
||||
}
|
||||
}
|
||||
|
||||
public RentalWorkers(
|
||||
RentalStore store, RentalTasks tasks, RentalSocket socket, RentalIdentity identity) {
|
||||
this.store = store;
|
||||
this.tasks = tasks;
|
||||
this.socket = socket;
|
||||
this.identity = identity;
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelay = 15000)
|
||||
public void heartbeat() {
|
||||
socket.tick();
|
||||
store.execute(
|
||||
"UPDATE rent_node SET connection_status='OFFLINE',version=version+1,updated_at=?"
|
||||
+ " WHERE connection_status<>'OFFLINE' AND heartbeat_expires_at<?",
|
||||
now(),
|
||||
now());
|
||||
// 认证仅允许前后60秒,nonce保留180秒后分批清理仍不会重新接受过期请求。
|
||||
store.execute("DELETE FROM rent_nonce WHERE expires_at<? LIMIT 1000", now());
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelay = 5000)
|
||||
public void dispatch() {
|
||||
// 主键轮转,资源不足的早期订单不能永久阻塞其他网络或资源类型的订单。
|
||||
List<Map<String, Object>> waiting =
|
||||
store.rows(
|
||||
"SELECT id FROM rent_order WHERE status='WAITING' AND id>? ORDER BY id"
|
||||
+ " LIMIT 20",
|
||||
dispatchCursor);
|
||||
if (waiting.isEmpty()) {
|
||||
dispatchCursor = 0;
|
||||
}
|
||||
for (Map<String, Object> row : waiting) {
|
||||
dispatchCursor = number(row, "id");
|
||||
try {
|
||||
tasks.dispatch(dispatchCursor);
|
||||
} catch (Exception ex) {
|
||||
LOG.warn("租赁订单调度待重试,orderId={}", dispatchCursor);
|
||||
}
|
||||
}
|
||||
each(
|
||||
"SELECT id FROM rent_order WHERE reclaim_status IN ('WAITING','MANUAL_REVIEW') AND"
|
||||
+ " next_reclaim_at<=UTC_TIMESTAMP(3) ORDER BY next_reclaim_at LIMIT 20",
|
||||
tasks::reclaim);
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelay = 10000)
|
||||
public void verify() {
|
||||
each(
|
||||
"SELECT id FROM rent_task WHERE status IN"
|
||||
+ " ('PENDING','ACCEPTED','BROADCASTED','UNKNOWN') AND (next_check_at IS NULL"
|
||||
+ " OR next_check_at<=UTC_TIMESTAMP(3)) ORDER BY next_check_at LIMIT 20",
|
||||
id -> {
|
||||
try {
|
||||
tasks.verify(id);
|
||||
store.execute(
|
||||
"UPDATE rent_task SET"
|
||||
+ " status='UNKNOWN',version=version+1,updated_at=? WHERE id=?"
|
||||
+ " AND status IN ('PENDING','ACCEPTED') AND deadline<?",
|
||||
now(),
|
||||
id,
|
||||
now());
|
||||
} finally {
|
||||
store.execute(
|
||||
"UPDATE rent_task SET next_check_at=? WHERE id=?", after(30), id);
|
||||
}
|
||||
});
|
||||
each(
|
||||
"SELECT id FROM rent_order WHERE reclaim_status='RECOVERING' AND"
|
||||
+ " next_reclaim_at<=UTC_TIMESTAMP(3) ORDER BY next_reclaim_at LIMIT 20",
|
||||
id -> {
|
||||
try {
|
||||
tasks.recoverResource(id);
|
||||
} finally {
|
||||
// 即使RPC失败也推进重试时间,避免故障记录占满每批扫描窗口。
|
||||
store.execute(
|
||||
"UPDATE rent_order SET next_reclaim_at=? WHERE id=? AND"
|
||||
+ " reclaim_status='RECOVERING'",
|
||||
after(30),
|
||||
id);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelay = 15000)
|
||||
public void snapshots() {
|
||||
// 按主键轮转,不能让最早20个故障RPC钱包永久阻塞后续供应钱包。
|
||||
List<Map<String, Object>> rows =
|
||||
store.rows(
|
||||
"SELECT id FROM rent_wallet WHERE id>? AND status='ACTIVE' AND"
|
||||
+ " (snapshot_expires_at IS NULL OR snapshot_expires_at<=?) ORDER BY id"
|
||||
+ " LIMIT 20",
|
||||
walletCursor,
|
||||
now());
|
||||
if (rows.isEmpty()) {
|
||||
walletCursor = 0;
|
||||
return;
|
||||
}
|
||||
for (Map<String, Object> row : rows) {
|
||||
walletCursor = number(row, "id");
|
||||
try {
|
||||
tasks.refresh(walletCursor);
|
||||
} catch (Exception ex) {
|
||||
LOG.warn("租赁钱包快照暂不可用,walletId={}", walletCursor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void each(String sql, Consumer<Long> action) {
|
||||
for (Map<String, Object> row : store.rows(sql)) {
|
||||
long id = number(row, "id");
|
||||
try {
|
||||
action.accept(id);
|
||||
} catch (Exception ex) {
|
||||
LOG.warn("租赁后台核对暂未完成,recordId={},下轮继续;敏感异常不记录", id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelay = 30000)
|
||||
public void monitor() {
|
||||
List<Map<String, Object>> rows =
|
||||
store.rows(
|
||||
"SELECT id FROM rent_order WHERE id>? AND status='SUCCESS' AND"
|
||||
+ " reclaim_status='WAITING' AND service_expires_at>? ORDER BY id LIMIT"
|
||||
+ " 20",
|
||||
monitoringCursor,
|
||||
now());
|
||||
if (rows.isEmpty()) {
|
||||
monitoringCursor = 0;
|
||||
return;
|
||||
}
|
||||
for (Map<String, Object> row : rows) {
|
||||
monitoringCursor = number(row, "id");
|
||||
try {
|
||||
tasks.monitor(monitoringCursor);
|
||||
} catch (Exception ex) {
|
||||
LOG.warn("租赁在租委托监测待重试,orderId={}", monitoringCursor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelay = 5000)
|
||||
public void webhooks() {
|
||||
for (Map<String, Object> candidate :
|
||||
store.rows(
|
||||
"SELECT id FROM rent_webhook WHERE status IN ('PENDING','SENDING') AND"
|
||||
+ " (next_attempt_at IS NULL OR next_attempt_at<=?) AND (lock_until IS"
|
||||
+ " NULL OR lock_until<?) ORDER BY id LIMIT 20",
|
||||
now(),
|
||||
now())) {
|
||||
long id = number(candidate, "id");
|
||||
String lease = RentalValues.id("LEASE");
|
||||
Map<String, Object> row =
|
||||
tasks.tx(
|
||||
() -> {
|
||||
Map<String, Object> current = store.get("webhook", id, true);
|
||||
if (!Arrays.asList("PENDING", "SENDING")
|
||||
.contains(text(current, "status"))
|
||||
|| (current.get("lock_until") != null
|
||||
&& time(current.get("lock_until"))
|
||||
.isAfter(java.time.Instant.now()))) {
|
||||
return null;
|
||||
}
|
||||
store.update(
|
||||
"webhook",
|
||||
id,
|
||||
map(
|
||||
"status",
|
||||
"SENDING",
|
||||
"lock_owner",
|
||||
lease,
|
||||
"lock_until",
|
||||
after(30),
|
||||
"attempt_count",
|
||||
number(current, "attempt_count") + 1));
|
||||
return store.get("webhook", id, false);
|
||||
});
|
||||
if (row == null) {
|
||||
continue;
|
||||
}
|
||||
boolean acked = false;
|
||||
try {
|
||||
Map<String, Object> order = store.get("order", number(row, "order_id"), false);
|
||||
String url = text(order, "notify_url");
|
||||
if (url.isEmpty()) {
|
||||
acked = true;
|
||||
} else {
|
||||
RentalHttp.checkUrl(url);
|
||||
Map<String, Object> credential =
|
||||
store.one(
|
||||
"SELECT * FROM rent_credential WHERE owner_type='APP' AND"
|
||||
+ " owner_id=? AND status='ACTIVE' AND (expires_at IS NULL"
|
||||
+ " OR expires_at>?) ORDER BY id DESC LIMIT 1",
|
||||
order.get("app_id"),
|
||||
now());
|
||||
require(credential != null, "无有效回调凭证");
|
||||
String key = text(credential, "api_key");
|
||||
String nonce = RentalCrypto.random();
|
||||
String body = text(row, "payload");
|
||||
long timestamp = System.currentTimeMillis();
|
||||
HttpUrl parsed = HttpUrl.parse(url);
|
||||
require(parsed != null && parsed.query() == null, "回调URL不允许查询串");
|
||||
Request request =
|
||||
new Request.Builder()
|
||||
.url(url)
|
||||
.header("X-Rent-Key", key)
|
||||
.header("X-Rent-Timestamp", Long.toString(timestamp))
|
||||
.header("X-Rent-Nonce", nonce)
|
||||
.header(
|
||||
"X-Rent-Signature",
|
||||
RentalCrypto.sign(
|
||||
identity.secret(credential),
|
||||
"WEBHOOK",
|
||||
key,
|
||||
timestamp,
|
||||
nonce,
|
||||
"POST",
|
||||
parsed.encodedPath(),
|
||||
body))
|
||||
.post(
|
||||
RequestBody.create(
|
||||
MediaType.parse("application/json"), body))
|
||||
.build();
|
||||
try (Response response = callbacks.newCall(request).execute()) {
|
||||
acked = response.code() == 200 && "ok".equals(RentalHttp.body(response));
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
/* 不记录URL、签名或响应原文,保留同一事件下次重试。 */
|
||||
}
|
||||
int attempt = (int) number(row, "attempt_count");
|
||||
store.execute(
|
||||
"UPDATE rent_webhook SET"
|
||||
+ " status=?,next_attempt_at=?,lock_owner=NULL,lock_until=NULL,last_error=?,version=version+1,updated_at=?"
|
||||
+ " WHERE id=? AND lock_owner=?",
|
||||
acked ? "ACKED" : attempt >= 10 ? "DEAD" : "PENDING",
|
||||
after(Math.min(3600, 1L << Math.min(attempt, 11))),
|
||||
acked ? null : "回调未确认,请核对凭证、目标网络和响应",
|
||||
now(),
|
||||
id,
|
||||
lease);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,4 +44,11 @@ public class TronServiceProvider {
|
||||
if (networkType == NETWORK_MAINNET) return mainnetService;
|
||||
throw new CustomException("TRON 全局网络类型非法:" + networkType);
|
||||
}
|
||||
|
||||
/** 租赁订单按自身锁定网络查询,不能被全局支付网络切换影响。仅返回服务,不执行广播。 */
|
||||
public ITronService getServiceForNetwork(String network) {
|
||||
if ("NILE".equals(network)) { return nileService; }
|
||||
if ("MAINNET".equals(network)) { return mainnetService; }
|
||||
throw new IllegalArgumentException("TRON网络类型非法");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user