diff --git a/docs/rental-address-onchain.md b/docs/rental-address-onchain.md index efaf601..fb7e260 100644 --- a/docs/rental-address-onchain.md +++ b/docs/rental-address-onchain.md @@ -111,6 +111,8 @@ rental: 链上采集失败日志stage含义:BEFORE_BLOCK/AFTER_BLOCK为区块RPC,ACCOUNT_RESOURCE为资源RPC,ENERGY_DELEGATABLE/BANDWIDTH_DELEGATABLE为对应可委托本金RPC,BLOCK_CONSISTENCY为前后区块一致性检查,GLOBAL_PARAMETERS为全网参数检查。BLOCK_CHANGED_OR_INVALID显示前后高度;STALE_OR_CONCURRENT显示钱包版本、新旧高度及快照屏障。RPC另记录路径和非成功HTTP状态码,不记录认证头或响应原文。请按walletId、网络、地址和相邻时间关联日志。 +区块夹读不一致时,在本轮立即整套重采集,最多3次(含首次);每次重新查询前后区块、资源和两类可委托本金,绝不复用失败尝试的数据。日志包含attempt/maxAttempts、每次耗时,重试成功或耗尽时输出总耗时。3次均失败则不更新旧快照及时间,等待后续扫描。RPC错误、本金响应无效、全网参数缺失不作为跨区块错误盲目重试;数据库版本及快照屏障校验保持不变。持续跨区块应检查RPC延迟及节点一致性,重试不能保证慢RPC一定取得快照。 + 地址上链不依赖能量/带宽出租开关、可委托质押本金、历史资源证明或资源快照有效期。供应钱包必须在订单对应网络、状态为ACTIVE且已完成控制权验证;节点必须ACTIVE、ONLINE、心跳未过期,并由Agent在连接恢复同步时上报转账授权。仅打开能量/带宽出租并不会授予转账权限。 Agent配置 `RENT_TRANSFER_ENABLED=true` 后需重启或重连;数据库中的 `rent_node.transfer_enabled` 应由Agent同步上报,不应手工改成1绕过本地授权。Java Agent还需要打开总广播授权。云端实时查询余额至少覆盖固定1TRX与订单快照中的fee-limit-sun,Agent执行前还会检查实际创建费、带宽费用及本地留存。 diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalChain.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalChain.java index 029e2b7..74edc55 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalChain.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalChain.java @@ -22,6 +22,17 @@ import static com.ruoyi.system.rental.RentalValues.*; @Slf4j @Service public class RentalChain { + /** 总尝试次数(含首次),仅区块夹读冲突触发整套重采集。 */ + private static final int SNAPSHOT_MAX_ATTEMPTS = 3; + + /** 内部类型区分可重试的区块变化与RPC、参数及本金错误,禁止按异常文案判断。 */ + private static final class SnapshotBlockChangedException extends IllegalArgumentException { + private static final long serialVersionUID = 1L; + + private SnapshotBlockChangedException() { + super("快照区块不一致,整套重采集仍未通过"); + } + } @Value("${rental.rpc.nile:https://nile.trongrid.io}") private String nile; @@ -122,6 +133,32 @@ public class RentalChain { } public Map snapshot(String network, String address) { + long started = System.nanoTime(); + for (int attempt = 1; attempt <= SNAPSHOT_MAX_ATTEMPTS; attempt++) { + try { + // 每次调用重新查询前区块、资源、两类本金、后区块,不复用失败尝试的数据。 + Map result = snapshotOnce(network, address, attempt); + if (attempt > 1) { + log.info("租赁快照重采集成功 network={} address={} attempt={} maxAttempts={}" + + " blockHeight={} totalElapsedMs={}", + network, address, attempt, SNAPSHOT_MAX_ATTEMPTS, result.get("snapshot_block_height"), + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)); + } + return result; + } catch (SnapshotBlockChangedException ex) { + if (attempt == SNAPSHOT_MAX_ATTEMPTS) { + log.warn("租赁快照重采集耗尽 network={} address={} attempts={} totalElapsedMs={};保留旧快照,等待下一轮扫描", + network, address, attempt, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)); + throw ex; + } + log.info("租赁快照跨区块重试 network={} address={} nextAttempt={} maxAttempts={}", + network, address, attempt + 1, SNAPSHOT_MAX_ATTEMPTS); + } + } + throw new IllegalStateException("快照重采集未产生结果"); + } + + private Map snapshotOnce(String network, String address, int attempt) { long started = System.nanoTime(); String stage = "BEFORE_BLOCK"; try { @@ -148,15 +185,14 @@ public class RentalChain { if (before < 0 || before != after || !beforeBlock.path("blockID").asText().matches("[0-9a-fA-F]{64}") || !beforeBlock.path("blockID").asText().equalsIgnoreCase(afterBlock.path("blockID").asText())) { - log.warn("租赁快照区块不一致 network={} address={} beforeHeight={} afterHeight={}" + log.warn("租赁快照区块不一致 network={} address={} attempt={} maxAttempts={} beforeHeight={} afterHeight={}" + " reason=BLOCK_CHANGED_OR_INVALID;本次不更新,禁止混用不同区块资源", - network, address, before, after); + network, address, attempt, SNAPSHOT_MAX_ATTEMPTS, before, after); + throw new SnapshotBlockChangedException(); } require( - before >= 0 && before == after && energy >= 0 && bandwidth >= 0 - && beforeBlock.path("blockID").asText().matches("[0-9a-fA-F]{64}") - && beforeBlock.path("blockID").asText().equalsIgnoreCase(afterBlock.path("blockID").asText()), - "快照跨区块或本金查询不完整,请重试"); + energy >= 0 && bandwidth >= 0, + "快照本金查询不完整"); Map result = map( "snapshot_block_height", @@ -211,8 +247,8 @@ public class RentalChain { } return result; } catch (RuntimeException ex) { - log.warn("租赁链上快照采集失败 network={} address={} stage={} elapsedMs={} diagnostic={}", - network, address, stage, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started), + log.warn("租赁链上快照采集失败 network={} address={} attempt={} stage={} elapsedMs={} diagnostic={}", + network, address, attempt, stage, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started), RentalDiagnostics.describe(ex)); throw ex; } diff --git a/ruoyi-system/src/test/java/com/ruoyi/system/rental/RentalBusinessTest.java b/ruoyi-system/src/test/java/com/ruoyi/system/rental/RentalBusinessTest.java index 3257f7a..c104208 100644 --- a/ruoyi-system/src/test/java/com/ruoyi/system/rental/RentalBusinessTest.java +++ b/ruoyi-system/src/test/java/com/ruoyi/system/rental/RentalBusinessTest.java @@ -755,6 +755,26 @@ public class RentalBusinessTest { expectFailure(() -> tx.execute(status -> orders.create(app, 10, request))); } + @Test + public void failedSnapshotCollectionPreservesStoredSnapshotAndVersion() { + Map before = store.get("wallet", wallet, false); + RentalChain unavailable = new RentalChain(json) { + @Override + public Map snapshot(String network, String address) { + throw new IllegalArgumentException("controlled snapshot failure after retries"); + } + }; + RentalTasks failingTasks = new RentalTasks(store, unavailable, identity, orders, funds, + tx.getTransactionManager()); + expectFailure(() -> failingTasks.refresh(wallet)); + Map after = store.get("wallet", wallet, false); + assertEquals(before.get("snapshot_at"), after.get("snapshot_at")); + assertEquals(before.get("snapshot_expires_at"), after.get("snapshot_expires_at")); + assertEquals(before.get("snapshot_block_height"), after.get("snapshot_block_height")); + assertEquals(before.get("energy_delegatable_sun"), after.get("energy_delegatable_sun")); + assertEquals(before.get("version"), after.get("version")); + } + @Test public void onchainDispatchDoesNotRequireStakeSnapshotAndStillVerifiesTransfer() { store.update("node", node, map("transfer_enabled", 1)); diff --git a/ruoyi-system/src/test/java/com/ruoyi/system/rental/RentalSnapshotTest.java b/ruoyi-system/src/test/java/com/ruoyi/system/rental/RentalSnapshotTest.java new file mode 100644 index 0000000..39fa667 --- /dev/null +++ b/ruoyi-system/src/test/java/com/ruoyi/system/rental/RentalSnapshotTest.java @@ -0,0 +1,131 @@ +package com.ruoyi.system.rental; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.util.Map; + +import static com.ruoyi.system.rental.RentalValues.*; +import static org.junit.Assert.*; + +/** 可控RPC验证整套重采集与有界重试;不访问外网、不广播真实交易。 */ +public class RentalSnapshotTest { + @Test + public void changedBlockRetriesWholeSampleAndReturnsOnlyLatestValues() { + FakeChain chain = new FakeChain(1); + Map result = chain.snapshot("NILE", "test-address"); + assertEquals(2, chain.resourceCalls); + assertEquals(4, chain.principalCalls); + assertEquals(4, chain.blockCalls); + assertEquals(200, number(result, "energy_available")); + assertEquals(2000, number(result, "energy_delegatable_sun")); + assertEquals(2000, number(result, "bandwidth_delegatable_sun")); + assertEquals(104, number(result, "snapshot_block_height")); + } + + @Test + public void thirdAttemptCanSucceedAndSameHeightHashChangesAlsoRetry() { + FakeChain chain = new FakeChain(2); + chain.sameHeightConflict = true; + Map result = chain.snapshot("NILE", "test-address"); + assertEquals(3, chain.resourceCalls); + assertEquals(6, chain.principalCalls); + assertEquals(6, chain.blockCalls); + assertEquals(300, number(result, "energy_available")); + assertEquals(106, number(result, "snapshot_block_height")); + } + + @Test + public void repeatedBlockChangesStopAfterThreeCompleteAttempts() { + FakeChain chain = new FakeChain(3); + try { + chain.snapshot("NILE", "test-address"); + fail("跨区块不能返回不一致快照"); + } catch (IllegalArgumentException expected) { + assertEquals(3, chain.resourceCalls); + assertEquals(6, chain.principalCalls); + assertEquals(6, chain.blockCalls); + } + } + + @Test + public void stableSnapshotDoesNotMakeExtraRequests() { + FakeChain chain = new FakeChain(0); + assertEquals(102, number(chain.snapshot("NILE", "test-address"), "snapshot_block_height")); + assertEquals(1, chain.resourceCalls); + assertEquals(2, chain.principalCalls); + assertEquals(2, chain.blockCalls); + } + + @Test + public void resourceRpcFailureIsNotBlindlyRetried() { + FakeChain chain = new FakeChain(0); + chain.resourceRpcFailed = true; + try { + chain.snapshot("NILE", "test-address"); + fail("RPC失败不能生成快照"); + } catch (IllegalStateException expected) { + assertEquals(1, chain.resourceCalls); + assertEquals(1, chain.blockCalls); + assertEquals(0, chain.principalCalls); + } + } + + @Test + public void incompleteParametersAreNotTreatedAsBlockChanges() { + FakeChain chain = new FakeChain(0); + chain.invalidParameters = true; + try { + chain.snapshot("NILE", "test-address"); + fail("全网参数缺失应拒绝"); + } catch (IllegalArgumentException expected) { + assertEquals(1, chain.resourceCalls); + assertEquals(2, chain.blockCalls); + } + } + + private static final class FakeChain extends RentalChain { + private final ObjectMapper json = new ObjectMapper(); + private final int conflictingAttempts; + private int blockCalls; + private int resourceCalls; + private int principalCalls; + private boolean invalidParameters; + private boolean resourceRpcFailed; + private boolean sameHeightConflict; + + private FakeChain(int conflictingAttempts) { + super(new ObjectMapper()); + this.conflictingAttempts = conflictingAttempts; + } + + @Override + public JsonNode call(String network, String path, Map body) { + assertEquals("NILE", network); + if ("/wallet/getnowblock".equals(path)) { + int attempt = blockCalls / 2 + 1; + boolean after = ++blockCalls % 2 == 0; + boolean conflict = after && attempt <= conflictingAttempts; + long height = 100 + attempt * 2 + (conflict && !sameHeightConflict ? 1 : 0); + long blockIdentity = height + (conflict && sameHeightConflict ? 1000 : 0); + return json.valueToTree(map("blockID", String.format("%064x", blockIdentity), + "block_header", map("raw_data", map("number", height)))); + } + if ("/wallet/getaccountresource".equals(path)) { + resourceCalls++; + if (resourceRpcFailed) { + throw new IllegalStateException("controlled RPC failure"); + } + return json.valueToTree(map("EnergyLimit", resourceCalls * 100, + "TotalEnergyLimit", invalidParameters ? 0 : 60000000, + "TotalEnergyWeight", 1000000, "TotalNetLimit", 1000000, "TotalNetWeight", 1000)); + } + if ("/wallet/getcandelegatedmaxsize".equals(path)) { + principalCalls++; + return json.valueToTree(map("max_size", resourceCalls * 1000)); + } + throw new AssertionError("意外RPC路径: " + path); + } + } +}