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

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

@@ -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的响应上限。
}
}
}
}