接入租赁平台

This commit is contained in:
lu7213 committed 2026-11-05 09:20:29 -05:00
1 parent c035263bc6
commit 1c2d15b2a9
51 files changed
+3631 -15

No files matched your search

@@ -0,0 +1,198 @@
package com.ruoyi.system.chain;
import com.google.protobuf.ByteString;
import com.ruoyi.system.domain.UsdtConfig;
import com.ruoyi.system.domain.WalletAddressPlus;
import com.ruoyi.system.domain.vo.WalletOperationRequest;
import com.ruoyi.system.domain.vo.WalletResourceEstimateVo;
import com.ruoyi.system.mapper.UsdtConfigMapper;
import com.ruoyi.system.service.ITronService;
import com.ruoyi.system.service.TronServiceProvider;
import com.ruoyi.system.service.WalletOperationEstimateService;
import com.ruoyi.system.service.WalletSigningService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.tron.trident.core.ApiWrapper;
import org.tron.trident.proto.Chain;
import org.tron.trident.proto.Response;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
import static org.junit.Assert.*;
/** 可控节点替身验证广播先持久化、同交易重播和重启恢复;没有真实 RPC 或真实私钥。 */
public class ChainCommandExecutorTest {
private ChainExecutionStore store;
private ChainCommandExecutor executor;
private TestApi api;
private String executionId;
private int signedCount;
private int broadcasts;
private boolean acceptBroadcast;
private byte[] firstTransaction;
@Before
public void setup() throws Exception {
store = new ChainExecutionStore(new DriverManagerDataSource("jdbc:h2:mem:engine" + System.nanoTime()
+ ";MODE=MySQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1", "sa", ""));
String schema = new String(Files.readAllBytes(Paths.get("../sql/chain_executor.sql")), StandardCharsets.UTF_8);
store.jdbc().execute(schema.replaceAll("ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='[^']*'", ""));
api = new TestApi();
ITronService tron = (ITronService) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] {ITronService.class},
(proxy, method, args) -> {
if ("type".equals(method.getName())) return "nile";
if ("buildApiWrapper".equals(method.getName())) return api;
if ("getTRxBalance".equals(method.getName())) return new BigDecimal("100");
throw new UnsupportedOperationException(method.getName());
});
UsdtConfig config = new UsdtConfig();
config.setVersion(1L);
config.setTronNetType(0);
config.setTrxNum(BigDecimal.ONE);
config.setTokenAddress("test-main-wallet");
UsdtConfigMapper configs = (UsdtConfigMapper) Proxy.newProxyInstance(getClass().getClassLoader(),
new Class<?>[] {UsdtConfigMapper.class}, (proxy, method, args) -> config);
TronServiceProvider networks = new TronServiceProvider(configs, null) {
@Override public ITronService getServiceForNetwork(String network) { return tron; }
};
WalletSigningService signing = new WalletSigningService() {
@Override public <T> T execute(WalletAddressPlus wallet, String password, SignedOperation<T> operation) {
try { return operation.execute(tron, api, wallet); }
catch (Exception ex) { throw new IllegalStateException(ex); }
}
};
WalletOperationEstimateService estimates = new WalletOperationEstimateService(networks) {
@Override public WalletResourceEstimateVo estimate(String type, WalletAddressPlus wallet, WalletOperationRequest request) {
WalletResourceEstimateVo estimate = new WalletResourceEstimateVo();
estimate.setEstimatedBurnTrx(BigDecimal.ZERO);
return estimate;
}
};
executor = new ChainCommandExecutor(store, signing, estimates, configs, networks);
executionId = (String) store.create(command(), true).get("execution_id");
}
@After public void cleanup() { if (api != null) api.close(); }
@Test
public void responseLossRetriesIdenticalTransactionAndRecoveryDoesNotResign() {
executor.execute(executionId, "test-only-password");
assertEquals(1, signedCount);
assertEquals(4, broadcasts);
assertEquals("SIGNED", store.get(executionId).get("status"));
// 模拟重启后节点恢复:从持久化记录重播,不再解锁钱包,不再次构造/签名。
acceptBroadcast = true;
executor.recover(store.get(executionId));
assertEquals(1, signedCount);
assertEquals(5, broadcasts);
assertEquals("BROADCASTED", store.get(executionId).get("status"));
executor.execute(executionId, "test-only-password");
assertEquals(1, signedCount);
assertEquals(5, broadcasts);
}
@Test
public void expiredQueueEntryDoesNotSignOrBroadcast() {
ChainCommand expired = command();
expired.businessKey = "WALLET:expired";
expired.validUntil = 1L;
String id = (String) store.create(expired, true).get("execution_id");
executor.execute(id, "test-only-password");
assertEquals(0, signedCount);
assertEquals(0, broadcasts);
assertEquals("FAILED", store.get(id).get("status"));
}
@Test
public void rentalWaitingLeavesRemoteQueuedWithoutSigning() throws Exception {
ChainCommand waiting = command();
waiting.businessKey = "WALLET:resource-wait";
waiting.rentalRequired = true;
executionId = (String) store.create(waiting, true).get("execution_id");
java.lang.reflect.Field gate = ChainCommandExecutor.class.getDeclaredField("resourceGate");
gate.setAccessible(true);
gate.set(executor, new com.ruoyi.system.chain.resource.ResourceExecutionGate(null, null) {
@Override public boolean ready(ChainCommand command) { return false; }
});
executor.execute(executionId, "test-only-password");
executor.execute(executionId, "test-only-password");
assertEquals("QUEUED", store.get(executionId).get("status"));
assertEquals(0, signedCount);
assertEquals(0, broadcasts);
}
@Test
public void passwordRequestDoesNotRemainQueuedWhenResourcesFallBack() throws Exception {
ChainCommand waiting = command();
waiting.businessKey = "WALLET:password-resource-wait";
waiting.rentalRequired = true;
executionId = (String) store.create(waiting, false).get("execution_id");
// 未注入gate也必须安全失败;密码没有后台副本,不能留成永久等待任务。
executor.execute(executionId, "test-only-password");
assertEquals("FAILED", store.get(executionId).get("status"));
assertEquals(0, signedCount);
assertEquals(0, broadcasts);
}
private ChainCommand command() {
ChainCommand command = new ChainCommand();
command.businessKey = "WALLET:test";
command.operatorId = 1L;
command.address = "test-main-wallet";
command.tokenIndex = "0";
command.network = 0;
command.envelopeVersion = 1L;
command.validUntil = System.currentTimeMillis() + 60_000L;
command.type = "trx";
command.operation = new WalletOperationRequest();
command.operation.setToAddress("test-target");
command.operation.setAmount(BigDecimal.ONE);
command.operation.setBroadcast(true);
return command;
}
private final class TestApi extends ApiWrapper {
TestApi() { super("127.0.0.1:1", "127.0.0.1:1", "0000000000000000000000000000000000000000000000000000000000000001"); }
@Override public Response.TransactionExtention transfer(String from, String to, long amount) {
Chain.Transaction transaction = Chain.Transaction.newBuilder().setRawData(
Chain.Transaction.raw.newBuilder().setExpiration(System.currentTimeMillis() + 60_000)
.addContract(Chain.Transaction.Contract.newBuilder()
.setType(Chain.Transaction.Contract.ContractType.TransferContract))).build();
return Response.TransactionExtention.newBuilder().setTransaction(transaction).build();
}
@Override public Chain.Transaction signTransaction(Chain.Transaction transaction) {
signedCount++;
return transaction.toBuilder().addSignature(ByteString.copyFromUtf8("test-signature")).build();
}
@Override public String broadcastTransaction(Chain.Transaction transaction) {
Map<String, Object> stored = store.get(executionId);
assertEquals("SIGNED", stored.get("status"));
assertArrayEquals(transaction.toByteArray(), (byte[]) stored.get("signed_transaction"));
if (firstTransaction == null) firstTransaction = transaction.toByteArray();
else assertArrayEquals(firstTransaction, transaction.toByteArray());
broadcasts++;
if (!acceptBroadcast) throw new IllegalStateException("simulated response loss");
return (String) stored.get("transaction_id");
}
@Override public Chain.Transaction getTransactionById(String hash, org.tron.trident.core.NodeType... nodes) {
throw new IllegalStateException("simulated query unavailable");
}
@Override public Response.ChainParameters getChainParameters() {
return Response.ChainParameters.newBuilder()
.addChainParameter(Response.ChainParameters.ChainParameter.newBuilder().setKey("getEnergyFee").setValue(100))
.addChainParameter(Response.ChainParameters.ChainParameter.newBuilder().setKey("getTransactionFee").setValue(1000)).build();
}
}
}
@@ -0,0 +1,130 @@
package com.ruoyi.system.chain;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.domain.UsdtConfig;
import com.ruoyi.system.domain.WalletAddressPlus;
import com.ruoyi.system.domain.vo.WalletOperationRequest;
import com.ruoyi.system.mapper.UsdtConfigMapper;
import com.ruoyi.system.service.WalletSigningService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.junit.Assert.*;
/** 双通道路由边界:关闭时完全兼容;离线不建任务;提交后禁止转为本地新交易。 */
public class ChainExecutionRouterTest {
private ChainExecutionStore store;
private ChainExecutionRouter router;
private boolean enabled = true;
private boolean ready = true;
private int localExecutions;
private int notifications;
@Before
public void setup() throws Exception {
store = new ChainExecutionStore(new DriverManagerDataSource("jdbc:h2:mem:router" + System.nanoTime()
+ ";MODE=MySQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1", "sa", ""));
String sql = new String(Files.readAllBytes(Paths.get("../sql/chain_executor.sql")), StandardCharsets.UTF_8);
store.jdbc().execute(sql.replaceAll("ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='[^']*'", ""));
SysUser user = new SysUser();
user.setUserId(1L);
LoginUser login = new LoginUser();
login.setUser(user);
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(login, null));
UsdtConfig config = new UsdtConfig();
config.setVersion(1L);
config.setTronNetType(0);
UsdtConfigMapper configs = (UsdtConfigMapper) Proxy.newProxyInstance(getClass().getClassLoader(),
new Class<?>[] {UsdtConfigMapper.class}, (proxy, method, args) -> config);
ChainExecutorClient client = new ChainExecutorClient() {
@Override public boolean isEnabled() { return enabled; }
@Override public boolean ready() { return ready; }
@Override public void notifyExecutor() { notifications++; /* 模拟通知响应丢失 */ }
};
WalletSigningService signing = new WalletSigningService() {
@Override public <T> T execute(WalletAddressPlus wallet, String password, SignedOperation<T> operation) {
localExecutions++;
try { return operation.execute(null, null, wallet); }
catch (Exception ex) { throw new IllegalStateException(ex); }
}
@Override public void validateConfigurationPassword(String password) { }
};
ChainCommandExecutor executor = new ChainCommandExecutor(store, signing, null, configs, null) {
@Override public void execute(String id, String password) { localExecutions++; }
};
router = new ChainExecutionRouter(client, store, executor, signing, configs);
}
@After public void clearContext() { SecurityContextHolder.clearContext(); }
@Test
public void disabledFeatureUsesOriginalPasswordCallbackWithoutNewTable() {
enabled = false;
store.jdbc().execute("drop table usdt_chain_execution");
assertEquals("legacy-result", router.execute("trx", wallet(), request("password"), "WALLET:test",
(tron, api, wallet) -> "legacy-result"));
assertEquals(1, localExecutions);
assertEquals(0, notifications);
}
@Test
public void offlineBeforeSubmissionRequiresPasswordAndCreatesNoExecution() {
ready = false;
try {
router.execute("trx", wallet(), request(null), "WALLET:test", null);
fail("离线不得创建远程任务");
} catch (CustomException expected) {
assertFalse(expected instanceof ChainExecutionPendingException);
}
assertNull(store.byBusinessKey("WALLET:test"));
assertEquals(0, localExecutions);
}
@Test
public void remotePendingDoesNotFallbackEvenWhenUserSubmitsPassword() {
expectPending(request(null));
String original = (String) store.byBusinessKey("WALLET:test").get("execution_id");
ready = false;
expectPending(request("password"));
assertEquals(original, store.byBusinessKey("WALLET:test").get("execution_id"));
assertEquals(0, localExecutions);
WalletOperationRequest changed = request("password");
changed.setAmount(BigDecimal.TEN);
try { router.execute("trx", wallet(), changed, "WALLET:test", null); fail("同编号不能改变金额"); }
catch (CustomException expected) { assertFalse(expected instanceof ChainExecutionPendingException); }
assertEquals(0, localExecutions);
}
private void expectPending(WalletOperationRequest request) {
try { router.execute("trx", wallet(), request, "WALLET:test", null); fail("应查询原任务"); }
catch (ChainExecutionPendingException expected) { /* 正确保留执行占位 */ }
}
private WalletOperationRequest request(String password) {
WalletOperationRequest request = new WalletOperationRequest();
request.setAmount(BigDecimal.ONE);
request.setToAddress("test-target");
request.setBroadcast(true);
request.setConfigurationPassword(password);
return request;
}
private WalletAddressPlus wallet() {
WalletAddressPlus wallet = new WalletAddressPlus();
wallet.setToken("test-main");
wallet.setTokenIndex("0");
return wallet;
}
}
@@ -0,0 +1,117 @@
package com.ruoyi.system.chain;
import com.ruoyi.system.domain.vo.WalletOperationRequest;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.junit.Assert.*;
/** 隔离 H2 集成测试:使用实际增量脚本,覆盖唯一约束、抢占和签名后失败保护。 */
public class ChainExecutionStoreTest {
private ChainExecutionStore store;
@Before
public void setup() throws Exception {
DriverManagerDataSource data = new DriverManagerDataSource("jdbc:h2:mem:" + System.nanoTime()
+ ";MODE=MySQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1", "sa", "");
store = new ChainExecutionStore(data);
String sql = new String(Files.readAllBytes(Paths.get("../sql/chain_executor.sql")), StandardCharsets.UTF_8);
// H2 不支持 MySQL 表级 COMMENT=;仅去除存储引擎/字符集/表备注,保留全部列与索引。
store.jdbc().execute(sql.replaceAll("ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='[^']*'", ""));
}
@Test
public void concurrentDeliveryCreatesAndClaimsOnlyOneExecution() throws Exception {
ExecutorService threads = Executors.newFixedThreadPool(8);
try {
List<Callable<String>> attempts = new ArrayList<>();
for (int i = 0; i < 16; i++) attempts.add(() -> (String) store.create(command(), true).get("execution_id"));
List<Future<String>> results = threads.invokeAll(attempts);
String id = results.get(0).get();
for (Future<String> result : results) assertEquals(id, result.get());
List<Callable<Boolean>> claims = new ArrayList<>();
for (int i = 0; i < 16; i++) claims.add(() -> store.claim(id));
int winners = 0;
for (Future<Boolean> result : threads.invokeAll(claims)) if (result.get()) winners++;
assertEquals(1, winners);
} finally {
threads.shutdownNow();
}
}
@Test
public void signedTransactionCannotBecomeRetryableFailure() {
String id = (String) store.create(command(), true).get("execution_id");
assertTrue(store.claim(id));
byte[] signed = new byte[] {1, 2, 3};
store.signed(id, "fixed-transaction-hash", signed);
store.failBeforeSigning(id);
store.archiveFailure(command().businessKey);
assertEquals("SIGNED", store.get(id).get("status"));
assertArrayEquals(signed, (byte[]) store.get(id).get("signed_transaction"));
assertEquals(id, store.byBusinessKey(command().businessKey).get("execution_id"));
assertFalse(store.claim(id));
store.broadcasted(id);
store.failBeforeSigning(id);
assertEquals("BROADCASTED", store.get(id).get("status"));
}
@Test
public void failureBeforeSigningCanBeArchivedWithoutLosingAudit() {
String id = (String) store.create(command(), false).get("execution_id");
store.claim(id);
store.failBeforeSigning(id);
store.archiveFailure(command().businessKey);
String next = (String) store.create(command(), true).get("execution_id");
assertNotEquals(id, next);
assertEquals("FAILED", store.get(id).get("status"));
assertEquals(1, ((Number) store.get(id).get("reconciled")).intValue());
}
@Test
public void passwordIsNeverPersistedEvenIfCallerSetsIt() {
ChainCommand command = command();
command.operation.setConfigurationPassword("never-persist-this-password");
Map<String, Object> row = store.create(command, true);
assertFalse(((String) row.get("command_json")).contains("never-persist"));
}
@Test
public void onlyConfirmedFailureOfSameHashAllowsPayoutRetry() {
String id = (String) store.create(command(), true).get("execution_id");
store.claim(id);
store.signed(id, "known-hash", new byte[] {1});
store.broadcasted(id);
store.chainFailed(command().businessKey, "other-hash");
assertEquals("BROADCASTED", store.get(id).get("status"));
store.chainFailed(command().businessKey, "known-hash");
assertEquals("CHAIN_FAILED", store.get(id).get("status"));
store.archiveFailure(command().businessKey);
assertNotEquals(id, store.create(command(), false).get("execution_id"));
assertEquals("known-hash", store.get(id).get("transaction_id"));
}
private ChainCommand command() {
ChainCommand command = new ChainCommand();
command.businessKey = "PAYOUT:123";
command.operatorId = 1L;
command.type = "usdt";
command.operation = new WalletOperationRequest();
command.operation.setAmount(new BigDecimal("1.000001"));
command.operation.setBroadcast(true);
return command;
}
}
@@ -0,0 +1,89 @@
package com.ruoyi.system.chain.resource;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.system.rental.RentalCrypto;
import okhttp3.FormBody;
import okhttp3.Request;
import okio.Buffer;
import org.junit.Test;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.junit.Assert.*;
/** 使用内存HTTP替身检查两种不同认证/编码协议,绝不访问租赁平台。 */
public class ResourceRentalProviderTest {
private final ObjectMapper json = new ObjectMapper();
@Test
public void duiyaUsesResourceOrdersAndDocumentedAuthentication() throws Exception {
FakeHttp http = new FakeHttp();
DuiyaResourceRentalProvider adapter = new DuiyaResourceRentalProvider(http);
Map<String, Object> config = config("https://weidubot.cc/api/v2");
ResourceRentalProvider.Quote quote = adapter.quote(config, "MAINNET", "receiver", "BANDWIDTH", 500);
assertEquals("net", http.request.url().queryParameter("type"));
assertEquals("/api/v2/query_price", http.request.url().encodedPath());
String timestamp = http.request.header("x-timestamp");
assertEquals(ResourceProviderHttp.hmac("test-secret", "test-key" + timestamp), http.request.header("x-signature"));
http.payload = "{\"code\":1,\"data\":{\"order_sn\":\"net-order\"}}";
assertEquals("net-order", adapter.create(config, "local-id", quote).orderNo);
assertEquals("/api/v2/buy_net", http.request.url().encodedPath());
FormBody form = (FormBody) http.request.body();
assertEquals("count", form.name(0));
assertEquals("500", form.value(0));
assertEquals("address", form.name(2));
assertEquals("receiver", form.value(2));
}
@Test
public void internalUsesStableMerchantNumberAndSignsExactJson() throws Exception {
FakeHttp http = new FakeHttp();
http.payload = "{\"code\":200,\"data\":{\"amount\":\"1.2\"}}";
InternalResourceRentalProvider adapter = new InternalResourceRentalProvider(http);
Map<String, Object> config = config("https://rental.example.invalid");
ResourceRentalProvider.Quote quote = adapter.quote(config, "NILE", "receiver", "ENERGY", 60000);
http.payload = "{\"code\":200,\"data\":{\"order_no\":\"internal-order\",\"status\":\"PENDING\"}}";
adapter.create(config, "fixed-id", quote);
Buffer buffer = new Buffer(); http.request.body().writeTo(buffer);
String body = buffer.readUtf8();
Map<String, Object> request = json.readValue(body, new TypeReference<Map<String, Object>>() { });
assertEquals("fixed-id", request.get("merchant_order_no"));
assertFalse(request.containsKey("package_id"));
assertEquals("NILE", request.get("network"));
assertEquals("1.2", request.get("expected_amount"));
assertEquals(RentalCrypto.sign("test-secret", "API", "test-key",
Long.parseLong(http.request.header("X-Rent-Timestamp")), http.request.header("X-Rent-Nonce"),
"POST", "/api/rental/v1/create", body), http.request.header("X-Rent-Signature"));
}
@Test
public void duiyaRejectsBusinessErrorEvenIfHttpSuccess() {
FakeHttp http = new FakeHttp();
http.payload = "{\"code\":0,\"data\":{\"amount\":\"1.2\"}}";
try {
new DuiyaResourceRentalProvider(http).quote(config("https://example.invalid"), "MAINNET", "receiver", "ENERGY", 30000);
fail("business error must not become a usable quote");
} catch (com.ruoyi.common.exception.CustomException expected) { }
}
private Map<String, Object> config(String url) {
Map<String, Object> config = new LinkedHashMap<>();
config.put("base_url", url); config.put("energy_period", "1h");
config.put("bandwidth_period", "1day"); config.put("duration_seconds", 3600);
return config;
}
private class FakeHttp extends ResourceProviderHttp {
Request request;
String payload = "{\"code\":1,\"data\":{\"amount\":\"1.2\"}}";
FakeHttp() { super(null); }
public String key(Map<String, Object> config) { return "test-key"; }
public String secret(Map<String, Object> config) { return "test-secret"; }
public Map<String, Object> send(Request value) {
request = value;
try { return json.readValue(payload, new TypeReference<Map<String, Object>>() { }); }
catch (Exception impossible) { throw new IllegalStateException(impossible); }
}
}
}
@@ -0,0 +1,192 @@
package com.ruoyi.system.chain.resource;
import com.ruoyi.system.chain.ChainCommand;
import com.ruoyi.system.domain.vo.WalletOperationRequest;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.*;
/**
* 实际增量SQL + H2事务隔离测试。平台和链上查询均为可控替身,不访问外网、不付费、不签名。
* 特别覆盖“租赁受理成功并不等于到账”以及并发/超时不能重复付费的行为契约。
*/
public class ResourceRentalServiceTest {
private ResourceLeaseStore store;
private ResourceRentalService service;
private FakeProbe probe;
private FakeProvider provider;
private ChainCommand command;
@Before
public void setup() throws Exception {
DriverManagerDataSource data = new DriverManagerDataSource("jdbc:h2:mem:resource" + System.nanoTime()
+ ";MODE=MySQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1", "sa", "");
DataSourceTransactionManager manager = new DataSourceTransactionManager(data);
store = new ResourceLeaseStore(data, manager);
for (String file : Arrays.asList("resource_rental.sql", "chain_executor.sql")) {
String sql = new String(Files.readAllBytes(Paths.get("../sql/" + file)), StandardCharsets.UTF_8);
store.jdbc().execute(sql.replaceAll("ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='[^']*'", ""));
}
store.jdbc().update("insert into usdt_resource_rental_config(provider_code,network,base_url,api_key_cipher,api_secret_cipher,currency) values('INTERNAL','NILE','https://example.invalid','cipher','cipher','USDT')");
command = command("PAYOUT:1", "sender");
probe = new FakeProbe();
provider = new FakeProvider();
service = new ResourceRentalService(new ResourceRentalProperties() {
public boolean isEnabled() { return true; }
public String getProvider() { return "INTERNAL"; }
public int getTimeoutSeconds() { return 300; }
}, store, probe, Collections.singletonList(provider), manager);
ResourceBusinessResolver resolver = new ResourceBusinessResolver(store, null) {
public List<ChainCommand> resolve(String kind, Long id) {
return Collections.singletonList(command(kind + ":" + id, "sender"));
}
public void validateQueued(ChainCommand ignored) { }
};
Field field = ResourceRentalService.class.getDeclaredField("businessResolver");
field.setAccessible(true);
field.set(service, resolver);
}
@Test
public void previewNeverBuysAndBothResourcesMustArrive() {
service.preview(command);
assertEquals(0, provider.creates.get());
service.prepare(command, new BigDecimal("2"));
assertEquals(2, provider.creates.get());
assertEquals("WAITING", preparation().get("stage"));
probe.energy = 100;
service.check(preparation());
assertEquals("WAITING", preparation().get("stage"));
probe.bandwidth = 100;
service.check(preparation());
assertEquals("READY", preparation().get("stage"));
assertTrue(new ResourceExecutionGate(store, probe).ready(command));
probe.energy = 0;
assertFalse(new ResourceExecutionGate(store, probe).ready(command));
assertEquals(2, provider.creates.get());
}
@Test
public void concurrentPreparePaysOncePerResource() throws Exception {
ExecutorService threads = Executors.newFixedThreadPool(8);
try {
List<Callable<Void>> calls = new ArrayList<>();
for (int i = 0; i < 16; i++) calls.add(() -> { service.prepare(command, new BigDecimal("2")); return null; });
for (Future<Void> call : threads.invokeAll(calls)) call.get();
assertEquals(2, provider.creates.get());
assertEquals(2, service.orders(preparation()).size());
} finally { threads.shutdownNow(); }
}
@Test
public void unknownCreateResultBlocksEvenWhenResourcesLaterAppear() {
provider.uncertain = true;
service.prepare(command, new BigDecimal("2"));
probe.energy = 100; probe.bandwidth = 100;
service.prepare(command, new BigDecimal("2"));
service.preview(command);
service.resume(command);
assertEquals("REVIEW", preparation().get("stage"));
assertFalse(new ResourceExecutionGate(store, probe).ready(command));
assertEquals(2, provider.creates.get());
}
@Test
public void timeoutResumeAndConfigSwitchReuseOriginalOrders() {
service.prepare(command, new BigDecimal("2"));
store.jdbc().update("update usdt_resource_rental_config set enabled=0");
store.jdbc().update("update usdt_resource_preparation set deadline_at=?", new Timestamp(1));
service.check(preparation());
assertEquals("TIMEOUT", preparation().get("stage"));
probe.energy = 100; probe.bandwidth = 100;
service.resume(command);
assertEquals("READY", preparation().get("stage"));
service.preview(command);
assertEquals(2, provider.creates.get());
}
@Test
public void rpcFailureAndFeeLimitNeverCreatePaidOrder() {
probe.unavailable = true;
try { service.prepare(command, BigDecimal.TEN); fail(); } catch (IllegalStateException expected) { }
probe.unavailable = false;
try { service.prepare(command, BigDecimal.ONE); fail(); } catch (RuntimeException expected) { }
assertEquals(0, provider.creates.get());
assertTrue(service.orders(preparation()).isEmpty());
}
@Test
public void addressIsExclusiveAndPublicViewContainsNoCommandOrRequests() {
service.prepare(command, new BigDecimal("2"));
ChainCommand other = command("PAYOUT:2", "sender");
service.prepare(other, new BigDecimal("2"));
assertEquals("ADDRESS_BUSY", store.byBusiness(other.businessKey).get("stage"));
assertEquals(2, provider.creates.get());
Map<String, Object> view = service.view(preparation());
assertFalse(view.containsKey("command_json"));
for (Map<String, Object> row : service.orders(preparation())) assertNotNull(row.get("request_json"));
assertFalse(store.encode(view).contains("request_json"));
}
@Test
public void abandonedSubmittingIsNeverResent() {
service.prepare(command, new BigDecimal("2"));
provider.uncertain = true;
store.jdbc().update("update usdt_resource_rental_order set status='SUBMITTING',updated_at=?", new Timestamp(1));
service.check(preparation());
assertEquals("REVIEW", preparation().get("stage"));
service.prepare(command, new BigDecimal("2"));
assertEquals(2, provider.creates.get());
}
private Map<String, Object> preparation() { return store.byBusiness(command.businessKey); }
private ChainCommand command(String key, String address) {
ChainCommand value = new ChainCommand();
value.businessKey = key; value.address = address; value.tokenIndex = "0";
value.network = 0; value.envelopeVersion = 1L; value.type = "usdt";
value.operation = new WalletOperationRequest();
value.operation.setToAddress("receiver"); value.operation.setAmount(BigDecimal.ONE);
return value;
}
private static class FakeProbe extends ResourceProbe {
volatile long energy, bandwidth;
volatile boolean unavailable;
FakeProbe() { super(null); }
public Observation inspect(ChainCommand ignored) {
if (unavailable) throw new IllegalStateException("mock RPC unavailable");
Observation value = new Observation();
value.requiredEnergy = 100; value.requiredBandwidth = 100;
value.availableEnergy = energy; value.availableBandwidth = bandwidth;
return value;
}
}
private static class FakeProvider implements ResourceRentalProvider {
final AtomicInteger creates = new AtomicInteger();
volatile boolean uncertain;
public String code() { return "INTERNAL"; }
public Quote quote(Map<String, Object> config, String network, String address, String resource, long quantity) {
Quote value = new Quote(); value.quantity = quantity; value.amount = BigDecimal.ONE;
value.currency = "USDT"; value.request = Collections.singletonMap("receiver_address", address);
return value;
}
public Submission create(Map<String, Object> config, String key, Quote quote) {
creates.incrementAndGet();
if (uncertain) throw new IllegalStateException("mock response lost after purchase");
return new Submission(key, "PENDING");
}
public String query(Map<String, Object> config, String key, String order) { return uncertain ? "UNKNOWN" : "SUCCESS"; }
}
}