自行建设,补充这部分功能,给出具体的表设计和代码实现,同云端服务端一起部署
This commit is contained in:
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);
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import org.h2.jdbcx.JdbcDataSource;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.*;
|
||||
|
||||
/** 真实DDL/SQL/事务 + 可控确认RPC;不访问业务数据库、不连接TRON、不广播交易。 */
|
||||
public class RentalHistoryTest {
|
||||
private static final String OWNER = "TMVQGm1qAQYVdetCeGRRkTWYYrLXuHK2HC";
|
||||
private static final String RECEIVER = "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf";
|
||||
private static final long SUN = 1300000000L;
|
||||
private final ObjectMapper json = new ObjectMapper();
|
||||
private final Map<Long, JsonNode> blocks = new HashMap<>();
|
||||
private RentalStore store;
|
||||
private RentalHistoryService service;
|
||||
private RentalChain chain;
|
||||
private long currentHead;
|
||||
private long relation;
|
||||
private long energyLimit = 60000000;
|
||||
private int changingHeads;
|
||||
private boolean invalidParameters;
|
||||
private boolean rpcFailure;
|
||||
private int calls;
|
||||
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
JdbcDataSource source = new JdbcDataSource();
|
||||
source.setURL("jdbc:h2:mem:" + UUID.randomUUID()
|
||||
+ ";MODE=MySQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=10000");
|
||||
JdbcTemplate jdbc = new JdbcTemplate(source);
|
||||
// H2 1.4没有MySQL UTC_TIMESTAMP;仅为数据库时钟函数提供等价UTC测试适配。
|
||||
jdbc.execute("CREATE ALIAS UTC_TIMESTAMP FOR \"com.ruoyi.system.rental.RentalHistoryTest.utcTimestamp\"");
|
||||
store = new RentalStore(jdbc);
|
||||
String ddl = new String(Files.readAllBytes(Paths.get("../sql/rent_history_init.sql")),
|
||||
StandardCharsets.UTF_8).replaceAll("(?m)^--.*$", "")
|
||||
.replace("ENGINE=InnoDB ROW_FORMAT=DYNAMIC DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin", "");
|
||||
for (String statement : ddl.split(";")) {
|
||||
if (!statement.trim().isEmpty()) {
|
||||
jdbc.execute(statement);
|
||||
}
|
||||
}
|
||||
RentalChain rpc = new RentalChain(json) {
|
||||
@Override
|
||||
public JsonNode call(String network, String path, Map<String, Object> body) {
|
||||
calls++;
|
||||
if (rpcFailure) {
|
||||
throw new IllegalStateException("controlled RPC failure");
|
||||
}
|
||||
if (path.endsWith("getnowblock")) {
|
||||
long height = changingHeads > 0 ? currentHead + changingHeads-- : currentHead;
|
||||
return block(height);
|
||||
}
|
||||
if (path.endsWith("getaccountresource")) {
|
||||
return json.valueToTree(invalidParameters ? map("TotalEnergyLimit", 0)
|
||||
: map("TotalEnergyLimit", energyLimit, "TotalEnergyWeight", 1000000,
|
||||
"TotalNetLimit", 1500000, "TotalNetWeight", 1000000));
|
||||
}
|
||||
if (path.equals("/walletsolidity/getdelegatedresourcev2")) {
|
||||
return json.valueToTree(Boolean.TRUE.equals(body.get("lock")) ? map()
|
||||
: map("delegatedResource", Arrays.asList(map("frozen_balance_for_energy", relation))));
|
||||
}
|
||||
if (path.endsWith("getblockbynum")) {
|
||||
return block(number(body, "num"));
|
||||
}
|
||||
if (path.equals("/wallet/getdelegatedresourcev2")) {
|
||||
return json.valueToTree(map("delegatedResource", Arrays.asList(
|
||||
map("frozen_balance_for_energy", SUN))));
|
||||
}
|
||||
if (path.endsWith("gettransactionbyid") || path.endsWith("gettransactioninfobyid")) {
|
||||
for (Map.Entry<Long, JsonNode> entry : blocks.entrySet()) {
|
||||
for (JsonNode tx : entry.getValue().path("transactions")) {
|
||||
if (text(body, "value").equals(tx.path("txID").asText())) {
|
||||
return path.endsWith("gettransactionbyid") ? tx
|
||||
: json.valueToTree(map("blockNumber", entry.getKey(),
|
||||
"blockTimeStamp", 1700000000000L + entry.getKey() * 3000));
|
||||
}
|
||||
}
|
||||
}
|
||||
return json.createObjectNode();
|
||||
}
|
||||
throw new AssertionError("unexpected RPC " + path);
|
||||
}
|
||||
};
|
||||
service = new RentalHistoryService(store, rpc, new DataSourceTransactionManager(source));
|
||||
chain = rpc;
|
||||
setField(service, "confirmations", 1L);
|
||||
currentHead = 100;
|
||||
}
|
||||
|
||||
private static String hash(long number) {
|
||||
return String.format("%064x", number);
|
||||
}
|
||||
|
||||
public static java.sql.Timestamp utcTimestamp(int precision) {
|
||||
return java.sql.Timestamp.valueOf(now());
|
||||
}
|
||||
|
||||
private static void setField(Object target, String name, Object value) throws Exception {
|
||||
java.lang.reflect.Field field = target instanceof RentalChain
|
||||
? RentalChain.class.getDeclaredField(name) : RentalHistoryService.class.getDeclaredField(name);
|
||||
field.setAccessible(true);
|
||||
field.set(target, value);
|
||||
}
|
||||
|
||||
private JsonNode block(long number) {
|
||||
return blocks.computeIfAbsent(number, height -> json.valueToTree(map(
|
||||
"blockID", hash(height), "block_header", map("raw_data", map(
|
||||
"number", height, "parentHash", hash(height - 1),
|
||||
"timestamp", 1700000000000L + height * 3000)), "transactions", new ArrayList<>())));
|
||||
}
|
||||
|
||||
private JsonNode event(long tx, String operation, String type, long sun) {
|
||||
return json.valueToTree(map("txID", hash(tx), "raw_data", map("contract", Arrays.asList(map(
|
||||
"type", operation, "parameter", map("value", map(
|
||||
"owner_address", RentalHistoryService.addressHex(OWNER),
|
||||
"receiver_address", RentalHistoryService.addressHex(RECEIVER),
|
||||
"resource", type, "balance", sun, "lock", false))))),
|
||||
"ret", Arrays.asList(map("contractRet", "SUCCESS"))));
|
||||
}
|
||||
|
||||
private void transactions(long height, JsonNode... transactions) {
|
||||
((ObjectNode) block(height)).set("transactions", json.valueToTree(Arrays.asList(transactions)));
|
||||
}
|
||||
|
||||
private void collect(long height) {
|
||||
currentHead = height;
|
||||
service.collect("NILE");
|
||||
}
|
||||
|
||||
private Map<String, Object> proof(long tx, long height) {
|
||||
return service.proof("NILE", hash(tx), height, OWNER, RECEIVER, "ENERGY");
|
||||
}
|
||||
|
||||
private void anchor() {
|
||||
service.anchor("NILE", OWNER, RECEIVER, "ENERGY");
|
||||
}
|
||||
|
||||
private void rejects(Runnable action) {
|
||||
try {
|
||||
action.run();
|
||||
fail("expected fail-closed rejection");
|
||||
} catch (IllegalArgumentException | IllegalStateException expected) {
|
||||
// 所有拒绝必须发生在写入成功状态/返回证明之前。
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void coherentArchiveProducesProofAndPreservesOldParameters() {
|
||||
anchor();
|
||||
collect(100);
|
||||
transactions(101, event(1001, "DelegateResourceContract", "ENERGY", SUN));
|
||||
collect(101);
|
||||
energyLimit = 90000000;
|
||||
collect(102);
|
||||
Map<String, Object> proof = proof(1001, 101);
|
||||
assertEquals(0, number(proof, "baseline_sun"));
|
||||
assertEquals(SUN, number(proof, "after_sun"));
|
||||
assertEquals(60000000, number(proof, "total_limit"));
|
||||
assertEquals(78000, quantity(SUN, number(proof, "total_limit"), number(proof, "total_weight")));
|
||||
assertEquals(hash(101), proof.get("block_id"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void missedParameterHeightIsNotFilledWithCurrentState() {
|
||||
anchor();
|
||||
collect(100);
|
||||
transactions(101, event(1001, "DelegateResourceContract", "ENERGY", SUN));
|
||||
collect(102);
|
||||
assertNull(proof(1001, 101));
|
||||
assertEquals(1, number(service.status().get(0), "parameter_gap_count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noPreTransactionAnchorCannotProduceProof() {
|
||||
collect(100);
|
||||
transactions(101, event(1001, "DelegateResourceContract", "ENERGY", SUN));
|
||||
collect(101);
|
||||
assertNull(proof(1001, 101));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void firstCollectorStartsFromEarlierAnchorInsteadOfSkippingItsEvents() {
|
||||
anchor();
|
||||
transactions(101, event(1001, "DelegateResourceContract", "ENERGY", SUN));
|
||||
collect(101);
|
||||
assertNotNull(proof(1001, 101));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void repeatedCollectionAndAnchorAreIdempotent() {
|
||||
anchor();
|
||||
anchor();
|
||||
collect(100);
|
||||
transactions(101, event(1001, "DelegateResourceContract", "ENERGY", SUN));
|
||||
collect(101);
|
||||
collect(101);
|
||||
assertEquals(1, number(store.one("SELECT COUNT(*) AS n FROM rent_history_anchor"), "n"));
|
||||
assertEquals(1, number(store.one("SELECT COUNT(*) AS n FROM rent_history_event"), "n"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void failedDelegateIsExcludedFromReplay() {
|
||||
JsonNode failed = event(1001, "DelegateResourceContract", "ENERGY", SUN);
|
||||
((ObjectNode) failed.path("ret").get(0)).put("contractRet", "REVERT");
|
||||
transactions(101, failed, event(1002, "DelegateResourceContract", "ENERGY", SUN));
|
||||
anchor();
|
||||
collect(101);
|
||||
assertEquals(0, number(proof(1002, 101), "baseline_sun"));
|
||||
rejects(() -> proof(1001, 101));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void missingReceiptPreventsPartialBlockCommit() {
|
||||
anchor();
|
||||
collect(100);
|
||||
JsonNode incomplete = event(1002, "DelegateResourceContract", "ENERGY", SUN);
|
||||
((ObjectNode) incomplete).remove("ret");
|
||||
transactions(101, event(1001, "DelegateResourceContract", "ENERGY", SUN), incomplete);
|
||||
rejects(() -> collect(101));
|
||||
assertEquals(100, number(service.status().get(0), "scanned_height"));
|
||||
assertEquals(0, number(store.one("SELECT COUNT(*) AS n FROM rent_history_event"), "n"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parentMismatchStopsCursor() {
|
||||
collect(100);
|
||||
((ObjectNode) block(101).path("block_header").path("raw_data")).put("parentHash", hash(99));
|
||||
rejects(() -> collect(101));
|
||||
assertEquals(100, number(service.status().get(0), "scanned_height"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void changedCanonicalTargetRefusesExistingProof() {
|
||||
anchor();
|
||||
transactions(101, event(1001, "DelegateResourceContract", "ENERGY", SUN));
|
||||
collect(101);
|
||||
((ObjectNode) block(101)).put("blockID", hash(999));
|
||||
rejects(() -> proof(1001, 101));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void movingConfirmedHeadDoesNotWriteAnAnchor() {
|
||||
changingHeads = 6;
|
||||
rejects(this::anchor);
|
||||
assertEquals(0, number(store.one("SELECT COUNT(*) AS n FROM rent_history_anchor"), "n"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invalidParametersCannotBeStored() {
|
||||
invalidParameters = true;
|
||||
rejects(this::anchor);
|
||||
assertEquals(0, number(store.one("SELECT COUNT(*) AS n FROM rent_history_block"), "n"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nonzeroConfirmedRelationPreventsDispatchBaseline() {
|
||||
relation = 1;
|
||||
rejects(this::anchor);
|
||||
assertEquals(0, number(store.one("SELECT COUNT(*) AS n FROM rent_history_anchor"), "n"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void scannerLagIsRetryableInsteadOfMissingEvidence() {
|
||||
anchor();
|
||||
collect(100);
|
||||
rejects(() -> proof(1001, 101));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void otherResourceEventsDoNotPolluteEnergyProof() {
|
||||
anchor();
|
||||
transactions(101, event(1001, "DelegateResourceContract", "BANDWIDTH", 1000000),
|
||||
event(1002, "DelegateResourceContract", "ENERGY", SUN));
|
||||
collect(101);
|
||||
assertEquals(0, number(proof(1002, 101), "baseline_sun"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bandwidthUsesOwnHistoricalParameters() {
|
||||
service.anchor("NILE", OWNER, RECEIVER, "BANDWIDTH");
|
||||
transactions(101, event(1001, "DelegateResourceContract", "BANDWIDTH", SUN));
|
||||
collect(101);
|
||||
Map<String, Object> proof = service.proof("NILE", hash(1001), 101, OWNER, RECEIVER, "BANDWIDTH");
|
||||
assertEquals(1500000, number(proof, "total_limit"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void replayIncludesIntermediateDelegationAndReclaim() {
|
||||
anchor();
|
||||
collect(100);
|
||||
transactions(101, event(1001, "DelegateResourceContract", "ENERGY", 1000000));
|
||||
transactions(102, event(1002, "UnDelegateResourceContract", "ENERGY", 1000000));
|
||||
transactions(103, event(1003, "DelegateResourceContract", "ENERGY", SUN));
|
||||
collect(103);
|
||||
assertEquals(0, number(proof(1003, 103), "baseline_sun"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void negativeReplayBalanceIsRejected() {
|
||||
anchor();
|
||||
transactions(101, event(1001, "UnDelegateResourceContract", "ENERGY", 1),
|
||||
event(1002, "DelegateResourceContract", "ENERGY", SUN));
|
||||
collect(101);
|
||||
rejects(() -> proof(1002, 101));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void laterSameBlockReclaimCannotBeReportedAsDelivered() {
|
||||
anchor();
|
||||
transactions(101, event(1001, "DelegateResourceContract", "ENERGY", SUN),
|
||||
event(1002, "UnDelegateResourceContract", "ENERGY", SUN));
|
||||
collect(101);
|
||||
rejects(() -> proof(1001, 101));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deletedIntermediateBlockIsRejected() {
|
||||
anchor();
|
||||
collect(100);
|
||||
transactions(102, event(1001, "DelegateResourceContract", "ENERGY", SUN));
|
||||
collect(102);
|
||||
store.execute("DELETE FROM rent_history_block WHERE network='NILE' AND block_height=101");
|
||||
rejects(() -> proof(1001, 102));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void lockedTargetCannotProduceNonlockedDeliveryProof() {
|
||||
anchor();
|
||||
JsonNode locked = event(1001, "DelegateResourceContract", "ENERGY", SUN);
|
||||
((ObjectNode) locked.path("raw_data").path("contract").get(0).path("parameter").path("value")).put("lock", true);
|
||||
transactions(101, locked);
|
||||
collect(101);
|
||||
rejects(() -> proof(1001, 101));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void networkLeasePreventsSecondCollectorRpcCalls() {
|
||||
collect(100);
|
||||
store.execute("UPDATE rent_history_cursor SET lease_owner='other',"
|
||||
+ "lease_until=TIMESTAMPADD(SECOND,60,UTC_TIMESTAMP(3)) WHERE network='NILE'");
|
||||
int before = calls;
|
||||
collect(101);
|
||||
assertEquals(before, calls);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rpcFailureReleasesLeaseAndDoesNotAdvanceCursor() {
|
||||
collect(100);
|
||||
rpcFailure = true;
|
||||
rejects(() -> collect(101));
|
||||
Map<String, Object> status = store.one("SELECT * FROM rent_history_cursor WHERE network='NILE'");
|
||||
assertEquals(100, number(status, "scanned_height"));
|
||||
assertNull(status.get("lease_owner"));
|
||||
assertFalse(text(status, "last_error").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sameHeightParameterConflictNeverOverwritesStoredValues() {
|
||||
collect(100);
|
||||
energyLimit++;
|
||||
rejects(() -> collect(100));
|
||||
assertEquals(60000000, number(store.one("SELECT * FROM rent_history_block WHERE block_height=100"), "energy_limit"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invalidInputsAreRejectedBeforeRpc() {
|
||||
rejects(() -> service.anchor("OTHER", OWNER, RECEIVER, "ENERGY"));
|
||||
rejects(() -> service.anchor("MAINNET", OWNER, RECEIVER, "ENERGY"));
|
||||
rejects(() -> service.proof("NILE", "bad", 1, OWNER, RECEIVER, "ENERGY"));
|
||||
rejects(() -> service.proof("NILE", hash(1), 1, "bad", RECEIVER, "ENERGY"));
|
||||
assertEquals(0, calls);
|
||||
}
|
||||
|
||||
private void embeddedMode() throws Exception {
|
||||
org.springframework.beans.factory.support.DefaultListableBeanFactory factory =
|
||||
new org.springframework.beans.factory.support.DefaultListableBeanFactory();
|
||||
factory.registerSingleton("history", service);
|
||||
setField(chain, "embeddedHistory", true);
|
||||
setField(chain, "historyService", factory.getBeanProvider(RentalHistoryService.class));
|
||||
setField(chain, "confirmations", 1L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void actualChainVerificationUsesInternalProofAndReturnsAuditEvidence() throws Exception {
|
||||
embeddedMode();
|
||||
chain.prepareHistory("NILE", OWNER, RECEIVER, "ENERGY");
|
||||
transactions(101, event(1001, "DelegateResourceContract", "ENERGY", SUN));
|
||||
collect(101);
|
||||
Map<String, Object> verified = chain.verify(map("network", "NILE", "task_type", "DELEGATE",
|
||||
"delegate_sun", SUN, "resource_type", "ENERGY"), hash(1001), OWNER, RECEIVER);
|
||||
assertEquals(Boolean.TRUE, verified.get("delivery_proven"));
|
||||
assertEquals(78000, number(verified, "verified_resource_quantity"));
|
||||
assertEquals("EMBEDDED_SOLIDITY_REPLAY_V1", ((Map<?, ?>) verified.get("history_proof")).get("source"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void actualChainVerificationKeepsManualPathWhenHistoricalParameterWasMissed() throws Exception {
|
||||
embeddedMode();
|
||||
chain.prepareHistory("NILE", OWNER, RECEIVER, "ENERGY");
|
||||
collect(100);
|
||||
transactions(101, event(1001, "DelegateResourceContract", "ENERGY", SUN));
|
||||
collect(102);
|
||||
Map<String, Object> verified = chain.verify(map("network", "NILE", "task_type", "DELEGATE",
|
||||
"delegate_sun", SUN, "resource_type", "ENERGY"), hash(1001), OWNER, RECEIVER);
|
||||
assertEquals("CONFIRMED", verified.get("status"));
|
||||
assertEquals(Boolean.FALSE, verified.get("delivery_proven"));
|
||||
assertFalse(verified.containsKey("verified_resource_quantity"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void proofEndpointRequiresConfiguredConfirmationDepth() throws Exception {
|
||||
anchor();
|
||||
transactions(101, event(1001, "DelegateResourceContract", "ENERGY", SUN));
|
||||
collect(101);
|
||||
setField(service, "confirmations", 19L);
|
||||
rejects(() -> proof(1001, 101));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void historyHttpEndpointsAreRestrictedToOperationsPermission() throws Exception {
|
||||
for (java.lang.reflect.Method method : RentalHistoryController.class.getDeclaredMethods()) {
|
||||
String expression = method.getAnnotation(
|
||||
org.springframework.security.access.prepost.PreAuthorize.class).value();
|
||||
assertEquals("@ss.hasPermi('rent:manage:audit')", expression);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fullBlockResponseCanExceedOrdinaryRpcLimitButStaysBounded() throws Exception {
|
||||
byte[] bytes = new byte[1024 * 1024 + 1];
|
||||
okhttp3.Request request = new okhttp3.Request.Builder().url("https://rpc.invalid/").build();
|
||||
try (okhttp3.Response response = new okhttp3.Response.Builder().request(request)
|
||||
.protocol(okhttp3.Protocol.HTTP_1_1).code(200).message("OK")
|
||||
.body(okhttp3.ResponseBody.create(null, bytes)).build()) {
|
||||
assertEquals(bytes.length, RentalHttp.body(response, 16 * 1024 * 1024).length());
|
||||
}
|
||||
try (okhttp3.Response response = new okhttp3.Response.Builder().request(request)
|
||||
.protocol(okhttp3.Protocol.HTTP_1_1).code(200).message("OK")
|
||||
.body(okhttp3.ResponseBody.create(null, bytes)).build()) {
|
||||
try {
|
||||
RentalHttp.body(response);
|
||||
fail("ordinary RPC must remain bounded");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
// 不扩大回调或普通RPC的响应上限。
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user