租赁资金账户资金充值功能,对接项目的支付接口,application-rental.yml添加配置NILE和主网的对接配置
This commit is contained in:
1 parent
911a3634ee
commit
e73f099734
20 files changed
+878
-9
No files matched your search
@@ -0,0 +1,195 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
import static org.junit.Assert.*;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.security.*;
|
||||
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 org.springframework.core.io.DefaultResourceLoader;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
/** 隔离MySQL兼容DDL与真实事务测试;支付和链上适配器可控,不访问真实账户或广播。 */
|
||||
public class RentalTopupTest {
|
||||
private static final String ADDRESS = "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf";
|
||||
private static final String HASH = String.join("", Collections.nCopies(64, "a"));
|
||||
private RentalStore store;
|
||||
private RentalFunds funds;
|
||||
private RentalTopups service;
|
||||
private RentalPaymentProperties config;
|
||||
private RentalPaymentClient client;
|
||||
private TransactionTemplate tx;
|
||||
private long account;
|
||||
private String paymentNetwork = "NILE";
|
||||
private String paymentAmount = "10.000000";
|
||||
private int paymentStatus = 1;
|
||||
private boolean failCreate;
|
||||
private boolean failChain;
|
||||
private Set<String> created = new HashSet<>();
|
||||
private int createCalls;
|
||||
private int chainCalls;
|
||||
private final ObjectMapper json = new ObjectMapper();
|
||||
|
||||
@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);
|
||||
store = new RentalStore(jdbc);
|
||||
for (String file : Arrays.asList("rent_init.sql", "rent_topup_init.sql")) {
|
||||
String ddl = new String(Files.readAllBytes(Paths.get("../sql/" + file)), StandardCharsets.UTF_8)
|
||||
.replaceAll("(?m)^--.*$", "").replace("CHARACTER SET ascii COLLATE ascii_bin", "")
|
||||
.replaceAll("(?i)\\bJSON\\b", "LONGTEXT")
|
||||
.replace("ENGINE=InnoDB ROW_FORMAT=DYNAMIC DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin", "");
|
||||
for (String sql : ddl.split(";")) if (!sql.trim().isEmpty()) jdbc.execute(sql);
|
||||
}
|
||||
DataSourceTransactionManager manager = new DataSourceTransactionManager(source);
|
||||
tx = new TransactionTemplate(manager);
|
||||
funds = new RentalFunds(store);
|
||||
account = number(funds.account(10, "NILE"), "id");
|
||||
config = new RentalPaymentProperties(); config.setEnabled(true);
|
||||
RentalPaymentProperties.Channel channel = config.getNile();
|
||||
channel.setEnabled(true); channel.setBaseUrl("https://pay.example.com");
|
||||
channel.setApiKey("payment-key"); channel.setApiSecret("test-secret");
|
||||
channel.setNotifyUrl("https://rent.example.com/api/rental/payment/notify/NILE");
|
||||
client = new RentalPaymentClient(json, config, new DefaultResourceLoader()) {
|
||||
@Override public String publicKey(RentalPaymentProperties.Channel value) { return "public-key-fixture"; }
|
||||
@Override public boolean verify(Map<String, Object> order, Map<String, Object> payload, String key, String signature) {
|
||||
return "payment-key".equals(key) && "valid".equals(signature);
|
||||
}
|
||||
@Override public Map<String, Object> call(Map<String, Object> order, String operation) {
|
||||
String no = text(order, "topup_no");
|
||||
if ("create-transaction".equals(operation)) {
|
||||
createCalls++; created.add(no);
|
||||
if (failCreate) throw new IllegalStateException("controlled lost response");
|
||||
return map("order_id", no, "trade_id", "P" + no, "payment_address", ADDRESS,
|
||||
"payment_amount", money("10"), "expiration_time", System.currentTimeMillis() + 600000,
|
||||
"url", "https://pay.example.com/checkout?trade=" + no);
|
||||
}
|
||||
return map("order_id", no, "trade_id", "P" + no, "status", paymentStatus,
|
||||
"transaction_id", HASH, "network", paymentNetwork,
|
||||
"payment_amount", money(paymentAmount), "payment_address", ADDRESS);
|
||||
}
|
||||
};
|
||||
RentalChain chain = new RentalChain(json) {
|
||||
@Override public Map<String, Object> paymentTransfer(String network, String hash, String address,
|
||||
java.math.BigDecimal amount, long createdAt, long expiresAt) {
|
||||
chainCalls++;
|
||||
assertEquals("NILE", network); assertEquals(HASH, hash); assertEquals(ADDRESS, address);
|
||||
assertEquals(money("10"), amount);
|
||||
if (failChain) throw new IllegalStateException("controlled unconfirmed transfer");
|
||||
return map("reference", "NILE:" + HASH + ":0", "log_index", 0);
|
||||
}
|
||||
};
|
||||
service = new RentalTopups(store, funds, chain, config, client, manager);
|
||||
}
|
||||
private Map<String, Object> create(String request) throws Exception {
|
||||
return service.create(10, map("network", "NILE", "amount", "10.00", "client_request_no", request));
|
||||
}
|
||||
private long id(Map<String, Object> view) { return number(store.one("SELECT id FROM rent_topup_order WHERE topup_no=?", view.get("topup_no")), "id"); }
|
||||
private void due(long id) { store.update("topup_order", id, map("next_query_at", now().minusSeconds(1))); }
|
||||
private Map<String, Object> payload(Map<String, Object> row) { return map("order_id", row.get("topup_no"), "trade_id", "P" + row.get("topup_no"), "status", 2, "transaction_id", HASH); }
|
||||
|
||||
@Test public void duplicateCreateNotificationAndPollingCreditOnce() throws Exception {
|
||||
Map<String, Object> first = create("click-1");
|
||||
assertEquals("WAITING_PAYMENT", first.get("status"));
|
||||
assertEquals(first.get("topup_no"), create("click-1").get("topup_no"));
|
||||
service.notify("NILE", payload(first), "payment-key", "valid");
|
||||
service.notify("NILE", payload(first), "payment-key", "valid");
|
||||
assertEquals(1, number(store.one("SELECT COUNT(*) AS n FROM rent_topup_notify"), "n"));
|
||||
assertEquals(ZERO, amount(store.get("account", account, false), "available_amount"));
|
||||
paymentStatus = 2; due(id(first)); service.reconcile(id(first)); service.reconcile(id(first));
|
||||
assertEquals("CREDITED", service.detail(10, text(first, "topup_no")).get("status"));
|
||||
assertEquals(money("10"), amount(store.get("account", account, false), "available_amount"));
|
||||
assertEquals(1, number(store.one("SELECT COUNT(*) AS n FROM rent_ledger"), "n"));
|
||||
assertEquals("DONE", store.one("SELECT * FROM rent_topup_notify").get("status"));
|
||||
assertFalse(first.containsKey("payment_api_key")); assertFalse(first.containsKey("payment_public_key"));
|
||||
assertEquals(1, createCalls);
|
||||
}
|
||||
@Test public void lostCreateResponseRetriesOriginalPaymentOrder() throws Exception {
|
||||
failCreate = true;
|
||||
Map<String, Object> first = create("lost");
|
||||
assertEquals("CREATE_UNKNOWN", first.get("status"));
|
||||
failCreate = false; due(id(first)); service.reconcile(id(first));
|
||||
assertEquals(1, created.size());
|
||||
assertEquals("WAITING_PAYMENT", service.detail(10, text(first, "topup_no")).get("status"));
|
||||
}
|
||||
@Test public void networkAndAmountMismatchNeverCredit() throws Exception {
|
||||
paymentStatus = 2; paymentNetwork = "MAINNET";
|
||||
Map<String, Object> wrongNetwork = create("network");
|
||||
assertEquals("MANUAL_REVIEW", wrongNetwork.get("status"));
|
||||
paymentNetwork = "NILE"; paymentAmount = "11";
|
||||
assertEquals("MANUAL_REVIEW", create("amount").get("status"));
|
||||
assertEquals(0, chainCalls);
|
||||
assertEquals(ZERO, amount(store.get("account", account, false), "available_amount"));
|
||||
}
|
||||
@Test public void chainFailureWaitsAndFrozenAccountGoesToReview() throws Exception {
|
||||
paymentStatus = 2; failChain = true;
|
||||
Map<String, Object> first = create("chain");
|
||||
assertEquals("VERIFYING", first.get("status"));
|
||||
failChain = false; store.update("account", account, map("status", "FROZEN"));
|
||||
due(id(first)); service.reconcile(id(first));
|
||||
assertEquals("MANUAL_REVIEW", service.detail(10, text(first, "topup_no")).get("status"));
|
||||
assertEquals(ZERO, amount(store.get("account", account, false), "available_amount"));
|
||||
}
|
||||
@Test public void invalidSignatureAndOwnershipAreRejected() throws Exception {
|
||||
Map<String, Object> first = create("auth");
|
||||
assertThrows(IllegalArgumentException.class, () -> service.detail(20, text(first, "topup_no")));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.notify("NILE", payload(first), "payment-key", "forged"));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.notify("MAINNET", payload(first), "payment-key", "valid"));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(10, map("network", "NILE", "amount", "11", "client_request_no", "auth")));
|
||||
}
|
||||
@Test public void manualAndAutomaticTopupShareTransferIdempotency() throws Exception {
|
||||
Map<String, Object> first = create("manual");
|
||||
tx.execute(status -> { funds.post(account, "TOPUP:NILE:" + HASH + ":0", "TOPUP", money("10"), ZERO, ZERO, ZERO, null, null, null, 99, HASH, "manual"); return null; });
|
||||
paymentStatus = 2; due(id(first)); service.reconcile(id(first));
|
||||
assertEquals("MANUAL_REVIEW", service.detail(10, text(first, "topup_no")).get("status"));
|
||||
assertEquals(money("10"), amount(store.get("account", account, false), "available_amount"));
|
||||
}
|
||||
@Test public void realRsaVerificationRejectsTamperingAndWrongKey() throws Exception {
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048);
|
||||
KeyPair pair = generator.generateKeyPair();
|
||||
String pem = "-----BEGIN PUBLIC KEY-----\n" + Base64.getEncoder().encodeToString(pair.getPublic().getEncoded()) + "\n-----END PUBLIC KEY-----";
|
||||
Map<String, Object> order = map("payment_api_key", "payment-key", "payment_public_key", pem);
|
||||
Map<String, Object> payload = map("order_id", "demo", "status", 2);
|
||||
String signature = com.ruoyi.system.service.PaymentSignatureService.signRsa(payload, pair.getPrivate());
|
||||
RentalPaymentClient real = new RentalPaymentClient(json, config, new DefaultResourceLoader());
|
||||
assertTrue(real.verify(order, payload, "payment-key", signature));
|
||||
assertFalse(real.verify(order, payload, "other-key", signature));
|
||||
payload.put("status", 1); assertFalse(real.verify(order, payload, "payment-key", signature));
|
||||
}
|
||||
|
||||
@Test public void concurrentReconciliationCreditsOnlyOnceWithoutNotification() throws Exception {
|
||||
Map<String, Object> first = create("parallel");
|
||||
long orderId = id(first);
|
||||
paymentStatus = 2; due(orderId);
|
||||
ExecutorService workers = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<?> left = workers.submit(() -> service.reconcile(orderId));
|
||||
Future<?> right = workers.submit(() -> service.reconcile(orderId));
|
||||
left.get(20, TimeUnit.SECONDS); right.get(20, TimeUnit.SECONDS);
|
||||
} finally { workers.shutdownNow(); }
|
||||
assertEquals("CREDITED", service.detail(10, text(first, "topup_no")).get("status"));
|
||||
assertEquals(money("10"), amount(store.get("account", account, false), "available_amount"));
|
||||
assertEquals(1, number(store.one("SELECT COUNT(*) AS n FROM rent_ledger"), "n"));
|
||||
}
|
||||
|
||||
@Test public void expiredWorkerCannotOverwriteNewLeaseOrTerminalState() throws Exception {
|
||||
Map<String, Object> first = create("lease"); long orderId = id(first);
|
||||
store.update("topup_order", orderId, map("lease_token", "new-owner"));
|
||||
java.lang.reflect.Method method = RentalTopups.class.getDeclaredMethod("updateOwned", long.class, String.class, Map.class);
|
||||
method.setAccessible(true);
|
||||
method.invoke(service, orderId, "expired-owner", map("status", "EXPIRED"));
|
||||
assertEquals("WAITING_PAYMENT", service.detail(10, text(first, "topup_no")).get("status"));
|
||||
store.update("topup_order", orderId, map("status", "CREDITED"));
|
||||
method.invoke(service, orderId, "new-owner", map("status", "WAITING_PAYMENT"));
|
||||
assertEquals("CREDITED", service.detail(10, text(first, "topup_no")).get("status"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user