尽量服用,和优化采样区块,交易所在区块的资源参数 获取不需要每次获取有下单租赁订单都获取一遍,应该是全局异步获取是不是就可以,帮我设计合理方案。 和清理逻辑

This commit is contained in:
lu7213 committed 2026-10-31 19:10:27 -04:00
1 parent 13665668ac
commit 1538cd0819
24 files changed
+1894 -230

No files matched your search

@@ -36,6 +36,8 @@ public class RentalBusinessTest {
private long wallet;
private long node;
private boolean proofAvailable = true;
private long verifiedResourceQuantity = 78000;
private long verificationBlockAgeSeconds = 5;
private boolean receiverActivated;
private boolean activationRpcFailed;
private int activationChecks;
@@ -696,7 +698,7 @@ public class RentalBusinessTest {
"block_height",
101,
"block_time",
now().minusSeconds(5),
now().minusSeconds(verificationBlockAgeSeconds),
"after_sun",
"DELEGATE".equals(text(task, "task_type"))
? task.get("delegate_sun")
@@ -706,7 +708,7 @@ public class RentalBusinessTest {
"verified_total_weight",
1000000,
"verified_resource_quantity",
78000,
verifiedResourceQuantity,
"delivery_proven",
proofAvailable);
}
@@ -1141,6 +1143,111 @@ public class RentalBusinessTest {
ADDRESS)));
}
@Test
public void orderAndTaskEventsArePublishedOnlyAfterCommit() throws Exception {
List<RentalDeliveryEvents> events = new ArrayList<>();
org.springframework.context.ApplicationEventPublisher publisher = event -> events.add((RentalDeliveryEvents) event);
injectPublisher(orders, publisher);
injectPublisher(tasks, publisher);
long orderId = tx.execute(status -> {
long id = number(create("AFTER-COMMIT"), "id");
assertTrue(events.isEmpty());
return id;
});
assertEquals(1, events.size());
assertTrue(events.get(0).order);
assertEquals(orderId, events.get(0).id);
tx.execute(status -> {
tasks.dispatch(orderId);
assertEquals(1, events.size());
return null;
});
assertEquals(2, events.size());
assertFalse(events.get(1).order);
assertEquals(node, events.get(1).id);
}
@Test
public void rolledBackOrderDoesNotScheduleDelivery() throws Exception {
List<Object> events = new ArrayList<>();
injectPublisher(orders, events::add);
tx.execute(status -> {
create("ROLLBACK-DELIVERY");
status.setRollbackOnly();
return null;
});
assertTrue(events.isEmpty());
assertNull(store.one("SELECT id FROM rent_order WHERE merchant_order_no='ROLLBACK-DELIVERY'"));
}
@Test
public void committedOrderDispatchesOnIndependentDeliveryWorker() throws Exception {
org.springframework.beans.factory.support.DefaultListableBeanFactory factory =
new org.springframework.beans.factory.support.DefaultListableBeanFactory();
RentalSocket socket = new RentalSocket(store, identity, tasks, json);
factory.registerSingleton("tasks", tasks);
factory.registerSingleton("socket", socket);
RentalDeliveryDispatcher dispatcher = new RentalDeliveryDispatcher(
factory.getBeanProvider(RentalTasks.class), factory.getBeanProvider(RentalSocket.class));
dispatcher.start();
CountDownLatch taskCommitted = new CountDownLatch(1);
java.util.concurrent.atomic.AtomicReference<String> dispatchThread = new java.util.concurrent.atomic.AtomicReference<>();
injectPublisher(orders, event -> dispatcher.receive((RentalDeliveryEvents) event));
injectPublisher(tasks, event -> {
dispatchThread.set(Thread.currentThread().getName());
taskCommitted.countDown();
});
try {
long id = number(create("IMMEDIATE-DISPATCH"), "id");
assertTrue(taskCommitted.await(5, TimeUnit.SECONDS));
assertTrue(dispatchThread.get().startsWith("rental-delivery-"));
assertNotNull(store.one("SELECT id FROM rent_task WHERE order_id=?", id));
} finally {
dispatcher.close();
}
}
private void injectPublisher(Object target, org.springframework.context.ApplicationEventPublisher publisher)
throws Exception {
java.lang.reflect.Field field = target.getClass().getDeclaredField("deliveryEvents");
field.setAccessible(true);
field.set(target, publisher);
}
@Test
public void historyCleanupReadsRealBusinessSchemaAndKeepsFunds() throws Exception {
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()) { store.execute(statement); }
}
// 此测试的完整业务DDL来自setup;清理器只能读业务状态,不能改动账户/流水。
store.execute("CREATE ALIAS IF NOT EXISTS UTC_TIMESTAMP FOR \"com.ruoyi.system.rental.RentalHistoryTest.utcTimestamp\"");
Map<String, Object> oldAccount = new LinkedHashMap<>(store.get("account", payer, false));
Map<String, Object> order = create("CLEANUP-PRESERVE-FUNDS");
Map<String, Object> heldAccount = new LinkedHashMap<>(store.get("account", payer, false));
store.execute("INSERT INTO rent_history_cursor (network,scanned_height,scanned_block_id,updated_at)"
+ " VALUES ('NILE',30000,?,?)", String.format("%064x", 30000), now());
store.execute("INSERT INTO rent_history_block (network,block_height,block_id,parent_id,block_time,"
+ "events_complete,created_at) VALUES ('NILE',100,?,?,?,1,?)", String.format("%064x", 100),
String.format("%064x", 99), System.currentTimeMillis() - 45L * 86400000,
now().minusDays(45));
java.nio.file.Path directory = Files.createTempDirectory("rental-history-cleanup-business-");
RentalHistoryCleaner cleaner = new RentalHistoryCleaner(store, json, new RentalHistoryArchive(json), tx.getTransactionManager());
java.lang.reflect.Field archiveDirectory = RentalHistoryCleaner.class.getDeclaredField("archiveDirectory");
archiveDirectory.setAccessible(true);
archiveDirectory.set(cleaner, directory.toString());
assertEquals(1, cleaner.clean("NILE"));
assertEquals(heldAccount, store.get("account", payer, false));
assertEquals("HELD", text(store.get("order", number(order, "id"), false), "fund_status"));
assertEquals(1, store.rows("SELECT id FROM rent_ledger WHERE order_id=?", order.get("id")).size());
assertTrue(amount(oldAccount, "available_amount").compareTo(amount(heldAccount, "available_amount")) > 0);
// 只删除本测试创建的临时归档文件,不访问部署归档目录。
for (java.io.File file : directory.toFile().listFiles()) { Files.delete(file.toPath()); }
Files.delete(directory);
}
private void expectFailure(Runnable action) {
try {
action.run();
@@ -1296,7 +1403,15 @@ public class RentalBusinessTest {
tasks.dispatch(deliveryOrder);
RentalWorkers workers = new RentalWorkers(store, tasks, socket, identity);
workers.validateDeliveryIntervals();
workers.pushTasks();
ExecutorService competingPushes = Executors.newFixedThreadPool(2);
try {
Future<?> immediate = competingPushes.submit(() -> socket.push(node));
Future<?> periodic = competingPushes.submit(workers::pushTasks);
immediate.get(5, TimeUnit.SECONDS);
periodic.get(5, TimeUnit.SECONDS);
} finally {
competingPushes.shutdownNow();
}
Map<String, Object> delivered = store.one("SELECT * FROM rent_task WHERE order_id=?", deliveryOrder);
assertNotNull(delivered);
assertEquals(1, number(delivered, "delivery_count"));
@@ -1792,6 +1907,16 @@ public class RentalBusinessTest {
Map<String, Object> order = store.get("order", id, false);
assertEquals("MANUAL_REVIEW", text(order, "status"));
assertEquals("HELD", text(order, "fund_status"));
Map<String, Object> diagnostic = store.one("SELECT * FROM rent_event WHERE object_type='ORDER'"
+ " AND object_id=? AND action='DELIVERY_REVIEW'", id);
assertTrue(text(diagnostic, "reason").contains("缺少完整历史履约证明"));
List<Map<String, Object>> visible = new RentalQueries(store).list("order", 10L, 1);
assertEquals(text(diagnostic, "reason"), text(visible.get(0), "fulfillment_reason"));
assertFalse(visible.get(0).containsKey("review_evidence"));
assertTrue(new RentalQueries(store).list("order", 999L, 1).isEmpty());
store.execute("DELETE FROM rent_event WHERE id=?", diagnostic.get("id"));
assertTrue(text(new RentalQueries(store).list("order", 10L, 1).get(0), "fulfillment_reason")
.contains("缺少完整历史履约证明"));
expectFailure(() -> tasks.resolveRecovered(id, 99, "not recovered"));
store.update("order", id, map("next_reclaim_at", after(-1)));
tasks.reclaim(id);
@@ -1815,6 +1940,31 @@ public class RentalBusinessTest {
assertEquals("FAILED", text(store.get("order", id, false), "status"));
}
@Test
public void insufficientQuantityAndExpiredLeaseAreBothRecordedWithoutCharging() {
verifiedResourceQuantity = 1;
verificationBlockAgeSeconds = 100000;
long id = confirmed("INSUFFICIENT-EXPIRED");
Map<String, Object> order = store.get("order", id, false);
assertEquals("MANUAL_REVIEW", text(order, "status"));
assertEquals("HELD", text(order, "fund_status"));
String reason = text(new RentalQueries(store).list("order", null, 1).get(0), "fulfillment_reason");
assertTrue(reason.contains("实际核验资源数量不足"));
assertTrue(reason.contains("核验完成时租期已结束"));
assertFalse(reason.contains("缺少完整历史履约证明"));
}
@Test
public void fulfillmentDiagnosticsRespectBoundaryAndDoNotGuessMissingProofQuantity() {
java.time.Instant expiry = java.time.Instant.parse("2026-10-31T12:00:00Z");
assertEquals("", RentalDeliveryDiagnostics.explain(true, 18L, 18, expiry, expiry.minusMillis(1)));
assertTrue(RentalDeliveryDiagnostics.explain(true, 18L, 18, expiry, expiry).contains("租期已结束"));
assertTrue(RentalDeliveryDiagnostics.explain(false, null, 18, expiry, expiry.minusMillis(1))
.contains("缺少完整历史履约证明"));
assertFalse(RentalDeliveryDiagnostics.explain(false, null, 18, expiry, expiry.minusMillis(1))
.contains("实际核验资源数量不足"));
}
@Test
public void merchantAndSupplierSameAccountNoDoubleLockOrWrongBalance() {
store.update("node", node, map("user_id", 10));
@@ -0,0 +1,440 @@
package com.ruoyi.system.rental;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.h2.jdbcx.JdbcDataSource;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.*;
import static com.ruoyi.system.rental.RentalValues.*;
import static org.junit.Assert.*;
/** 真实历史DDL、H2事务/行锁和临时归档目录;业务表为只读查询所需的受控投影,不接触项目数据库。 */
public class RentalHistoryCleanupTest {
private static final String OWNER = "TMVQGm1qAQYVdetCeGRRkTWYYrLXuHK2HC";
private static final String RECEIVER = "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf";
@Rule public TemporaryFolder temporary = new TemporaryFolder();
private final ObjectMapper json = new ObjectMapper();
private RentalStore store;
private DataSourceTransactionManager manager;
private RentalHistoryCleaner cleaner;
private Path archives;
private LocalDateTime old;
@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);
jdbc.execute("CREATE ALIAS UTC_TIMESTAMP FOR \"com.ruoyi.system.rental.RentalHistoryTest.utcTimestamp\"");
store = new RentalStore(jdbc);
manager = new DataSourceTransactionManager(source);
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); }
}
jdbc.execute("CREATE TABLE rent_order (id BIGINT PRIMARY KEY,network VARCHAR(16),resource_type VARCHAR(16),"
+ "status VARCHAR(32),wallet_id BIGINT,fund_status VARCHAR(16),relation_slot INT,"
+ "reclaim_status VARCHAR(24),service_expires_at TIMESTAMP,updated_at TIMESTAMP)");
jdbc.execute("CREATE TABLE rent_task (id BIGINT PRIMARY KEY,order_id BIGINT,network VARCHAR(16),"
+ "resource_type VARCHAR(16),intent LONGTEXT,status VARCHAR(32),wallet_execution_slot INT,"
+ "reservation_status VARCHAR(16),updated_at TIMESTAMP)");
jdbc.execute("CREATE TABLE rent_transaction (id BIGINT PRIMARY KEY,task_id BIGINT,block_height BIGINT,"
+ "status VARCHAR(32),updated_at TIMESTAMP)");
jdbc.execute("CREATE TABLE rent_ledger (id BIGINT PRIMARY KEY,amount DECIMAL(30,6))");
store.execute("INSERT INTO rent_ledger VALUES (1,123.456789)");
archives = temporary.newFolder("archives").toPath();
old = now().minusDays(45);
store.execute("INSERT INTO rent_history_cursor (network,scanned_height,scanned_block_id,updated_at)"
+ " VALUES ('NILE',30000,?,?)", hash(30000), now());
block("NILE", 100, old, old, 1);
block("NILE", 30000, now(), now(), 1);
cleaner = cleaner(new RentalHistoryArchive(json));
}
private RentalHistoryCleaner cleaner(RentalHistoryArchive archive) throws Exception {
RentalHistoryCleaner value = new RentalHistoryCleaner(store, json, archive, manager);
field(value, "archiveDirectory", archives.toString());
return value;
}
private static void field(Object target, String name, Object value) throws Exception {
java.lang.reflect.Field field = target.getClass().getDeclaredField(name);
field.setAccessible(true);
field.set(target, value);
}
private static String hash(long height) { return String.format("%064x", height); }
private void block(String network, long height, LocalDateTime chainTime, LocalDateTime stored, int complete) {
store.execute("INSERT INTO rent_history_block (network,block_height,block_id,parent_id,block_time,"
+ "events_complete,created_at) VALUES (?,?,?,?,?,?,?)", network, height, hash(height),
hash(height - 1), chainTime.toInstant(ZoneOffset.UTC).toEpochMilli(), complete, stored);
}
private void anchor(long height) {
store.execute("INSERT INTO rent_history_anchor VALUES ('NILE',?,?,'ENERGY',?,?,0,?)",
RentalHistoryService.addressHex(OWNER), RentalHistoryService.addressHex(RECEIVER), height, hash(height), old);
}
private void event(long height, long tx, int index) {
store.execute("INSERT INTO rent_history_event VALUES ('NILE',?,?,?,?,?,'ENERGY','DELEGATE',1000000,0,?)",
hash(tx), height, index, RentalHistoryService.addressHex(OWNER),
RentalHistoryService.addressHex(RECEIVER), old);
}
private void task(boolean closed) throws Exception {
store.execute("INSERT INTO rent_order VALUES (1,'NILE','ENERGY',?,1,?,NULL,?, ?,?)",
closed ? "SUCCESS" : "MANUAL_REVIEW", closed ? "CHARGED" : "HELD",
closed ? "DONE" : "MANUAL_REVIEW", old, old);
store.execute("INSERT INTO rent_task VALUES (1,1,'NILE','ENERGY',?,'VERIFIED',NULL,'COMMITTED',?)",
json.writeValueAsString(map("owner", OWNER, "receiver", RECEIVER)), old);
store.execute("INSERT INTO rent_transaction VALUES (1,1,101,'CONFIRMED',?)", old);
}
private long count(String table) { return number(store.one("SELECT COUNT(*) AS n FROM " + table), "n"); }
private void fails(Runnable action) {
try { action.run(); fail("must abort deletion"); }
catch (IllegalStateException | IllegalArgumentException expected) { }
}
@Test
public void expiredFactsAreArchivedBeforeDeletionAndCursorIsKept() throws Exception {
anchor(100);
event(100, 1001, 0);
assertEquals(3, cleaner.clean("NILE"));
assertNull(store.one("SELECT * FROM rent_history_block WHERE block_height=100"));
assertEquals(0, count("rent_history_event"));
assertEquals(0, count("rent_history_anchor"));
assertEquals(30000, number(store.one("SELECT * FROM rent_history_cursor"), "scanned_height"));
assertNull(store.one("SELECT * FROM rent_history_cursor").get("cleanup_owner"));
long archivedEvents = 0, archivedBlocks = 0, archivedAnchors = 0;
for (java.io.File file : archives.toFile().listFiles()) {
byte[] bytes = Files.readAllBytes(file.toPath());
String digest = javax.xml.bind.DatatypeConverter.printHexBinary(
java.security.MessageDigest.getInstance("SHA-256").digest(bytes)).toLowerCase();
assertTrue(file.getName().endsWith(digest + ".json"));
JsonNode data = json.readTree(bytes);
assertEquals("RENT_HISTORY_ARCHIVE_V1", data.path("format").asText());
archivedEvents += data.path("events").size();
archivedBlocks += data.path("blocks").size();
archivedAnchors += data.path("anchors").size();
}
assertEquals(1, archivedEvents);
assertEquals(1, archivedBlocks);
assertEquals(1, archivedAnchors);
assertEquals(0, cleaner.clean("NILE"));
assertEquals(1, count("rent_ledger"));
}
@Test
public void liveManualOrderPinsItsOldBaselineAndEntireReplayRange() throws Exception {
anchor(100);
block("NILE", 101, old, old, 1);
event(101, 1001, 0);
task(false);
assertEquals(0, cleaner.clean("NILE"));
assertEquals(1, count("rent_history_anchor"));
assertEquals(1, count("rent_history_event"));
assertEquals(3, count("rent_history_block"));
assertEquals("HELD", text(store.one("SELECT * FROM rent_order"), "fund_status"));
assertEquals(1, count("rent_task"));
assertEquals(1, count("rent_transaction"));
}
@Test
public void oldClosedOrderDoesNotPreventCleanupButBusinessRecordsRemain() throws Exception {
anchor(100);
task(true);
assertEquals(2, cleaner.clean("NILE"));
assertEquals(1, count("rent_order"));
assertEquals(1, count("rent_task"));
assertEquals(1, count("rent_transaction"));
assertEquals(1, count("rent_ledger"));
}
@Test
public void recentClosedOrderStillKeepsItsAuditEvidence() throws Exception {
anchor(100);
task(true);
store.execute("UPDATE rent_order SET updated_at=?", now());
assertEquals(0, cleaner.clean("NILE"));
assertEquals(1, count("rent_history_anchor"));
}
@Test
public void unknownTransactionWithoutHeightCannotBeTimedOutByCleaner() throws Exception {
anchor(100);
task(true);
store.execute("UPDATE rent_task SET status='UNKNOWN'");
store.execute("UPDATE rent_transaction SET status='UNKNOWN',block_height=NULL");
assertEquals(0, cleaner.clean("NILE"));
assertEquals("UNKNOWN", text(store.one("SELECT * FROM rent_task"), "status"));
}
@Test
public void heldFundsOutstandingRelationAndReclaimEachKeepEvidence() throws Exception {
anchor(100);
task(true);
store.execute("UPDATE rent_order SET fund_status='HELD'");
assertEquals(0, cleaner.clean("NILE"));
store.execute("UPDATE rent_order SET fund_status='CHARGED',relation_slot=1");
assertEquals(0, cleaner.clean("NILE"));
store.execute("UPDATE rent_order SET relation_slot=NULL,reclaim_status='RECOVERING'");
assertEquals(0, cleaner.clean("NILE"));
store.execute("UPDATE rent_order SET reclaim_status='DONE',service_expires_at=?", after(60));
assertEquals(0, cleaner.clean("NILE"));
assertEquals(1, count("rent_history_anchor"));
}
@Test
public void orphanOrMismatchedTaskStopsCleanup() throws Exception {
anchor(100);
task(false);
store.execute("DELETE FROM rent_order");
assertEquals(0, cleaner.clean("NILE"));
store.execute("INSERT INTO rent_order VALUES (1,'MAINNET','ENERGY','MANUAL_REVIEW',1,'HELD',1,'WAITING',?,?)", old, old);
assertEquals(0, cleaner.clean("NILE"));
assertEquals(1, count("rent_history_anchor"));
}
@Test
public void selectedWalletWithoutTaskStopsCleanup() throws Exception {
task(false);
store.execute("DELETE FROM rent_transaction");
store.execute("DELETE FROM rent_task");
assertEquals(0, cleaner.clean("NILE"));
assertEquals(2, count("rent_history_block"));
}
@Test
public void multipleAttemptsReuseOneProtectedPair() throws Exception {
anchor(100);
task(false);
for (int i = 2; i <= 120; i++) {
store.execute("INSERT INTO rent_task SELECT ?,order_id,network,resource_type,intent,'REJECTED',"
+ "NULL,'RELEASED',updated_at FROM rent_task WHERE id=1", i);
}
assertEquals(0, cleaner.clean("NILE"));
assertEquals(120, count("rent_task"));
}
@Test
public void protectedRelationsAreReadAcrossMultipleLookupBatches() throws Exception {
block("NILE", 5, old, old, 1);
block("NILE", 50, old, old, 1);
for (int i = 1; i <= 105; i++) {
byte[] address = new byte[21];
address[0] = 0x41;
address[20] = (byte) i;
String receiver = org.tron.trident.utils.Base58Check.bytesToBase58(address);
long baseline = i == 105 ? 10 : 50 + i;
store.execute("INSERT INTO rent_order VALUES (?,'NILE','ENERGY','MANUAL_REVIEW',1,'HELD',1,'WAITING',?,?)", i, old, old);
store.execute("INSERT INTO rent_task VALUES (?,?,'NILE','ENERGY',?,'VERIFIED',NULL,'COMMITTED',?)",
i, i, json.writeValueAsString(map("owner", OWNER, "receiver", receiver)), old);
store.execute("INSERT INTO rent_history_anchor VALUES ('NILE',?,?,'ENERGY',?,?,0,?)",
RentalHistoryService.addressHex(OWNER), RentalHistoryService.addressHex(receiver), baseline, hash(baseline), old);
}
assertEquals(1, cleaner.clean("NILE"));
assertNotNull(store.one("SELECT * FROM rent_history_block WHERE block_height=50"));
assertEquals(105, count("rent_history_anchor"));
}
@Test
public void missingOrMalformedBaselineStopsDeletion() throws Exception {
task(false);
assertEquals(0, cleaner.clean("NILE"));
anchor(100);
store.execute("UPDATE rent_task SET intent='not-json'");
assertEquals(0, cleaner.clean("NILE"));
assertNotNull(store.one("SELECT * FROM rent_history_block WHERE block_height=100"));
}
@Test
public void replayWindowRecentBackfillAndIncompleteBlocksStay() {
block("NILE", 20001, old, old, 1);
block("NILE", 101, old, now(), 1);
block("NILE", 102, now(), old, 1);
block("NILE", 103, old, old, 0);
assertEquals(1, cleaner.clean("NILE"));
assertEquals(5, count("rent_history_block"));
}
@Test
public void cleanupIsNetworkIsolated() {
block("MAINNET", 99, old, old, 1);
assertEquals(1, cleaner.clean("NILE"));
assertNotNull(store.one("SELECT * FROM rent_history_block WHERE network='MAINNET'"));
}
@Test
public void cleanupLeaseBlocksOtherCleanerAndExpiredLeaseCanBeTakenOver() {
store.execute("UPDATE rent_history_cursor SET cleanup_owner='other',cleanup_until=?", after(60));
assertEquals(0, cleaner.clean("NILE"));
assertEquals(0, archives.toFile().listFiles().length);
store.execute("UPDATE rent_history_cursor SET cleanup_until=?", after(-1));
assertEquals(1, cleaner.clean("NILE"));
}
@Test
public void scannerLeaseIsNotStolenByCleanup() {
store.execute("UPDATE rent_history_cursor SET lease_owner='scanner',lease_until=?", after(60));
assertEquals(1, cleaner.clean("NILE"));
assertEquals("scanner", text(store.one("SELECT * FROM rent_history_cursor"), "lease_owner"));
assertNull(store.one("SELECT * FROM rent_history_cursor").get("cleanup_owner"));
}
@Test
public void archiveFailureRollsBackAndReleasesLease() throws Exception {
RentalHistoryCleaner broken = cleaner(new RentalHistoryArchive(json) {
@Override public String save(Path path, Map<String, Object> batch) {
throw new IllegalStateException("controlled disk failure");
}
});
fails(() -> broken.clean("NILE"));
assertEquals(2, count("rent_history_block"));
assertNull(store.one("SELECT * FROM rent_history_cursor").get("cleanup_owner"));
assertEquals(1, cleaner.clean("NILE"));
}
@Test
public void realUnwritableArchiveLocationPreventsDeletion() throws Exception {
field(cleaner, "archiveDirectory", temporary.newFile("not-a-directory").getAbsolutePath());
fails(() -> cleaner.clean("NILE"));
assertEquals(2, count("rent_history_block"));
assertNull(store.one("SELECT * FROM rent_history_cursor").get("cleanup_owner"));
}
@Test
public void databaseFailureAfterArchiveRollsBackWholeBatch() throws Exception {
block("NILE", 99, old, old, 1);
event(100, 1001, 0);
anchor(100);
RentalStore failing = new RentalStore(new JdbcTemplate(manager.getDataSource())) {
@Override public int execute(String sql, Object... args) {
if (sql.startsWith("DELETE FROM rent_history_block")) {
throw new IllegalStateException("controlled SQL deletion failure");
}
return super.execute(sql, args);
}
};
RentalHistoryCleaner broken = new RentalHistoryCleaner(failing, json, new RentalHistoryArchive(json), manager);
field(broken, "archiveDirectory", archives.toString());
fails(() -> broken.clean("NILE"));
assertEquals(1, count("rent_history_event"));
assertEquals(1, count("rent_history_anchor"));
assertEquals(3, count("rent_history_block"));
assertEquals(1, archives.toFile().listFiles().length);
assertEquals(4, cleaner.clean("NILE"));
}
@Test
public void leaseExpiryDuringArchivePreventsDeletion() throws Exception {
RentalHistoryCleaner expired = cleaner(new RentalHistoryArchive(json) {
@Override public String save(Path path, Map<String, Object> batch) {
String result = super.save(path, batch);
store.execute("UPDATE rent_history_cursor SET cleanup_until=?", after(-1));
return result;
}
});
fails(() -> expired.clean("NILE"));
assertEquals(2, count("rent_history_block"));
assertTrue(archives.toFile().listFiles().length > 0);
}
@Test
public void boundedEventBatchNeverPartiallyDeletesItsBlock() throws Exception {
for (int i = 0; i < 3; i++) { event(100, 1001 + i, i); }
field(cleaner, "batchSize", 1);
field(cleaner, "maxBatches", 1);
assertEquals(1, cleaner.clean("NILE"));
assertEquals(2, count("rent_history_event"));
assertNotNull(store.one("SELECT * FROM rent_history_block WHERE block_height=100"));
field(cleaner, "maxBatches", 10);
assertEquals(3, cleaner.clean("NILE"));
}
@Test
public void pendingAndConflictingSamplesAreNotAgeDeleted() {
store.execute("UPDATE rent_history_block SET energy_limit=10,energy_weight=2,bandwidth_limit=30,"
+ "bandwidth_weight=4,parameters_at=? WHERE block_height=100", old);
store.execute("INSERT INTO rent_history_sample VALUES ('NILE',100,?,10,2,30,4,?)", hash(100), old);
store.execute("INSERT INTO rent_history_sample VALUES ('NILE',40000,?,10,2,30,4,?)", hash(40000), old);
block("NILE", 101, old, old, 1);
store.execute("INSERT INTO rent_history_sample VALUES ('NILE',101,?,10,2,30,4,?)", hash(999), old);
assertEquals(2, cleaner.clean("NILE"));
assertEquals(2, count("rent_history_sample"));
assertNotNull(store.one("SELECT * FROM rent_history_block WHERE block_height=101"));
}
@Test
public void disabledCleanerPerformsNoArchiveOrDeletion() throws Exception {
field(cleaner, "enabled", false);
assertEquals(0, cleaner.clean("NILE"));
assertEquals(2, count("rent_history_block"));
assertEquals(0, archives.toFile().listFiles().length);
}
@Test
public void proofAndSecondCleanerWaitForSameDatabaseGuard() throws Exception {
anchor(100);
block("NILE", 50, old, old, 1);
block("NILE", 101, old, old, 1);
event(101, 1001, 0);
task(false);
store.execute("UPDATE rent_history_block SET energy_limit=60000000,energy_weight=1000000,"
+ "bandwidth_limit=1500000,bandwidth_weight=1000000,parameters_at=? WHERE block_height=101", old);
CountDownLatch archiving = new CountDownLatch(1), release = new CountDownLatch(1);
RentalHistoryCleaner slow = cleaner(new RentalHistoryArchive(json) {
@Override public String save(Path path, Map<String, Object> batch) {
archiving.countDown();
try { assertTrue(release.await(5, TimeUnit.SECONDS)); }
catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new IllegalStateException(ex); }
return super.save(path, batch);
}
});
RentalChain chain = new RentalChain(json) {
@Override public JsonNode call(String network, String path, Map<String, Object> body) {
assertFalse("RPC must run outside history lock transaction", TransactionSynchronizationManager.isActualTransactionActive());
long height = path.endsWith("getnowblock") ? 30000 : number(body, "num");
return json.valueToTree(map("blockID", hash(height), "block_header",
map("raw_data", map("number", height))));
}
};
RentalHistoryService history = new RentalHistoryService(store, chain, manager);
ExecutorService pool = Executors.newFixedThreadPool(3);
try {
Future<Integer> cleaning = pool.submit(() -> slow.clean("NILE"));
assertTrue(archiving.await(5, TimeUnit.SECONDS));
Future<Map<String, Object>> proof = pool.submit(() -> history.proof("NILE", hash(1001), 101, OWNER, RECEIVER, "ENERGY"));
Future<Integer> competing = pool.submit(() -> cleaner.clean("NILE"));
try { proof.get(100, TimeUnit.MILLISECONDS); fail("proof should wait for cursor lock"); }
catch (TimeoutException expected) { }
release.countDown();
assertEquals(1, cleaning.get(5, TimeUnit.SECONDS).intValue());
assertNotNull(proof.get(5, TimeUnit.SECONDS));
assertEquals(0, competing.get(5, TimeUnit.SECONDS).intValue());
assertEquals(1, archives.toFile().listFiles().length);
} finally {
release.countDown();
pool.shutdownNow();
}
}
}
@@ -25,20 +25,25 @@ public class RentalHistoryTest {
private final ObjectMapper json = new ObjectMapper();
private final Map<Long, JsonNode> blocks = new HashMap<>();
private RentalStore store;
private javax.sql.DataSource storeDataSource;
private RentalHistoryService service;
private RentalChain chain;
private long currentHead;
private long relation;
private long lockedRelation;
private boolean malformedRelation;
private long energyLimit = 60000000;
private int changingHeads;
private boolean invalidParameters;
private boolean rpcFailure;
private JsonNode principalResponse;
private int calls;
private long confirmationLag;
@Before
public void setup() throws Exception {
JdbcDataSource source = new JdbcDataSource();
storeDataSource = source;
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);
@@ -73,9 +78,13 @@ public class RentalHistoryTest {
: map("TotalEnergyLimit", energyLimit, "TotalEnergyWeight", 1000000,
"TotalNetLimit", 1500000, "TotalNetWeight", 1000000));
}
if (path.equals("/wallet/getdelegatedresourcev2")) {
return json.valueToTree(Boolean.TRUE.equals(body.get("lock")) ? map()
: map("delegatedResource", Arrays.asList(map("frozen_balance_for_energy", relation))));
if (path.endsWith("getcandelegatedmaxsize")) {
return principalResponse == null ? json.createObjectNode() : principalResponse;
}
if (path.endsWith("/getdelegatedresourcev2")) {
return json.valueToTree(malformedRelation ? map("message", "controlled failure")
: map("delegatedResource", Arrays.asList(map("frozen_balance_for_energy",
Boolean.TRUE.equals(body.get("lock")) ? lockedRelation : relation))));
}
if (path.endsWith("getblockbynum")) {
return block(number(body, "num"));
@@ -102,6 +111,7 @@ public class RentalHistoryTest {
service = new RentalHistoryService(store, rpc, new DataSourceTransactionManager(source));
chain = rpc;
setField(service, "confirmations", 1L);
setField(service, "parameterGraceSeconds", 0L);
currentHead = 100;
}
@@ -142,6 +152,8 @@ public class RentalHistoryTest {
private void collect(long height) {
currentHead = height;
service.sample("NILE");
service.confirmSamples("NILE");
service.collect("NILE");
}
@@ -150,6 +162,7 @@ public class RentalHistoryTest {
}
private void anchor() {
service.sample("NILE");
service.anchor("NILE", OWNER, RECEIVER, "ENERGY");
}
@@ -163,26 +176,26 @@ public class RentalHistoryTest {
}
@Test
public void fullNodeSamplesWaitForConfirmationWithoutRelabelingParameters() {
public void confirmedBaselineDoesNotWaitForFullNodeSamples() {
confirmationLag = 2;
rejects(this::anchor);
assertEquals(0, number(store.one("SELECT COUNT(*) AS n FROM rent_history_anchor"), "n"));
anchor();
assertEquals(98, number(store.one("SELECT * FROM rent_history_anchor"), "block_height"));
assertNull(store.one("SELECT * FROM rent_history_block WHERE block_height=98").get("parameters_at"));
service.sample("NILE");
currentHead = 101;
energyLimit = 90000000;
rejects(this::anchor);
service.sample("NILE");
currentHead = 102;
anchor();
Map<String, Object> saved = store.one("SELECT * FROM rent_history_anchor");
assertEquals(100, number(saved, "block_height"));
service.confirmSamples("NILE");
assertEquals(60000000, number(store.one("SELECT * FROM rent_history_block WHERE block_height=100"), "energy_limit"));
}
@Test
public void collectionKeepsSamplingWhileWaitingAndArchivesOriginalHeight() {
confirmationLag = 2;
rejects(() -> collect(100));
collect(100);
energyLimit = 90000000;
rejects(() -> collect(101));
collect(101);
collect(102);
assertEquals(100, number(service.status().get(0), "scanned_height"));
assertEquals(60000000, number(store.one("SELECT * FROM rent_history_block WHERE block_height=100"), "energy_limit"));
@@ -194,11 +207,12 @@ public class RentalHistoryTest {
@Test
public void forkedUnconfirmedSampleCannotBecomeEvidence() {
confirmationLag = 2;
rejects(this::anchor);
service.sample("NILE");
((ObjectNode) block(100)).put("blockID", hash(999));
currentHead = 102;
rejects(this::anchor);
service.confirmSamples("NILE");
assertEquals(0, number(store.one("SELECT COUNT(*) AS n FROM rent_history_anchor"), "n"));
assertEquals(0, number(store.one("SELECT COUNT(*) AS n FROM rent_history_block"), "n"));
}
@Test
@@ -224,6 +238,7 @@ public class RentalHistoryTest {
transactions(101, event(1001, "DelegateResourceContract", "ENERGY", SUN));
collect(102);
assertNull(proof(1001, 101));
assertEquals("PARAMETERS_MISSING", service.missingProofCode("NILE", 101, OWNER, RECEIVER, "ENERGY"));
assertEquals(1, number(service.status().get(0), "parameter_gap_count"));
}
@@ -233,6 +248,7 @@ public class RentalHistoryTest {
transactions(101, event(1001, "DelegateResourceContract", "ENERGY", SUN));
collect(101);
assertNull(proof(1001, 101));
assertEquals("BASELINE_MISSING", service.missingProofCode("NILE", 101, OWNER, RECEIVER, "ENERGY"));
}
@Test
@@ -297,15 +313,16 @@ public class RentalHistoryTest {
@Test
public void movingConfirmedHeadDoesNotWriteAnAnchor() {
service.sample("NILE");
changingHeads = 6;
rejects(this::anchor);
rejects(() -> service.anchor("NILE", OWNER, RECEIVER, "ENERGY"));
assertEquals(0, number(store.one("SELECT COUNT(*) AS n FROM rent_history_anchor"), "n"));
}
@Test
public void invalidParametersCannotBeStored() {
invalidParameters = true;
rejects(this::anchor);
rejects(() -> service.sample("NILE"));
assertEquals(0, number(store.one("SELECT COUNT(*) AS n FROM rent_history_block"), "n"));
}
@@ -334,6 +351,7 @@ public class RentalHistoryTest {
@Test
public void bandwidthUsesOwnHistoricalParameters() {
service.sample("NILE");
service.anchor("NILE", OWNER, RECEIVER, "BANDWIDTH");
transactions(101, event(1001, "DelegateResourceContract", "BANDWIDTH", SUN));
collect(101);
@@ -396,7 +414,8 @@ public class RentalHistoryTest {
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);
currentHead = 101;
service.collect("NILE");
assertEquals(before, calls);
}
@@ -404,7 +423,8 @@ public class RentalHistoryTest {
public void rpcFailureReleasesLeaseAndDoesNotAdvanceCursor() {
collect(100);
rpcFailure = true;
rejects(() -> collect(101));
currentHead = 101;
rejects(() -> service.collect("NILE"));
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"));
@@ -428,7 +448,122 @@ public class RentalHistoryTest {
assertEquals(0, calls);
}
@Test
public void scannerContinuesWhenResourceSamplingFails() {
collect(100);
invalidParameters = true;
currentHead = 101;
rejects(() -> service.sample("NILE"));
service.collect("NILE");
assertEquals(101, number(service.status().get(0), "scanned_height"));
assertNull(store.one("SELECT * FROM rent_history_block WHERE block_height=101").get("parameters_at"));
}
@Test
public void pendingSamplesSurviveServiceRestart() {
confirmationLag = 2;
service.sample("NILE");
service = new RentalHistoryService(store, chain, transactionManager());
currentHead = 102;
energyLimit = 90000000;
service.confirmSamples("NILE");
assertEquals(60000000, number(store.one("SELECT * FROM rent_history_block WHERE block_height=100"), "energy_limit"));
assertEquals(0, number(store.one("SELECT COUNT(*) AS n FROM rent_history_sample"), "n"));
}
private DataSourceTransactionManager transactionManager() {
// 重新创建服务对象模拟进程内存全部丢失,数据库及已采参数保持不变。
return new DataSourceTransactionManager(storeDataSource);
}
@Test
public void baselineReusesContinuousReplayWithoutRelationshipRpc() {
anchor();
collect(100);
transactions(101, event(1001, "DelegateResourceContract", "ENERGY", 1000000));
collect(101);
transactions(102, event(1002, "UnDelegateResourceContract", "ENERGY", 1000000));
collect(102);
int before = calls;
service.anchor("NILE", OWNER, RECEIVER, "ENERGY");
assertEquals(before, calls);
assertNotNull(store.one("SELECT * FROM rent_history_anchor WHERE block_height=102"));
}
@Test
public void baselineReuseRejectsOutstandingDelegation() {
anchor();
collect(100);
transactions(101, event(1001, "DelegateResourceContract", "ENERGY", 1000000));
collect(101);
int before = calls;
rejects(() -> service.anchor("NILE", OWNER, RECEIVER, "ENERGY"));
assertEquals(before, calls);
}
@Test
public void parameterPromotionBacklogIsRetryableWithinGrace() throws Exception {
anchor();
collect(100);
transactions(101, event(1001, "DelegateResourceContract", "ENERGY", SUN));
currentHead = 101;
service.sample("NILE");
service.collect("NILE");
setField(service, "parameterGraceSeconds", 120L);
rejects(() -> proof(1001, 101));
service.confirmSamples("NILE");
assertNotNull(proof(1001, 101));
}
@Test
public void staleOrAbsentGlobalSamplerPreventsNewBaseline() {
rejects(() -> service.anchor("NILE", OWNER, RECEIVER, "ENERGY"));
service.sample("NILE");
store.execute("UPDATE rent_history_sample SET created_at=?", after(-60));
rejects(() -> service.anchor("NILE", OWNER, RECEIVER, "ENERGY"));
assertEquals(0, number(store.one("SELECT COUNT(*) AS n FROM rent_history_anchor"), "n"));
}
@Test
public void latePromotionDoesNotMakeOldSamplingAppearFresh() {
service.sample("NILE");
store.execute("UPDATE rent_history_sample SET created_at=?", after(-60));
service.confirmSamples("NILE");
rejects(() -> service.anchor("NILE", OWNER, RECEIVER, "ENERGY"));
}
@Test
public void walletRefreshReusesFreshParametersAndAcceptsProtobufZeroPrincipal() throws Exception {
embeddedMode();
Map<String, Object> snapshot = chain.snapshot("NILE", OWNER);
assertEquals(0, number(snapshot, "bandwidth_delegatable_sun"));
assertEquals(0, number(snapshot, "energy_delegatable_sun"));
assertEquals(1, number(store.one("SELECT COUNT(*) AS n FROM rent_history_sample"), "n"));
assertEquals(100, number(store.one("SELECT * FROM rent_history_sample"), "block_height"));
}
@Test
public void walletPrincipalRpcErrorsCannotBecomeZeroBalance() {
principalResponse = json.valueToTree(map("code", "FAILED", "message", "controlled failure"));
rejects(() -> chain.snapshot("NILE", OWNER));
}
@Test
public void lockedConfirmedPrincipalAlsoPreventsBaseline() {
lockedRelation = 1;
rejects(this::anchor);
assertEquals(0, number(store.one("SELECT COUNT(*) AS n FROM rent_history_anchor"), "n"));
}
@Test
public void malformedConfirmedRelationCannotBecomeEmptyBaseline() {
malformedRelation = true;
rejects(this::anchor);
assertEquals(0, number(store.one("SELECT COUNT(*) AS n FROM rent_history_anchor"), "n"));
}
private void embeddedMode() throws Exception {
service.sample("NILE");
org.springframework.beans.factory.support.DefaultListableBeanFactory factory =
new org.springframework.beans.factory.support.DefaultListableBeanFactory();
factory.registerSingleton("history", service);