修正RPC响应失败
This commit is contained in:
1 parent
1e79e836e8
commit
911a3634ee
5 files changed
+124
-21
No files matched your search
@@ -1,5 +1,6 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
@@ -14,7 +15,10 @@ import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/** 独立采集线程,不与业务五秒/十五秒调度争抢同一个调度线程;无链上写操作。 */
|
||||
/**
|
||||
* 独立采集线程,不与业务五秒/十五秒调度争抢同一个调度线程;无链上写操作。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@ConditionalOnProperty(name = {"rental.enabled", "rental.history.embedded-enabled"}, havingValue = "true")
|
||||
public class RentalHistoryCollector {
|
||||
@@ -50,6 +54,8 @@ public class RentalHistoryCollector {
|
||||
executor.scheduleWithFixedDelay(() -> {
|
||||
try {
|
||||
service.collect(network);
|
||||
} catch (RentalHistoryService.PendingConfirmationException ex) {
|
||||
LOG.debug("租赁历史采样等待区块确认,network={}", network);
|
||||
} catch (Exception ex) {
|
||||
// 不记录异常原文,避免RPC配置、认证头或供应商数据进入日志。
|
||||
LOG.warn("租赁历史采集未完成,network={},请查看受保护的历史状态接口", network);
|
||||
|
||||
@@ -26,7 +26,7 @@ import java.util.Map;
|
||||
/**
|
||||
* 云端内置的只读历史采集与证明服务。
|
||||
*
|
||||
* <p>普通节点只提供最新确认状态,因此用同一确认头前后夹读为参数、关系基线绑定高度。
|
||||
* <p>FullNode状态以最新头前后夹读绑定高度,等待Solidity确认并核对哈希后才归档。
|
||||
* 已错过高度只能补区块交易,不能补造历史参数。所有HTTP在事务外执行,数据库事务只保存事实。
|
||||
* 本服务信任运营配置的同一一致性RPC节点,不接受供应商提交的历史参数,不持有私钥,不广播。
|
||||
*/
|
||||
@@ -50,6 +50,18 @@ public class RentalHistoryService {
|
||||
@Value("${rental.confirmations:19}")
|
||||
private long confirmations = 19;
|
||||
|
||||
/** 未确认采样只驻留内存;重启丢弃,禁止回填或使用其他高度参数替代。 */
|
||||
private final Map<String, Snapshot> pendingSnapshots = new java.util.concurrent.ConcurrentHashMap<>();
|
||||
|
||||
/** 确认预热属于正常等待,不作为RPC故障反复输出错误堆栈。 */
|
||||
public static final class PendingConfirmationException extends IllegalStateException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private PendingConfirmationException() {
|
||||
super("资源采样区块尚未确认,请稍后重试");
|
||||
}
|
||||
}
|
||||
|
||||
public RentalHistoryService(RentalStore store, RentalChain chain,
|
||||
PlatformTransactionManager manager) {
|
||||
this.store = store;
|
||||
@@ -94,21 +106,26 @@ public class RentalHistoryService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 三次有界尝试,只有确认头高度和哈希均未变化才接纳快照。
|
||||
* 这里读取walletsolidity状态,不允许用wallet最新未确认状态冒充历史快照。
|
||||
* 最新头夹读绑定采样高度;采样必须等该高度确认且哈希一致后才能用于历史证明。
|
||||
* 必须配置同一一致性FullNode(或保证会话一致性的网关),不能混用不同高度后端。
|
||||
*/
|
||||
private Snapshot capture(String network, String owner, String receiver, String type) {
|
||||
private synchronized Snapshot capture(String network, String owner, String receiver, String type) {
|
||||
String key = network + ":" + owner + ":" + receiver + ":" + type;
|
||||
// 有界缓存防止异常地址请求造成无限内存增长;过期快照不再用于新基线。
|
||||
long oldest = System.currentTimeMillis() - 10 * 60 * 1000L;
|
||||
pendingSnapshots.entrySet().removeIf(entry -> entry.getValue().sampledAt < oldest);
|
||||
require(pendingSnapshots.size() < 10000, "待确认资源采样过多,请稍后重试");
|
||||
for (int attempt = 0; attempt < 3; attempt++) {
|
||||
JsonNode before = head(network);
|
||||
JsonNode before = chain.call(network, "/wallet/getnowblock", map());
|
||||
long blockHeight = height(before);
|
||||
String blockId = hash(before);
|
||||
long[] totals = parameters(chain.call(network, "/walletsolidity/getaccountresource",
|
||||
long[] totals = parameters(chain.call(network, "/wallet/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",
|
||||
JsonNode response = chain.call(network, "/wallet/getdelegatedresourcev2",
|
||||
map("fromAddress", owner, "toAddress", receiver,
|
||||
"lock", locked, "visible", true));
|
||||
require(!response.has("Error") && !response.has("error")
|
||||
@@ -125,12 +142,40 @@ public class RentalHistoryService {
|
||||
}
|
||||
}
|
||||
}
|
||||
JsonNode after = head(network);
|
||||
JsonNode after = chain.call(network, "/wallet/getnowblock", map());
|
||||
if (blockHeight == height(after) && blockId.equals(hash(after))) {
|
||||
return new Snapshot(before, totals, balance);
|
||||
// 每轮继续采样,等待确认期间不能停止采样,否则会漏掉后续交易高度的参数。
|
||||
String sampleKey = key + ":" + blockHeight;
|
||||
Snapshot sampled = new Snapshot(before.deepCopy(), totals, balance);
|
||||
Snapshot original = pendingSnapshots.putIfAbsent(sampleKey, sampled);
|
||||
if (original != null) {
|
||||
if (!hash(original.block).equals(blockId)) {
|
||||
pendingSnapshots.remove(sampleKey);
|
||||
throw new IllegalStateException("未确认采样区块发生分叉,丢弃并重新采样");
|
||||
}
|
||||
require(hash(original.block).equals(blockId)
|
||||
&& Arrays.equals(original.totals, totals) && original.balance == balance,
|
||||
"同一采样高度状态不一致,请检查RPC后端一致性");
|
||||
}
|
||||
long confirmedHeight = height(head(network));
|
||||
Map.Entry<String, Snapshot> ready = pendingSnapshots.entrySet().stream()
|
||||
.filter(entry -> entry.getKey().startsWith(key + ":")
|
||||
&& height(entry.getValue().block) <= confirmedHeight)
|
||||
.min(java.util.Comparator.comparingLong(entry -> height(entry.getValue().block)))
|
||||
.orElse(null);
|
||||
if (ready == null) {
|
||||
throw new PendingConfirmationException();
|
||||
}
|
||||
Snapshot pending = ready.getValue();
|
||||
JsonNode canonical = chain.call(network, "/walletsolidity/getblockbynum",
|
||||
map("num", height(pending.block), "visible", false));
|
||||
pendingSnapshots.remove(ready.getKey());
|
||||
require(height(canonical) == height(pending.block)
|
||||
&& hash(canonical).equals(hash(pending.block)), "资源采样区块发生分叉,丢弃并重新采样");
|
||||
return pending;
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("确认头在采样期间变化,请重试,未记录历史证据");
|
||||
throw new IllegalStateException("最新头在采样期间变化,请重试,未记录历史证据");
|
||||
}
|
||||
|
||||
/** 派单前建立真实基线;非零关系拒绝派单,不用任务声明的0替代链上读取。 */
|
||||
@@ -241,6 +286,9 @@ public class RentalHistoryService {
|
||||
return null;
|
||||
});
|
||||
}
|
||||
} catch (PendingConfirmationException ex) {
|
||||
// 预热不会推进游标或生成参数;finally仍然释放本网络租约。
|
||||
throw ex;
|
||||
} catch (RuntimeException ex) {
|
||||
store.execute("UPDATE rent_history_cursor SET last_error=?,updated_at=?"
|
||||
+ " WHERE network=? AND lease_owner=?", "采集未完成,请检查RPC一致性、限流、表结构及确认链连续性",
|
||||
@@ -430,6 +478,7 @@ public class RentalHistoryService {
|
||||
private final JsonNode block;
|
||||
private final long[] totals;
|
||||
private final long balance;
|
||||
private final long sampledAt = System.currentTimeMillis();
|
||||
|
||||
private Snapshot(JsonNode block, long[] totals, long balance) {
|
||||
this.block = block;
|
||||
|
||||
@@ -81,7 +81,8 @@ public final class RentalHttp {
|
||||
/** 完整区块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响应失败");
|
||||
require(response.isSuccessful() && response.body() != null,
|
||||
"RPC响应失败,HTTP状态码=" + response.code());
|
||||
java.io.InputStream stream = response.body().byteStream();
|
||||
java.io.ByteArrayOutputStream output = new java.io.ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[4096];
|
||||
|
||||
@@ -34,6 +34,7 @@ public class RentalHistoryTest {
|
||||
private boolean invalidParameters;
|
||||
private boolean rpcFailure;
|
||||
private int calls;
|
||||
private long confirmationLag;
|
||||
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
@@ -61,14 +62,18 @@ public class RentalHistoryTest {
|
||||
}
|
||||
if (path.endsWith("getnowblock")) {
|
||||
long height = changingHeads > 0 ? currentHead + changingHeads-- : currentHead;
|
||||
if (path.startsWith("/walletsolidity/")) {
|
||||
height -= confirmationLag;
|
||||
}
|
||||
return block(height);
|
||||
}
|
||||
if (path.endsWith("getaccountresource")) {
|
||||
assertEquals("/wallet/getaccountresource", path);
|
||||
return json.valueToTree(invalidParameters ? map("TotalEnergyLimit", 0)
|
||||
: map("TotalEnergyLimit", energyLimit, "TotalEnergyWeight", 1000000,
|
||||
"TotalNetLimit", 1500000, "TotalNetWeight", 1000000));
|
||||
}
|
||||
if (path.equals("/walletsolidity/getdelegatedresourcev2")) {
|
||||
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))));
|
||||
}
|
||||
@@ -157,6 +162,45 @@ public class RentalHistoryTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fullNodeSamplesWaitForConfirmationWithoutRelabelingParameters() {
|
||||
confirmationLag = 2;
|
||||
rejects(this::anchor);
|
||||
assertEquals(0, number(store.one("SELECT COUNT(*) AS n FROM rent_history_anchor"), "n"));
|
||||
currentHead = 101;
|
||||
energyLimit = 90000000;
|
||||
rejects(this::anchor);
|
||||
currentHead = 102;
|
||||
anchor();
|
||||
Map<String, Object> saved = store.one("SELECT * FROM rent_history_anchor");
|
||||
assertEquals(100, number(saved, "block_height"));
|
||||
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));
|
||||
energyLimit = 90000000;
|
||||
rejects(() -> 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"));
|
||||
collect(103);
|
||||
assertEquals(101, number(service.status().get(0), "scanned_height"));
|
||||
assertEquals(90000000, number(store.one("SELECT * FROM rent_history_block WHERE block_height=101"), "energy_limit"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void forkedUnconfirmedSampleCannotBecomeEvidence() {
|
||||
confirmationLag = 2;
|
||||
rejects(this::anchor);
|
||||
((ObjectNode) block(100)).put("blockID", hash(999));
|
||||
currentHead = 102;
|
||||
rejects(this::anchor);
|
||||
assertEquals(0, number(store.one("SELECT COUNT(*) AS n FROM rent_history_anchor"), "n"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void coherentArchiveProducesProofAndPreservesOldParameters() {
|
||||
anchor();
|
||||
@@ -399,6 +443,7 @@ public class RentalHistoryTest {
|
||||
chain.prepareHistory("NILE", OWNER, RECEIVER, "ENERGY");
|
||||
transactions(101, event(1001, "DelegateResourceContract", "ENERGY", SUN));
|
||||
collect(101);
|
||||
relation = SUN;
|
||||
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"));
|
||||
@@ -413,6 +458,7 @@ public class RentalHistoryTest {
|
||||
collect(100);
|
||||
transactions(101, event(1001, "DelegateResourceContract", "ENERGY", SUN));
|
||||
collect(102);
|
||||
relation = SUN;
|
||||
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"));
|
||||
|
||||
Reference in new issue
Block a user