自行建设,补充这部分功能,给出具体的表设计和代码实现,同云端服务端一起部署

This commit is contained in:
lu7213 committed 2026-10-24 04:36:20 -04:00
1 parent cab8056412
commit b3419aa389
15 files changed
+1369 -14

No files matched your search

@@ -33,6 +33,13 @@ public class RentalChain {
@Value("${rental.history.mainnet:}")
private String mainHistory;
@Value("${rental.history.embedded-enabled:false}")
private boolean embeddedHistory;
// 延迟获取内置历史服务,避免历史采集复用本只读RPC适配器时发生构造循环依赖。
@org.springframework.beans.factory.annotation.Autowired
private org.springframework.beans.factory.ObjectProvider<RentalHistoryService> historyService;
@Value("${rental.rpc.api-key:}")
private String apiKey;
@@ -72,7 +79,9 @@ public class RentalChain {
json.writeValueAsString(body)))
.build();
try (Response response = client.newCall(request).execute()) {
return json.readTree(RentalHttp.body(response));
boolean fullBlock = path.endsWith("/getnowblock") || path.endsWith("/getblockbynum");
return json.readTree(RentalHttp.body(response,
(fullBlock ? 16 : 1) * 1024 * 1024));
}
} catch (Exception ex) {
throw new IllegalStateException("链上查询失败,保留原业务状态");
@@ -168,6 +177,13 @@ public class RentalChain {
return total;
}
/** 内置历史模式在派单前建立确认关系基线,RPC失败时继续等待派单,不先广播再补基线。 */
public void prepareHistory(String network, String owner, String receiver, String resource) {
if (embeddedHistory) {
historyService.getObject().anchor(network, owner, receiver, resource);
}
}
/** 返回CONFIRMED仅代表交易真实成功;历史资源证据不足时delivery_proven=false。 */
public Map<String, Object> verify(
Map<String, Object> task, String txId, String owner, String receiver) {
@@ -224,9 +240,18 @@ public class RentalChain {
"delivery_proven",
!delegate);
String history = "NILE".equals(network) ? nileHistory : mainHistory;
if (delegate && !history.isEmpty()) {
JsonNode proof =
request(
if (delegate && (embeddedHistory || !history.isEmpty())) {
JsonNode proof;
if (embeddedHistory) {
Map<String, Object> archived = historyService.getObject().proof(
network, txId, height, owner, receiver, text(task, "resource_type"));
if (archived == null) {
// 参数漏采或缺少派单前基线:保留原有MANUAL_REVIEW路径,绝不降级为当前快照。
return result;
}
proof = json.valueToTree(archived);
} else {
proof = request(
history,
"/rental/resource-proof",
map(
@@ -242,6 +267,7 @@ public class RentalChain {
receiver,
"resource_type",
text(task, "resource_type")));
}
require(
height == proof.path("block_height").asLong(-1)
&& txId.equalsIgnoreCase(proof.path("tx_id").asText())
@@ -252,6 +278,8 @@ public class RentalChain {
weight = proof.path("total_weight").asLong();
result.put("verified_total_limit", limit);
result.put("verified_total_weight", weight);
// 完整历史证明写入交易evidence JSON,保留区块哈希、基线高度和数据来源供审计。
result.put("history_proof", json.convertValue(proof, Map.class));
result.put(
"verified_resource_quantity",
quantity(number(task, "delegate_sun"), limit, weight));
@@ -0,0 +1,67 @@
package com.ruoyi.system.rental;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/** 独立采集线程,不与业务五秒/十五秒调度争抢同一个调度线程;无链上写操作。 */
@Component
@ConditionalOnProperty(name = {"rental.enabled", "rental.history.embedded-enabled"}, havingValue = "true")
public class RentalHistoryCollector {
private static final Logger LOG = LoggerFactory.getLogger(RentalHistoryCollector.class);
private final RentalHistoryService service;
private ScheduledThreadPoolExecutor executor;
@Value("${rental.history.networks:NILE}")
private String networks = "NILE";
@Value("${rental.history.poll-interval-ms:1000}")
private long interval = 1000;
public RentalHistoryCollector(RentalHistoryService service) {
this.service = service;
}
@PostConstruct
public void start() {
RentalValues.require(interval >= 200 && interval <= 60000, "历史采集间隔必须为200到60000毫秒");
Set<String> selected = new LinkedHashSet<>();
for (String name : networks.split(",")) {
selected.add(RentalValues.network(name.trim()));
}
AtomicInteger sequence = new AtomicInteger();
executor = new ScheduledThreadPoolExecutor(selected.size(), action -> {
Thread thread = new Thread(action, "rental-history-" + sequence.incrementAndGet());
thread.setDaemon(true);
return thread;
});
executor.setRemoveOnCancelPolicy(true);
for (String network : selected) {
executor.scheduleWithFixedDelay(() -> {
try {
service.collect(network);
} catch (Exception ex) {
// 不记录异常原文,避免RPC配置、认证头或供应商数据进入日志。
LOG.warn("租赁历史采集未完成,network={},请查看受保护的历史状态接口", network);
}
}, 0, interval, TimeUnit.MILLISECONDS);
}
}
@PreDestroy
public void close() {
if (executor != null) {
executor.shutdownNow();
}
}
}
@@ -0,0 +1,43 @@
package com.ruoyi.system.rental;
import static com.ruoyi.system.rental.RentalValues.input;
import static com.ruoyi.system.rental.RentalValues.number;
import static com.ruoyi.system.rental.RentalValues.require;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/** 历史状态与证明只向已登录运营开放;自动结算使用进程内调用,不需要开放匿名接口。 */
@RestController
@RequestMapping("/rental")
public class RentalHistoryController {
private final RentalHistoryService service;
public RentalHistoryController(RentalHistoryService service) {
this.service = service;
}
@GetMapping("/history/status")
@PreAuthorize("@ss.hasPermi('rent:manage:audit')")
public AjaxResult status() {
return AjaxResult.success(service.status());
}
/** 与原resource-proof数据协议一致,直接返回证明JSON;不接受用户指定RPC地址或本金。 */
@PostMapping("/resource-proof")
@PreAuthorize("@ss.hasPermi('rent:manage:audit')")
public Map<String, Object> proof(@RequestBody Map<String, Object> request) {
Map<String, Object> result = service.proof(input(request, "network", 16),
input(request, "tx_id", 64), number(request, "block_height"),
input(request, "owner", 64), input(request, "receiver", 64),
input(request, "resource_type", 16));
require(result != null, "该交易缺少历史参数或派单前基线,不能出具证明");
return result;
}
}
@@ -0,0 +1,440 @@
package com.ruoyi.system.rental;
import static com.ruoyi.system.rental.RentalValues.id;
import static com.ruoyi.system.rental.RentalValues.map;
import static com.ruoyi.system.rental.RentalValues.network;
import static com.ruoyi.system.rental.RentalValues.now;
import static com.ruoyi.system.rental.RentalValues.number;
import static com.ruoyi.system.rental.RentalValues.require;
import static com.ruoyi.system.rental.RentalValues.resource;
import static com.ruoyi.system.rental.RentalValues.text;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import org.tron.trident.core.ApiWrapper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* 云端内置的只读历史采集与证明服务。
*
* <p>普通节点只提供最新确认状态,因此用同一确认头前后夹读为参数、关系基线绑定高度。
* 已错过高度只能补区块交易,不能补造历史参数。所有HTTP在事务外执行,数据库事务只保存事实。
* 本服务信任运营配置的同一一致性RPC节点,不接受供应商提交的历史参数,不持有私钥,不广播。
*/
@Service
public class RentalHistoryService {
private static final int MAX_REPLAY_BLOCKS = 10000;
private static final String DEFAULT_PROBE = "T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb";
private final RentalStore store;
private final RentalChain chain;
private final TransactionTemplate transaction;
@Value("${rental.history.batch-size:30}")
private int batchSize = 30;
@Value("${rental.history.probe-address:T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb}")
private String probeAddress = DEFAULT_PROBE;
@Value("${rental.history.networks:NILE}")
private String enabledNetworks = "NILE";
@Value("${rental.confirmations:19}")
private long confirmations = 19;
public RentalHistoryService(RentalStore store, RentalChain chain,
PlatformTransactionManager manager) {
this.store = store;
this.chain = chain;
this.transaction = new TransactionTemplate(manager);
}
/** 仅接受合法TRON地址;库内统一十六进制,避免Base58大小写折叠或多种编码造成漏重放。 */
static String addressHex(String address) {
RentalOrders.address(address);
return ApiWrapper.toHex(ApiWrapper.parseAddress(address)).toLowerCase(Locale.ROOT);
}
private static long height(JsonNode block) {
return positive(block.path("block_header").path("raw_data").path("number"), true);
}
private static String hash(JsonNode block) {
String value = block.path("blockID").asText();
require(value.matches("[0-9a-fA-F]{64}"), "确认区块缺少合法哈希");
return value.toLowerCase(Locale.ROOT);
}
private static long positive(JsonNode value, boolean zeroAllowed) {
require(value.isIntegralNumber() && value.canConvertToLong(), "链上整数缺失或越界");
long result = value.longValue();
require(zeroAllowed ? result >= 0 : result > 0, "链上整数范围无效");
return result;
}
private JsonNode head(String network) {
return chain.call(network, "/walletsolidity/getnowblock", map());
}
private long[] parameters(JsonNode resource) {
return new long[] {
positive(resource.path("TotalEnergyLimit"), false),
positive(resource.path("TotalEnergyWeight"), false),
positive(resource.path("TotalNetLimit"), false),
positive(resource.path("TotalNetWeight"), false)
};
}
/**
* 三次有界尝试,只有确认头高度和哈希均未变化才接纳快照。
* 这里读取walletsolidity状态,不允许用wallet最新未确认状态冒充历史快照。
*/
private Snapshot capture(String network, String owner, String receiver, String type) {
for (int attempt = 0; attempt < 3; attempt++) {
JsonNode before = head(network);
long blockHeight = height(before);
String blockId = hash(before);
long[] totals = parameters(chain.call(network, "/walletsolidity/getaccountresource",
map("address", owner, "visible", true)));
long balance = 0;
if (receiver != null) {
// 锁定和非锁定本金都参与基线,锁定到期解锁不会改变合计本金。
for (boolean locked : new boolean[] {false, true}) {
JsonNode response = chain.call(network, "/walletsolidity/getdelegatedresourcev2",
map("fromAddress", owner, "toAddress", receiver,
"lock", locked, "visible", true));
require(!response.has("Error") && !response.has("error")
&& (!response.has("result") || !response.path("result").isBoolean()
|| response.path("result").asBoolean()), "确认关系查询失败");
JsonNode rows = response.path("delegatedResource");
require(rows.isMissingNode() || rows.isArray(), "确认关系响应结构错误");
for (JsonNode row : rows) {
String field = "ENERGY".equals(type)
? "frozen_balance_for_energy" : "frozen_balance_for_bandwidth";
// protobuf省略零字段;有值时必须为精确非负整数。
balance = Math.addExact(balance, row.has(field)
? positive(row.path(field), true) : 0);
}
}
}
JsonNode after = head(network);
if (blockHeight == height(after) && blockId.equals(hash(after))) {
return new Snapshot(before, totals, balance);
}
}
throw new IllegalStateException("确认头在采样期间变化,请重试,未记录历史证据");
}
/** 派单前建立真实基线;非零关系拒绝派单,不用任务声明的0替代链上读取。 */
public void anchor(String network, String owner, String receiver, String type) {
network(network);
require(Arrays.asList(enabledNetworks.split(",")).stream()
.anyMatch(value -> network.equals(value.trim())), "该网络尚未启用历史采集,暂不派单");
resource(type);
String ownerHex = addressHex(owner);
String receiverHex = addressHex(receiver);
Snapshot snapshot = capture(network, owner, receiver, type);
require(snapshot.balance == 0, "确认状态存在旧委托,暂不派单");
transaction.execute(status -> {
saveParameters(network, snapshot);
Map<String, Object> existing = store.one(
"SELECT * FROM rent_history_anchor WHERE network=? AND owner_address=?"
+ " AND receiver_address=? AND resource_type=? AND block_height=?",
network, ownerHex, receiverHex, type, height(snapshot.block));
if (existing == null) {
try {
store.execute("INSERT INTO rent_history_anchor (network,owner_address,"
+ "receiver_address,resource_type,block_height,block_id,balance_sun,created_at)"
+ " VALUES (?,?,?,?,?,?,?,?)", network, ownerHex, receiverHex, type,
height(snapshot.block), hash(snapshot.block), snapshot.balance, now());
} catch (DuplicateKeyException ex) {
// 并发派单采到同一基线时,只接受完全相同的不可变事实。
existing = store.one("SELECT * FROM rent_history_anchor WHERE network=?"
+ " AND owner_address=? AND receiver_address=? AND resource_type=?"
+ " AND block_height=?", network, ownerHex, receiverHex, type,
height(snapshot.block));
}
}
if (existing != null) {
require(hash(snapshot.block).equals(text(existing, "block_id"))
&& number(existing, "balance_sun") == snapshot.balance, "历史基线发生冲突");
}
return null;
});
}
/**
* 每网络一个数据库租约;RPC结束后落库前再次校验租约,过期实例不得推进游标。
* 首次从当前确认头开始,后续只沿父哈希顺序前进。停机后交易可补,参数不能回填。
*/
public void collect(String network) {
network(network);
String lease = id("H");
try {
store.execute("INSERT INTO rent_history_cursor (network,updated_at) VALUES (?,?)",
network, now());
} catch (DuplicateKeyException ex) {
// 既有网络保留原进度。
}
if (store.execute("UPDATE rent_history_cursor SET lease_owner=?,"
+ "lease_until=TIMESTAMPADD(SECOND,60,UTC_TIMESTAMP(3)),updated_at=?"
+ " WHERE network=? AND (lease_until IS NULL OR lease_until<UTC_TIMESTAMP(3))",
lease, now(), network) != 1) {
return;
}
try {
Snapshot snapshot = capture(network, probeAddress, null, null);
transaction.execute(status -> {
lockLease(network, lease);
saveParameters(network, snapshot);
return null;
});
long confirmed = height(snapshot.block);
Map<String, Object> cursor = store.one(
"SELECT * FROM rent_history_cursor WHERE network=?", network);
Map<String, Object> firstAnchor = store.one("SELECT MIN(block_height) AS first_height"
+ " FROM rent_history_anchor WHERE network=?", network);
long next = cursor.get("scanned_height") == null
? (firstAnchor.get("first_height") == null ? confirmed
: Math.min(confirmed, Math.addExact(number(firstAnchor, "first_height"), 1)))
: Math.addExact(number(cursor, "scanned_height"), 1);
require(batchSize > 0 && batchSize <= 200, "历史采集batch-size必须为1到200");
for (int i = 0; i < batchSize && next <= confirmed; i++, next++) {
final long expectedHeight = next;
JsonNode block = chain.call(network, "/walletsolidity/getblockbynum",
map("num", next, "visible", false));
require(height(block) == expectedHeight, "补采区块高度不符");
List<Map<String, Object>> events = parseEvents(block);
transaction.execute(status -> {
Map<String, Object> locked = lockLease(network, lease);
if (locked.get("scanned_height") != null) {
require(number(locked, "scanned_height") + 1 == expectedHeight
&& text(locked, "scanned_block_id").equals(parent(block)),
"确认链不连续或发生分叉,停止采集");
}
saveBlock(network, block);
Map<String, Object> saved = block(network, expectedHeight);
if (number(saved, "events_complete") == 0) {
for (Map<String, Object> event : events) {
store.execute("INSERT INTO rent_history_event (network,tx_id,block_height,"
+ "tx_index,owner_address,receiver_address,resource_type,operation,"
+ "amount_sun,locked,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
network, event.get("tx_id"), expectedHeight, event.get("tx_index"),
event.get("owner_address"), event.get("receiver_address"),
event.get("resource_type"), event.get("operation"),
event.get("amount_sun"), event.get("locked"), now());
}
store.execute("UPDATE rent_history_block SET events_complete=1"
+ " WHERE network=? AND block_height=?", network, expectedHeight);
}
store.execute("UPDATE rent_history_cursor SET scanned_height=?,scanned_block_id=?,"
+ "last_success_at=?,last_error=NULL,updated_at=? WHERE network=?",
expectedHeight, hash(block), now(), now(), network);
return null;
});
}
} catch (RuntimeException ex) {
store.execute("UPDATE rent_history_cursor SET last_error=?,updated_at=?"
+ " WHERE network=? AND lease_owner=?", "采集未完成,请检查RPC一致性、限流、表结构及确认链连续性",
now(), network, lease);
throw ex;
} finally {
store.execute("UPDATE rent_history_cursor SET lease_owner=NULL,lease_until=NULL"
+ " WHERE network=? AND lease_owner=?", network, lease);
}
}
private Map<String, Object> lockLease(String network, String lease) {
Map<String, Object> row = store.one("SELECT * FROM rent_history_cursor WHERE network=?"
+ " AND lease_owner=? AND lease_until>UTC_TIMESTAMP(3) FOR UPDATE", network, lease);
require(row != null, "历史采集租约过期");
return row;
}
private static String parent(JsonNode block) {
String parent = block.path("block_header").path("raw_data").path("parentHash").asText();
require(parent.matches("[0-9a-fA-F]{64}"), "确认区块缺少父哈希");
return parent.toLowerCase(Locale.ROOT);
}
private Map<String, Object> block(String network, long height) {
return store.one("SELECT * FROM rent_history_block WHERE network=? AND block_height=?",
network, height);
}
private void saveBlock(String network, JsonNode block) {
try {
store.execute("INSERT INTO rent_history_block (network,block_height,block_id,parent_id,"
+ "block_time,events_complete,created_at) VALUES (?,?,?,?,?,0,?)",
network, height(block), hash(block), parent(block),
positive(block.path("block_header").path("raw_data").path("timestamp"), false), now());
} catch (DuplicateKeyException ex) {
// 并发参数采集和区块补采允许命中同一区块,不允许覆盖不同哈希。
}
Map<String, Object> existing = store.one("SELECT * FROM rent_history_block WHERE network=?"
+ " AND block_height=? FOR UPDATE", network, height(block));
require(existing != null && hash(block).equals(text(existing, "block_id"))
&& parent(block).equals(text(existing, "parent_id")), "已归档确认区块发生冲突");
}
private void saveParameters(String network, Snapshot snapshot) {
saveBlock(network, snapshot.block);
Map<String, Object> row = block(network, height(snapshot.block));
long[] totals = snapshot.totals;
if (row.get("parameters_at") == null) {
store.execute("UPDATE rent_history_block SET energy_limit=?,energy_weight=?,"
+ "bandwidth_limit=?,bandwidth_weight=?,parameters_at=?"
+ " WHERE network=? AND block_height=?", totals[0], totals[1], totals[2],
totals[3], now(), network, height(snapshot.block));
} else {
require(number(row, "energy_limit") == totals[0]
&& number(row, "energy_weight") == totals[1]
&& number(row, "bandwidth_limit") == totals[2]
&& number(row, "bandwidth_weight") == totals[3], "相同确认区块资源参数不一致");
}
}
/** 解析全网成功委托事件,保留原交易顺序;未知/不完整的相关回执阻止整个区块完成。 */
static List<Map<String, Object>> parseEvents(JsonNode block) {
List<Map<String, Object>> result = new ArrayList<>();
JsonNode transactions = block.path("transactions");
require(transactions.isMissingNode() || transactions.isArray(), "区块交易列表格式不符");
int index = 0;
for (JsonNode tx : transactions) {
JsonNode contracts = tx.path("raw_data").path("contract");
require(contracts.isArray() && contracts.size() > 0, "区块内交易缺少合约,不能标记事件完整");
for (JsonNode contract : contracts) {
String operation = contract.path("type").asText();
if (!"DelegateResourceContract".equals(operation)
&& !"UnDelegateResourceContract".equals(operation)) {
continue;
}
require(contracts.size() == 1 && tx.path("ret").size() == 1
&& tx.path("ret").get(0).has("contractRet"), "相关交易缺少完整执行回执");
if (!"SUCCESS".equals(tx.path("ret").get(0).path("contractRet").asText())) {
continue;
}
String txId = tx.path("txID").asText().toLowerCase(Locale.ROOT);
require(txId.matches("[0-9a-f]{64}"), "区块交易哈希不合法");
JsonNode value = contract.path("parameter").path("value");
String owner = value.path("owner_address").asText().toLowerCase(Locale.ROOT);
String receiver = value.path("receiver_address").asText().toLowerCase(Locale.ROOT);
require(owner.matches("41[0-9a-f]{40}") && receiver.matches("41[0-9a-f]{40}"),
"区块交易地址不是TRON十六进制地址");
String type = resource(value.path("resource").asText("BANDWIDTH"));
result.add(map("tx_id", txId, "tx_index", index, "owner_address", owner,
"receiver_address", receiver, "resource_type", type,
"operation", "DelegateResourceContract".equals(operation) ? "DELEGATE" : "UNDELEGATE",
"amount_sun", positive(value.path("balance"), false),
"locked", value.path("lock").asBoolean(false) ? 1 : 0));
}
index++;
}
return result;
}
/**
* 返回null表示已明确缺少不可补造的参数/基线;扫描尚未赶上则抛异常让现有核验任务重试。
* 不查询当前资源参数,不根据请求中的本金构造证明,目标交易必须出现在完整归档区块中。
*/
public Map<String, Object> proof(String network, String txId, long targetHeight,
String owner, String receiver, String type) {
network(network);
resource(type);
require(txId != null && txId.matches("[0-9a-fA-F]{64}") && targetHeight >= 0,
"证明交易或高度无效");
String ownerHex = addressHex(owner);
String receiverHex = addressHex(receiver);
Map<String, Object> cursor = store.one("SELECT * FROM rent_history_cursor WHERE network=?", network);
require(cursor != null && cursor.get("scanned_height") != null
&& number(cursor, "scanned_height") >= targetHeight, "历史区块正在采集中,请稍后重试");
Map<String, Object> target = block(network, targetHeight);
if (target == null || target.get("parameters_at") == null) {
return null;
}
Map<String, Object> anchor = store.one("SELECT * FROM rent_history_anchor WHERE network=?"
+ " AND owner_address=? AND receiver_address=? AND resource_type=? AND block_height<?"
+ " ORDER BY block_height DESC LIMIT 1", network, ownerHex, receiverHex, type, targetHeight);
if (anchor == null) {
return null;
}
long baselineHeight = number(anchor, "block_height");
require(targetHeight - baselineHeight <= MAX_REPLAY_BLOCKS, "历史重放范围过大,需要人工核对");
List<Map<String, Object>> blocks = store.rows("SELECT * FROM rent_history_block WHERE network=?"
+ " AND block_height>? AND block_height<=? ORDER BY block_height", network, baselineHeight, targetHeight);
long expected = baselineHeight;
String previous = text(anchor, "block_id");
for (Map<String, Object> row : blocks) {
require(number(row, "block_height") == ++expected
&& number(row, "events_complete") == 1
&& previous.equals(text(row, "parent_id")), "历史区块缺失或链不连续");
previous = text(row, "block_id");
}
require(expected == targetHeight, "历史区块覆盖不足");
require(confirmations > 0 && height(head(network)) - targetHeight + 1 >= confirmations,
"历史证明交易确认深度不足");
// 再向配置节点核对目标区块哈希;节点换链/误切网络时不使用旧库证据继续结算。
JsonNode canonical = chain.call(network, "/walletsolidity/getblockbynum",
map("num", targetHeight, "visible", false));
require(height(canonical) == targetHeight && hash(canonical).equals(text(target, "block_id")),
"历史证明区块与确认链不一致");
List<Map<String, Object>> events = store.rows("SELECT * FROM rent_history_event WHERE network=?"
+ " AND owner_address=? AND receiver_address=? AND resource_type=?"
+ " AND block_height>? AND block_height<=? ORDER BY block_height,tx_index",
network, ownerHex, receiverHex, type, baselineHeight, targetHeight);
long balance = number(anchor, "balance_sun");
Map<String, Object> proof = null;
for (Map<String, Object> event : events) {
long before = balance;
balance = "DELEGATE".equals(text(event, "operation"))
? Math.addExact(balance, number(event, "amount_sun"))
: Math.subtractExact(balance, number(event, "amount_sun"));
require(balance >= 0, "历史委托本金重放出现负数");
if (txId.equalsIgnoreCase(text(event, "tx_id"))) {
require(number(event, "block_height") == targetHeight
&& "DELEGATE".equals(text(event, "operation"))
&& number(event, "locked") == 0, "目标历史交易与请求不匹配");
proof = map("network", network, "tx_id", text(event, "tx_id"),
"block_height", targetHeight, "block_id", text(target, "block_id"),
"owner", owner, "receiver", receiver, "resource_type", type,
"baseline_sun", before, "after_sun", balance,
"total_limit", number(target, "ENERGY".equals(type) ? "energy_limit" : "bandwidth_limit"),
"total_weight", number(target, "ENERGY".equals(type) ? "energy_weight" : "bandwidth_weight"),
"anchor_height", baselineHeight, "source", "EMBEDDED_SOLIDITY_REPLAY_V1");
}
}
require(proof != null && balance == number(proof, "after_sun"),
"交易未归档或同区块存在后续关系变更");
return proof;
}
/** 仅供运营查看,不返回RPC地址、认证头、私钥或响应原文。 */
public List<Map<String, Object>> status() {
return store.rows("SELECT c.network,c.scanned_height,c.scanned_block_id,c.last_success_at,"
+ "c.last_error,(SELECT MAX(b.block_height) FROM rent_history_block b"
+ " WHERE b.network=c.network AND b.parameters_at IS NOT NULL) AS last_parameter_height,"
+ "(SELECT COUNT(*) FROM rent_history_block b WHERE b.network=c.network"
+ " AND b.events_complete=1 AND b.parameters_at IS NULL) AS parameter_gap_count"
+ " FROM rent_history_cursor c ORDER BY c.network");
}
private static final class Snapshot {
private final JsonNode block;
private final long[] totals;
private final long balance;
private Snapshot(JsonNode block, long[] totals, long balance) {
this.block = block;
this.totals = totals;
this.balance = balance;
}
}
}
@@ -75,13 +75,19 @@ public final class RentalHttp {
}
public static String body(Response response) throws IOException {
return body(response, 1024 * 1024);
}
/** 完整区块JSON可能超过普通RPC的1MiB限制;仅受信区块查询允许显式提高至16MiB。 */
public static String body(Response response, int maxBytes) throws IOException {
require(maxBytes > 0 && maxBytes <= 16 * 1024 * 1024, "RPC响应上限配置错误");
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响应超过限制");
require(output.size() + count <= maxBytes, "RPC响应超过限制");
output.write(buffer, 0, count);
}
return new String(output.toByteArray(), java.nio.charset.StandardCharsets.UTF_8);
@@ -106,6 +106,8 @@ public class RentalTasks {
!= 0) {
continue;
}
chain.prepareHistory(text(initial, "network"), owner,
text(initial, "receiver_address"), type);
Boolean assigned =
tx(
() -> {
@@ -574,6 +576,7 @@ public class RentalTasks {
}
Map<String, Object> fields = new LinkedHashMap<>(proof);
fields.remove("delivery_proven");
fields.remove("history_proof");
fields.put("evidence", orders.encode(proof));
fields.put("confirmed_at", now());
store.update("transaction", number(record, "id"), fields);