fix: complete student issuance wallet and supervision flow

master
chenyuan1 4 weeks ago
parent d78ec58d96
commit 3edc29f797

@ -31,3 +31,17 @@
浏览器跑通模块五六步,并核对数据库订单 `SUCCESS`、实训 `COMPLETED`、付款余额 9000、收款余额 1000 和单笔双边准备金分录。模块四抽测正确卡号提交、错误原文拦截及刷新恢复。前后端构建通过。部署后应用空闲约 15 分钟的健康检查为 `UP`,耗时 144 毫秒。 浏览器跑通模块五六步,并核对数据库订单 `SUCCESS`、实训 `COMPLETED`、付款余额 9000、收款余额 1000 和单笔双边准备金分录。模块四抽测正确卡号提交、错误原文拦截及刷新恢复。前后端构建通过。部署后应用空闲约 15 分钟的健康检查为 `UP`,耗时 144 毫秒。
该专项结论不等于全项目验收;此前基线中的模块一及 SSO 旧测试问题未在本次修改业务规则或放宽断言来消除。 该专项结论不等于全项目验收;此前基线中的模块一及 SSO 旧测试问题未在本次修改业务规则或放宽断言来消除。
## 学生完整流程补充升级
五万元申请会生成 500 枚百元币串,其逐枚 SM2 签名汇总原文超过 MySQL `TEXT` 的 65535 字节容量。已有库部署前执行 `src/main/resources/db/manual/issuance_ownership_confirmation_capacity_upgrade.sql`,将确权原文字段扩容为 `MEDIUMTEXT`;脚本可重复执行,不修改业务行数据。新库的 `schema.sql` 已同步。
币串生成、来源预留和确权入库改为批量持久化;每次批量签名或验签仅查询一次当前用户、学校、班级的备案密钥,仍逐枚执行真实 SM2 运算。模块一生成请求对批次加锁,已生成批次重试返回原币串,避免重新分配币串标识或覆盖已预留、已发行状态。
模块三的新合约编号增加 UUID,避免同日不同学生都生成 `CTR_日期_001` 而导致模块四共享钱包投影冲突。历史已签名合约保留原文与摘要;仅当旧编号已被其他钱包占用时,为当前钱包建立稳定的独立运行态编号,不更新其他钱包的合约或限额计数。非旧格式编号发生冲突仍拒绝。
本轮在指定 MySQL 库实际执行确权字段扩容,并使用学生账号从页面完成模块一至五:生成及发行 500 枚百元币、开通钱包、兑换 5000 元、支付 1000 元。发行状态为 `RECEIPT_SENT`;支付订单为 `SUCCESS`、实验为 `COMPLETED`,付款及收款余额分别为 9000 元与 1000 元,双边钱包流水、准备金分录及双方通知均已核对。模块四、五使用原有独立教学案例币,不消耗模块二发行库存。
本轮聚焦回归 70 项全部通过,覆盖 500 枚币串生成及重试、预留释放与再预留、真实 SM2 批量签验、跨用户密钥隔离、历史合约碰撞和模块二/四/五动作接口。该结果仍不代表全项目旧测试全部通过。
模块六监管备案输出补记第八步完成,旧备案重放输出也可修复漏记进度,并保持原备案编号、时间及报文不变。未签名记录仍拒绝输出。新增 3 项回归先复现漏记问题,修复后全部通过;学生现有备案经页面重新确认后进度由 87.5% 恢复为 100%。

@ -175,6 +175,8 @@ public class DonationSupervisionService {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先完成SM2签名"); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先完成SM2签名");
} }
if (supervision.getOutputJson() != null) { if (supervision.getOutputJson() != null) {
// 兼容已备案但旧版本漏记最后一步的记录;原备案内容保持不变。
scoreService.markStepCompleted(subject.getUserId(), 8);
return buildOutputResult(supervision); return buildOutputResult(supervision);
} }
@ -195,6 +197,7 @@ public class DonationSupervisionService {
supervision.output(approvalTime, recordNumber, json); supervision.output(approvalTime, recordNumber, json);
supervisionRepository.update(supervision); supervisionRepository.update(supervision);
scoreService.markStepCompleted(subject.getUserId(), 8);
return result; return result;
} }

@ -16,6 +16,8 @@ import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List;
import java.util.ArrayList;
@Service @Service
public class InstitutionKeyService { public class InstitutionKeyService {
@ -104,6 +106,25 @@ public class InstitutionKeyService {
return cryptography.sign(privateKey(subject, CENTRAL_FIRST_KEY), message); return cryptography.sign(privateKey(subject, CENTRAL_FIRST_KEY), message);
} }
@Transactional(readOnly = true)
public List<String> signCentralBankMessages(InstitutionKeySubject subject, List<String> messages) {
// 密钥只在本次调用中复用,仍按用户、学校、班级查询,逐枚执行真实 SM2 签名。
String key = privateKey(subject, CENTRAL_FIRST_KEY);
List<String> signatures = new ArrayList<>();
for (String message : messages) signatures.add(cryptography.sign(key, message));
return signatures;
}
@Transactional(readOnly = true)
public boolean verifyCentralBankMessages(InstitutionKeySubject subject, List<String> messages, List<String> signatures) {
if (messages.size() != signatures.size()) return false;
String publicKey = required(subject, CENTRAL_FIRST_KEY).getPublicKey();
for (int i=0; i<messages.size(); i++) {
if (!cryptography.verify(publicKey, messages.get(i), signatures.get(i))) return false;
}
return true;
}
@Transactional(readOnly = true) @Transactional(readOnly = true)
public boolean verifyCentralBank(InstitutionKeySubject subject, String message, String signature) { public boolean verifyCentralBank(InstitutionKeySubject subject, String message, String signature) {
return cryptography.verify(required(subject, CENTRAL_FIRST_KEY).getPublicKey(), message, signature); return cryptography.verify(required(subject, CENTRAL_FIRST_KEY).getPublicKey(), message, signature);

@ -1,6 +1,7 @@
package com.yau.digitalrmb.institutionidentity.application; package com.yau.digitalrmb.institutionidentity.application;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yau.digitalrmb.institutionidentity.infrastructure.QuotaControlBitEntity; import com.yau.digitalrmb.institutionidentity.infrastructure.QuotaControlBitEntity;
import com.yau.digitalrmb.institutionidentity.infrastructure.QuotaControlBitMapper; import com.yau.digitalrmb.institutionidentity.infrastructure.QuotaControlBitMapper;
@ -172,7 +173,11 @@ public class StandardCurrencyService {
@Transactional @Transactional
public StandardCurrencyBatchResult generate(InstitutionKeySubject subject, String operator) { public StandardCurrencyBatchResult generate(InstitutionKeySubject subject, String operator) {
StandardCurrencyBatchEntity batch = requireLatest(subject); StandardCurrencyBatchEntity owned = requireLatest(subject);
StandardCurrencyBatchEntity batch = batchMapper.lockById(owned.getId());
if (batch == null) throw stateChanged();
// 超时重试和并发点击必须返回同一批币串,不得重置已预留或已发行币串。
if ("GENERATED".equals(batch.getStatus())) return result(batch);
if (batch.getPrefix() == null || batch.getIdRule() == null || batch.getCurrencyStatus() == null) { if (batch.getPrefix() == null || batch.getIdRule() == null || batch.getCurrencyStatus() == null) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先确认币串生成规则"); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先确认币串生成规则");
} }
@ -188,34 +193,18 @@ public class StandardCurrencyService {
.eq(StandardCurrencyEntity::getDeleted, false) .eq(StandardCurrencyEntity::getDeleted, false)
.orderByAsc(StandardCurrencyEntity::getSequenceNumber)); .orderByAsc(StandardCurrencyEntity::getSequenceNumber));
SecureRandom random = new SecureRandom(); SecureRandom random = new SecureRandom();
List<StandardCurrencyEntity> pending = new ArrayList<>();
for (int i = 0; i < values.size(); i++) { for (int i = 0; i < values.size(); i++) {
int sequence = i + 1; int sequence = i + 1;
String sequenceText = String.format("%03d", sequence); String sequenceText = String.format("%03d", sequence);
String checkCode = checkCode(random); String checkCode = checkCode(random);
String currencyId = "DC_" + batch.getBatchNumber() + "_" + sequenceText + "_" + checkCode; String currencyId = "DC_" + batch.getBatchNumber() + "_" + sequenceText + "_" + checkCode;
String denomination = values.get(i).setScale(2).toPlainString(); String denomination = values.get(i).setScale(2).toPlainString();
if (i < existing.size()) { // 兼容历史未完成批次,保留已经持久化的币串标识。
StandardCurrencyEntity currency = existing.get(i); if (i < existing.size()) continue;
currencyMapper.update(null, new LambdaUpdateWrapper<StandardCurrencyEntity>() {
.eq(StandardCurrencyEntity::getId, currency.getId())
.eq(StandardCurrencyEntity::getDeleted, false)
.set(StandardCurrencyEntity::getSequenceNumber, sequence)
.set(StandardCurrencyEntity::getDenomination, values.get(i))
.set(StandardCurrencyEntity::getRandomCheckCode, checkCode)
.set(StandardCurrencyEntity::getCurrencyId, currencyId)
.set(StandardCurrencyEntity::getInstitutionIdentifier, source.getInstitutionIdentifier())
.set(StandardCurrencyEntity::getBankSignatureSegment, source.getBankSignature())
.set(StandardCurrencyEntity::getCentralBankSignatureSegment,
source.getCentralBankSignatureSegment())
.set(StandardCurrencyEntity::getCompleteCurrency,
currencyId + "_" + source.getInstitutionIdentifier() + "_" + denomination
+ "_" + source.getBankSignature() + "_"
+ source.getCentralBankSignatureSegment())
.set(StandardCurrencyEntity::getStatus, "待生效")
.set(StandardCurrencyEntity::getUpdatedAt, LocalDateTime.now())
.set(StandardCurrencyEntity::getUpdatedBy, operator));
} else {
StandardCurrencyEntity currency = new StandardCurrencyEntity(); StandardCurrencyEntity currency = new StandardCurrencyEntity();
currency.setId(IdWorker.getId());
currency.setBatchId(batch.getId()); currency.setBatchId(batch.getId());
currency.setSequenceNumber(sequence); currency.setSequenceNumber(sequence);
currency.setDenomination(values.get(i)); currency.setDenomination(values.get(i));
@ -232,8 +221,11 @@ public class StandardCurrencyService {
currency.setCreatedBy(operator); currency.setCreatedBy(operator);
currency.setUpdatedBy(operator); currency.setUpdatedBy(operator);
currency.setDeleted(false); currency.setDeleted(false);
currencyMapper.insert(currency); pending.add(currency);
}
} }
for (int offset = 0; offset < pending.size(); offset += 200) {
currencyMapper.insertBatch(pending.subList(offset, Math.min(offset + 200, pending.size())));
} }
int updated = batchMapper.update(null, new LambdaUpdateWrapper<StandardCurrencyBatchEntity>() int updated = batchMapper.update(null, new LambdaUpdateWrapper<StandardCurrencyBatchEntity>()
.eq(StandardCurrencyBatchEntity::getId, batch.getId()) .eq(StandardCurrencyBatchEntity::getId, batch.getId())

@ -2,7 +2,11 @@ package com.yau.digitalrmb.institutionidentity.infrastructure;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Param;
@Mapper @Mapper
public interface StandardCurrencyBatchMapper extends BaseMapper<StandardCurrencyBatchEntity> { public interface StandardCurrencyBatchMapper extends BaseMapper<StandardCurrencyBatchEntity> {
@Select("SELECT * FROM standard_currency_batch WHERE id=#{id} AND deleted=0 FOR UPDATE")
StandardCurrencyBatchEntity lockById(@Param("id") long id);
} }

@ -2,7 +2,16 @@ package com.yau.digitalrmb.institutionidentity.infrastructure;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper @Mapper
public interface StandardCurrencyMapper extends BaseMapper<StandardCurrencyEntity> { public interface StandardCurrencyMapper extends BaseMapper<StandardCurrencyEntity> {
@Insert({"<script>",
"INSERT INTO standard_currency (id,batch_id,sequence_number,denomination,random_check_code,currency_id,institution_identifier,bank_signature_segment,central_bank_signature_segment,complete_currency,status,created_at,updated_at,created_by,updated_by,deleted) VALUES",
"<foreach collection='currencies' item='c' separator=','>",
"(#{c.id},#{c.batchId},#{c.sequenceNumber},#{c.denomination},#{c.randomCheckCode},#{c.currencyId},#{c.institutionIdentifier},#{c.bankSignatureSegment},#{c.centralBankSignatureSegment},#{c.completeCurrency},#{c.status},#{c.createdAt},#{c.updatedAt},#{c.createdBy},#{c.updatedBy},#{c.deleted})",
"</foreach>", "</script>"})
int insertBatch(@Param("currencies") List<StandardCurrencyEntity> currencies);
} }

@ -23,6 +23,7 @@ import com.yau.digitalrmb.institutionidentity.infrastructure.StandardCurrencyBat
import com.yau.digitalrmb.institutionidentity.infrastructure.StandardCurrencyEntity; import com.yau.digitalrmb.institutionidentity.infrastructure.StandardCurrencyEntity;
import com.yau.digitalrmb.institutionidentity.infrastructure.StandardCurrencyMapper; import com.yau.digitalrmb.institutionidentity.infrastructure.StandardCurrencyMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
@ -103,6 +104,14 @@ public class DigitalCurrencyGenerationModuleGateway {
return required(keyService.signCentralBank(subject, required(ownershipText, "数字货币确权原文")), "央行第一私钥签名"); return required(keyService.signCentralBank(subject, required(ownershipText, "数字货币确权原文")), "央行第一私钥签名");
} }
public List<String> signOwnershipBatch(InstitutionKeySubject subject, List<String> texts) {
return keyService.signCentralBankMessages(subject, texts);
}
public boolean verifyOwnershipBatch(InstitutionKeySubject subject, List<String> texts, List<String> signatures) {
return keyService.verifyCentralBankMessages(subject, texts, signatures);
}
public String digest(String originalText) { public String digest(String originalText) {
if (cryptography == null) throw new BusinessException(ErrorCode.INTERNAL_ERROR, "SM3 digest service is not configured"); if (cryptography == null) throw new BusinessException(ErrorCode.INTERNAL_ERROR, "SM3 digest service is not configured");
return cryptography.sm3(required(originalText, "ownership confirmation original text")); return cryptography.sm3(required(originalText, "ownership confirmation original text"));
@ -182,39 +191,38 @@ public class DigitalCurrencyGenerationModuleGateway {
List<StandardCurrencyEntity> available = sourceUsageMapper.selectAvailableSourcesForUpdate(batch.getId()); List<StandardCurrencyEntity> available = sourceUsageMapper.selectAvailableSourcesForUpdate(batch.getId());
List<StandardCurrencyEntity> selected = selectExactQuantities(available, requested); List<StandardCurrencyEntity> selected = selectExactQuantities(available, requested);
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
List<Long> selectedIds = selected.stream().map(StandardCurrencyEntity::getId).collect(java.util.stream.Collectors.toList());
Map<Long, IssuanceSourceCurrencyUsageEntity> usages = new java.util.HashMap<>();
if (!selectedIds.isEmpty()) {
for (IssuanceSourceCurrencyUsageEntity usage : sourceUsageMapper.selectUsagesForUpdate(selectedIds)) {
usages.put(usage.getSourceCurrencyId(), usage);
}
}
List<IssuanceSourceCurrencyUsageEntity> pending = new ArrayList<>();
List<Long> released = new ArrayList<>();
for (StandardCurrencyEntity currency : selected) { for (StandardCurrencyEntity currency : selected) {
IssuanceSourceCurrencyUsageEntity existing = sourceUsageMapper.selectBySourceCurrencyIdForUpdate( IssuanceSourceCurrencyUsageEntity existing = usages.get(currency.getId());
currency.getId()); if (existing != null) {
if (existing == null) { if (!"RELEASED".equals(existing.getStatus())) throw validation("币串库存已变化,请重新获取后再发行");
released.add(currency.getId());
continue;
}
IssuanceSourceCurrencyUsageEntity usage = new IssuanceSourceCurrencyUsageEntity(); IssuanceSourceCurrencyUsageEntity usage = new IssuanceSourceCurrencyUsageEntity();
usage.setId(IdWorker.getId());
usage.setSourceCurrencyId(currency.getId()); usage.setSourceCurrencyId(currency.getId());
usage.setSourceBatchId(currency.getBatchId()); usage.setSourceBatchId(currency.getBatchId());
usage.setIssuanceRequestId(requestId.toString()); usage.setIssuanceRequestId(requestId.toString());
usage.setStatus("RESERVED"); usage.setStatus("RESERVED"); usage.setReservedAt(now);
usage.setReservedAt(now); usage.setAuditUserId(actor.getUserId()); usage.setAuditUsername(actor.getUsername());
usage.setAuditUserId(actor.getUserId()); usage.setCreatedAt(now); usage.setUpdatedAt(now);
usage.setAuditUsername(actor.getUsername()); pending.add(usage);
usage.setCreatedAt(now);
usage.setUpdatedAt(now);
if (sourceUsageMapper.insert(usage) != 1) {
throw validation("币串库存已变化,请重新获取后再发行");
}
} else {
int reused = sourceUsageMapper.update(null,
new LambdaUpdateWrapper<IssuanceSourceCurrencyUsageEntity>()
.eq(IssuanceSourceCurrencyUsageEntity::getId, existing.getId())
.eq(IssuanceSourceCurrencyUsageEntity::getStatus, "RELEASED")
.set(IssuanceSourceCurrencyUsageEntity::getIssuanceRequestId, requestId.toString())
.set(IssuanceSourceCurrencyUsageEntity::getStatus, "RESERVED")
.set(IssuanceSourceCurrencyUsageEntity::getReservedAt, now)
.set(IssuanceSourceCurrencyUsageEntity::getReleasedAt, null)
.set(IssuanceSourceCurrencyUsageEntity::getIssuedAt, null)
.set(IssuanceSourceCurrencyUsageEntity::getAuditUserId, actor.getUserId())
.set(IssuanceSourceCurrencyUsageEntity::getAuditUsername, actor.getUsername())
.set(IssuanceSourceCurrencyUsageEntity::getUpdatedAt, now));
if (reused != 1) throw validation("币串库存已变化,请重新获取后再发行");
} }
for (int offset=0; offset<pending.size(); offset+=200) {
List<IssuanceSourceCurrencyUsageEntity> chunk=pending.subList(offset,Math.min(offset+200,pending.size()));
if(sourceUsageMapper.insertReservations(chunk)!=chunk.size()) throw validation("币串库存已变化,请重新获取后再发行");
} }
if(!released.isEmpty() && sourceUsageMapper.reserveReleased(released,requestId.toString(),now,
actor.getUserId(),actor.getUsername())!=released.size()) throw validation("币串库存已变化,请重新获取后再发行");
return stockItems(selected); return stockItems(selected);
} }
@ -232,6 +240,15 @@ public class DigitalCurrencyGenerationModuleGateway {
String requiredInstitution = required(institutionIdentifier, "发行机构标识"); String requiredInstitution = required(institutionIdentifier, "发行机构标识");
requiredActor(actor); requiredActor(actor);
if (confirmedCoins == null || confirmedCoins.isEmpty()) throw validation("待确权币串不能为空"); if (confirmedCoins == null || confirmedCoins.isEmpty()) throw validation("待确权币串不能为空");
List<Long> sourceIds = confirmedCoins.stream().map(DraftDigitalCurrency::getSourceCurrencyId)
.collect(java.util.stream.Collectors.toList());
if(sourceIds.contains(null) || new java.util.HashSet<>(sourceIds).size()!=sourceIds.size())
throw validation("发行币串来源为空或重复");
Map<Long,StandardCurrencyEntity> sourceById=new java.util.HashMap<>();
for(StandardCurrencyEntity source:standardCurrencyMapper.selectBatchIds(sourceIds)) sourceById.put(source.getId(),source);
Map<Long,IssuanceSourceCurrencyUsageEntity> usageById=new java.util.HashMap<>();
for(IssuanceSourceCurrencyUsageEntity usage:sourceUsageMapper.selectUsagesForUpdate(sourceIds)) usageById.put(usage.getSourceCurrencyId(),usage);
java.util.Set<Long> checkedBatches=new java.util.HashSet<>();
BigDecimal totalAmount = BigDecimal.ZERO.setScale(2); BigDecimal totalAmount = BigDecimal.ZERO.setScale(2);
String currencyCode = null; String currencyCode = null;
List<StandardCurrencyEntity> sources = new ArrayList<StandardCurrencyEntity>(); List<StandardCurrencyEntity> sources = new ArrayList<StandardCurrencyEntity>();
@ -242,9 +259,8 @@ public class DigitalCurrencyGenerationModuleGateway {
if (!requiredInstitution.equals(coin.getOrganizationId())) throw validation("发行币串机构标识不一致"); if (!requiredInstitution.equals(coin.getOrganizationId())) throw validation("发行币串机构标识不一致");
if (currencyCode == null) currencyCode = required(coin.getCurrency(), "发行币种"); if (currencyCode == null) currencyCode = required(coin.getCurrency(), "发行币种");
if (!currencyCode.equals(coin.getCurrency())) throw validation("同一发行批次币种不一致"); if (!currencyCode.equals(coin.getCurrency())) throw validation("同一发行批次币种不一致");
StandardCurrencyEntity source = standardCurrencyMapper.selectById(coin.getSourceCurrencyId()); StandardCurrencyEntity source = sourceById.get(coin.getSourceCurrencyId());
IssuanceSourceCurrencyUsageEntity usage = sourceUsageMapper.selectBySourceCurrencyIdForUpdate( IssuanceSourceCurrencyUsageEntity usage = usageById.get(coin.getSourceCurrencyId());
coin.getSourceCurrencyId());
if (source == null || !coin.getCoinId().equals(source.getCurrencyId()) if (source == null || !coin.getCoinId().equals(source.getCurrencyId())
|| !coin.getSourceCurrencyBatchId().equals(source.getBatchId()) || !coin.getSourceCurrencyBatchId().equals(source.getBatchId())
|| Boolean.TRUE.equals(source.getDeleted()) || Boolean.TRUE.equals(source.getDeleted())
@ -256,7 +272,7 @@ public class DigitalCurrencyGenerationModuleGateway {
|| !coin.getSourceCompleteCurrency().equals(source.getCompleteCurrency())) { || !coin.getSourceCompleteCurrency().equals(source.getCompleteCurrency())) {
throw validation("生成模块来源币串与发行记录不一致"); throw validation("生成模块来源币串与发行记录不一致");
} }
assertOwnedBatch(source.getBatchId(), subject); if(checkedBatches.add(source.getBatchId())) assertOwnedBatch(source.getBatchId(), subject);
if (coin.getOwnershipSignature() == null || coin.getCompleteCurrency() == null) { if (coin.getOwnershipSignature() == null || coin.getCompleteCurrency() == null) {
throw validation("币串尚未完成央行确权签名"); throw validation("币串尚未完成央行确权签名");
} }
@ -266,33 +282,13 @@ public class DigitalCurrencyGenerationModuleGateway {
transferVaultBalances(IssuanceOwner.of(subject.getUserId(), subject.getSchoolId(), subject.getClassId()), transferVaultBalances(IssuanceOwner.of(subject.getUserId(), subject.getSchoolId(), subject.getClassId()),
requiredBankCode, currencyCode, totalAmount); requiredBankCode, currencyCode, totalAmount);
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
for (int index = 0; index < sources.size(); index++) { if(sourceUsageMapper.markIssued(sourceIds,requestId.toString(),now,actor.getUserId(),actor.getUsername())!=sourceIds.size())
StandardCurrencyEntity source = sources.get(index); throw validation("币串发行状态已变化,不能重复确权");
DraftDigitalCurrency coin = confirmedCoins.get(index); for(int offset=0; offset<confirmedCoins.size(); offset+=200) {
int updated = sourceUsageMapper.update(null, List<DraftDigitalCurrency> chunk=confirmedCoins.subList(offset,Math.min(offset+200,confirmedCoins.size()));
new LambdaUpdateWrapper<IssuanceSourceCurrencyUsageEntity>() if(sourceUsageMapper.insertBankCurrencies(chunk,requestId.toString(),requiredBankCode,now,actor.getUserId(),actor.getUsername())!=chunk.size()
.eq(IssuanceSourceCurrencyUsageEntity::getSourceCurrencyId, source.getId()) || sourceUsageMapper.insertBankOwnership(chunk,requiredBankCode,now)!=chunk.size())
.eq(IssuanceSourceCurrencyUsageEntity::getIssuanceRequestId, requestId.toString()) throw validation("币串入库数量不一致");
.eq(IssuanceSourceCurrencyUsageEntity::getStatus, "RESERVED")
.set(IssuanceSourceCurrencyUsageEntity::getStatus, "ISSUED")
.set(IssuanceSourceCurrencyUsageEntity::getIssuedAt, now)
.set(IssuanceSourceCurrencyUsageEntity::getAuditUserId, actor.getUserId())
.set(IssuanceSourceCurrencyUsageEntity::getAuditUsername, actor.getUsername())
.set(IssuanceSourceCurrencyUsageEntity::getUpdatedAt, now));
if (updated != 1) throw validation("币串发行状态已变化,不能重复确权");
jdbcTemplate.update("INSERT INTO commercial_bank_currency "
+ "(currency_id, source_currency_id, source_batch_id, issuance_request_id, bank_code, "
+ "organization_id, denomination, currency, complete_currency, "
+ "issuance_ownership_original_text,issuance_ownership_signature,status,received_at, "
+ "received_by_user_id, received_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '可用', ?, ?, ?)",
coin.getCoinId(), source.getId(), source.getBatchId(), requestId.toString(), requiredBankCode,
requiredInstitution, source.getDenomination(), currencyCode, coin.getCompleteCurrency(),
coin.getOwnershipOriginalText(), coin.getOwnershipSignature(), now,
actor.getUserId(), actor.getUsername());
jdbcTemplate.update("INSERT INTO central_bank_currency_ownership "
+ "(currency_id,owner_type,owner_id,status,lock_business_type,lock_business_id,last_transaction_id,updated_at) "
+ "VALUES (?,'BANK',?,'AVAILABLE',NULL,NULL,NULL,?)",
coin.getCoinId(), requiredBankCode, now);
} }
} }

@ -58,9 +58,14 @@ public class DigitalCurrencyOwnershipConfirmationService {
required(batch.getControlSystemSignature(), "生产批次控制系统签名"); required(batch.getControlSystemSignature(), "生产批次控制系统签名");
Instant confirmedAt = Instant.now(); Instant confirmedAt = Instant.now();
List<DraftDigitalCurrency> confirmedCoins = new ArrayList<DraftDigitalCurrency>(); List<DraftDigitalCurrency> confirmedCoins = new ArrayList<DraftDigitalCurrency>();
List<String> originals = new ArrayList<>();
for (DraftDigitalCurrency coin : batch.getDraftCoins()) originals.add(ownershipOriginalText(coin));
List<String> signatures = generationGateway.signOwnershipBatch(subject, originals);
if (signatures.size() != originals.size()) throw validation("币串确权签名数量不一致");
int coinIndex = 0;
for (DraftDigitalCurrency coin : batch.getDraftCoins()) { for (DraftDigitalCurrency coin : batch.getDraftCoins()) {
String originalText = ownershipOriginalText(coin); String originalText = originals.get(coinIndex);
String ownershipSignature = generationGateway.signOwnership(subject, originalText); String ownershipSignature = required(signatures.get(coinIndex++), "币串确权签名");
confirmedCoins.add(coin.confirmOwnership(originalText, ownershipSignature, confirmedCoins.add(coin.confirmOwnership(originalText, ownershipSignature,
originalText + "|" + ownershipSignature, confirmedAt, actor.getUserId(), actor.getUsername())); originalText + "|" + ownershipSignature, confirmedAt, actor.getUserId(), actor.getUsername()));
} }
@ -105,13 +110,14 @@ public class DigitalCurrencyOwnershipConfirmationService {
required(confirmation.getCentralBankSignature(), "央行最终确权签名"))) { required(confirmation.getCentralBankSignature(), "央行最终确权签名"))) {
throw validation("央行最终确权签名验证失败"); throw validation("央行最终确权签名验证失败");
} }
List<String> originals = new ArrayList<>();
List<String> signatures = new ArrayList<>();
for (DraftDigitalCurrency coin : batch.getDraftCoins()) { for (DraftDigitalCurrency coin : batch.getDraftCoins()) {
if (!generationGateway.verifyOwnership(subject, originals.add(required(coin.getOwnershipOriginalText(), "币串确权原文"));
required(coin.getOwnershipOriginalText(), "币串确权原文"), signatures.add(required(coin.getOwnershipSignature(), "币串央行确权签名"));
required(coin.getOwnershipSignature(), "币串央行确权签名"))) {
throw validation("币串央行确权签名验证失败:" + coin.getCoinId());
}
} }
if (!generationGateway.verifyOwnershipBatch(subject, originals, signatures))
throw validation("币串央行确权签名验证失败");
DigitalCurrencyOwnershipConfirmation verified = confirmation.verified( DigitalCurrencyOwnershipConfirmation verified = confirmation.verified(
Instant.now(), actor.getUserId(), actor.getUsername()); Instant.now(), actor.getUserId(), actor.getUsername());
productionRepository.confirmOwnership(batch, verified); productionRepository.confirmOwnership(batch, verified);

@ -6,11 +6,44 @@ import com.yau.digitalrmb.issuance.infrastructure.persistence.entity.IssuanceSou
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Update;
import java.time.LocalDateTime;
import com.yau.digitalrmb.issuance.domain.model.DraftDigitalCurrency;
import java.util.List; import java.util.List;
@Mapper @Mapper
public interface IssuanceSourceCurrencyUsageMapper extends BaseMapper<IssuanceSourceCurrencyUsageEntity> { public interface IssuanceSourceCurrencyUsageMapper extends BaseMapper<IssuanceSourceCurrencyUsageEntity> {
@Select({"<script>SELECT * FROM issuance_source_currency_usage WHERE source_currency_id IN",
"<foreach collection='ids' item='id' open='(' separator=',' close=')'>#{id}</foreach>",
"ORDER BY source_currency_id FOR UPDATE</script>"})
List<IssuanceSourceCurrencyUsageEntity> selectUsagesForUpdate(@Param("ids") List<Long> ids);
@Insert({"<script>INSERT INTO issuance_source_currency_usage (id,source_currency_id,source_batch_id,issuance_request_id,status,reserved_at,audit_user_id,audit_username,created_at,updated_at) VALUES",
"<foreach collection='rows' item='r' separator=','>(#{r.id},#{r.sourceCurrencyId},#{r.sourceBatchId},#{r.issuanceRequestId},'RESERVED',#{r.reservedAt},#{r.auditUserId},#{r.auditUsername},#{r.createdAt},#{r.updatedAt})</foreach></script>"})
int insertReservations(@Param("rows") List<IssuanceSourceCurrencyUsageEntity> rows);
@Update({"<script>UPDATE issuance_source_currency_usage SET issuance_request_id=#{requestId},status='RESERVED',reserved_at=#{now},released_at=NULL,issued_at=NULL,audit_user_id=#{userId},audit_username=#{username},updated_at=#{now} WHERE status='RELEASED' AND source_currency_id IN",
"<foreach collection='ids' item='id' open='(' separator=',' close=')'>#{id}</foreach></script>"})
int reserveReleased(@Param("ids") List<Long> ids,@Param("requestId") String requestId,
@Param("now") LocalDateTime now,@Param("userId") String userId,@Param("username") String username);
@Update({"<script>UPDATE issuance_source_currency_usage SET status='ISSUED',issued_at=#{now},audit_user_id=#{userId},audit_username=#{username},updated_at=#{now} WHERE status='RESERVED' AND issuance_request_id=#{requestId} AND source_currency_id IN",
"<foreach collection='ids' item='id' open='(' separator=',' close=')'>#{id}</foreach></script>"})
int markIssued(@Param("ids") List<Long> ids,@Param("requestId") String requestId,
@Param("now") LocalDateTime now,@Param("userId") String userId,@Param("username") String username);
@Insert({"<script>INSERT INTO commercial_bank_currency (currency_id,source_currency_id,source_batch_id,issuance_request_id,bank_code,organization_id,denomination,currency,complete_currency,issuance_ownership_original_text,issuance_ownership_signature,status,received_at,received_by_user_id,received_by) VALUES",
"<foreach collection='coins' item='c' separator=','>(#{c.coinId},#{c.sourceCurrencyId},#{c.sourceCurrencyBatchId},#{requestId},#{bankCode},#{c.organizationId},#{c.denomination},#{c.currency},#{c.completeCurrency},#{c.ownershipOriginalText},#{c.ownershipSignature},'可用',#{now},#{userId},#{username})</foreach></script>"})
int insertBankCurrencies(@Param("coins") List<DraftDigitalCurrency> coins,@Param("requestId") String requestId,
@Param("bankCode") String bankCode,@Param("now") LocalDateTime now,
@Param("userId") String userId,@Param("username") String username);
@Insert({"<script>INSERT INTO central_bank_currency_ownership (currency_id,owner_type,owner_id,status,lock_business_type,lock_business_id,last_transaction_id,updated_at) VALUES",
"<foreach collection='coins' item='c' separator=','>(#{c.coinId},'BANK',#{bankCode},'AVAILABLE',NULL,NULL,NULL,#{now})</foreach></script>"})
int insertBankOwnership(@Param("coins") List<DraftDigitalCurrency> coins,@Param("bankCode") String bankCode,
@Param("now") LocalDateTime now);
@Select("SELECT sc.* FROM standard_currency sc " @Select("SELECT sc.* FROM standard_currency sc "
+ "JOIN issuance_source_currency_usage u ON u.source_currency_id = sc.id " + "JOIN issuance_source_currency_usage u ON u.source_currency_id = sc.id "
+ "WHERE sc.batch_id = #{batchId} AND sc.deleted = FALSE " + "WHERE sc.batch_id = #{batchId} AND sc.deleted = FALSE "

@ -311,28 +311,42 @@ public class WalletPrerequisiteProjectionService {
} }
private void ensureContract(SourceWallet source) { private void ensureContract(SourceWallet source) {
boolean legacyId = source.contract.contractId.matches("CTR_[0-9]{8}_001");
String scopedId = source.contract.contractId + "_" + UUID.nameUUIDFromBytes(
source.walletId.getBytes(StandardCharsets.UTF_8)).toString().replace("-", "");
List<WalletContract> existing = jdbc.query( List<WalletContract> existing = jdbc.query(
"SELECT contract_id,wallet_id,wallet_type FROM wallet_contract WHERE wallet_id=? OR contract_id=?", "SELECT contract_id,wallet_id,wallet_type FROM wallet_contract WHERE wallet_id=?",
(rs, row) -> new WalletContract(rs.getString("contract_id"), (rs, row) -> new WalletContract(rs.getString("contract_id"),
rs.getString("wallet_id"), rs.getString("wallet_type")), rs.getString("wallet_id"), rs.getString("wallet_type")),
source.walletId, source.contract.contractId); source.walletId);
if (!existing.isEmpty()) { if (!existing.isEmpty()) {
if (existing.size() != 1) throw conflict("共享钱包合约标识或钱包归属冲突"); if (existing.size() != 1) throw conflict("共享钱包合约标识或钱包归属冲突");
WalletContract value = existing.get(0); WalletContract value = existing.get(0);
if (!source.walletId.equals(value.walletId) if (!source.walletId.equals(value.walletId)
|| !source.contract.contractId.equals(value.contractId) || !(source.contract.contractId.equals(value.contractId)
|| (legacyId && scopedId.equals(value.contractId)))
|| !source.contract.walletType.equals(value.walletType)) { || !source.contract.walletType.equals(value.walletType)) {
throw conflict("共享钱包合约与模块三结果不一致"); throw conflict("共享钱包合约与模块三结果不一致");
} }
return; return;
} }
// 旧版本给同日所有学生签发同一编号。只为该钱包建立独立运行态主键,
// 保留模块三已签名的合约原文与摘要,不修改占用旧编号的其他钱包。
String runtimeId = source.contract.contractId;
if (jdbc.queryForObject("SELECT COUNT(*) FROM wallet_contract WHERE contract_id=?",
Integer.class, runtimeId) > 0) {
if (!legacyId) throw conflict("共享钱包合约标识或钱包归属冲突");
runtimeId = scopedId;
if (jdbc.queryForObject("SELECT COUNT(*) FROM wallet_contract WHERE contract_id=?",
Integer.class, runtimeId) > 0) throw conflict("共享钱包合约标识或钱包归属冲突");
}
try { try {
jdbc.update("INSERT INTO wallet_contract " + jdbc.update("INSERT INTO wallet_contract " +
"(contract_id,wallet_id,wallet_type,single_payment_limit,daily_payment_limit," + "(contract_id,wallet_id,wallet_type,single_payment_limit,daily_payment_limit," +
"annual_payment_limit,balance_limit,valid_until,original_text,digest,status,daily_used_amount," + "annual_payment_limit,balance_limit,valid_until,original_text,digest,status,daily_used_amount," +
"daily_counter_date,annual_used_amount,annual_counter_year,created_at,updated_at) " + "daily_counter_date,annual_used_amount,annual_counter_year,created_at,updated_at) " +
"VALUES (?,?,?,?,?,?,?,NULL,?,?,'ACTIVE',0,NULL,0,NULL,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)", "VALUES (?,?,?,?,?,?,?,NULL,?,?,'ACTIVE',0,NULL,0,NULL,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",
source.contract.contractId, source.walletId, source.contract.walletType, runtimeId, source.walletId, source.contract.walletType,
source.contract.singleLimit, source.contract.dailyLimit, source.contract.annualLimit, source.contract.singleLimit, source.contract.dailyLimit, source.contract.annualLimit,
source.contract.balanceLimit, source.contract.originalText, source.contract.digest); source.contract.balanceLimit, source.contract.originalText, source.contract.digest);
} catch (DuplicateKeyException exception) { } catch (DuplicateKeyException exception) {

@ -98,7 +98,9 @@ public class SmartContractService {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先生成合约摘要"); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先生成合约摘要");
} }
String date = LocalDateTime.now().format(DATE_FORMAT); String date = LocalDateTime.now().format(DATE_FORMAT);
String contractId = "CTR_" + date + "_001"; // 编号跨学生、跨实训轮次唯一;重复输出保留已签名引用的原编号。
String contractId = c.getContractId() != null ? c.getContractId()
: "CTR_" + date + "_" + java.util.UUID.randomUUID().toString().replace("-", "");
String effectiveTime = c.getContractTimestamp(); String effectiveTime = c.getContractTimestamp();
String json = buildContractJson(contractId, c); String json = buildContractJson(contractId, c);
c.outputContract(contractId, json, effectiveTime); c.outputContract(contractId, json, effectiveTime);

@ -0,0 +1,4 @@
-- 500/930 枚币串的逐枚 SM2 签名汇总会超过 TEXT 的 65535 字节上限。
-- 仅扩容字段,不修改已有业务记录;可重复执行。
ALTER TABLE digital_currency_ownership_confirmation
MODIFY COLUMN confirmation_original_text MEDIUMTEXT NULL;

@ -328,7 +328,7 @@ CREATE TABLE IF NOT EXISTS digital_currency_ownership_confirmation (
confirmed_by_user_id VARCHAR(36) NOT NULL, confirmed_by_user_id VARCHAR(36) NOT NULL,
confirmed_by VARCHAR(64) NOT NULL, confirmed_by VARCHAR(64) NOT NULL,
signing_key_id VARCHAR(64) NOT NULL, signing_key_id VARCHAR(64) NOT NULL,
confirmation_original_text TEXT NULL, confirmation_original_text MEDIUMTEXT NULL,
confirmation_digest CHAR(64) NULL, confirmation_digest CHAR(64) NULL,
central_bank_signature VARCHAR(512) NULL, central_bank_signature VARCHAR(512) NULL,
verified_at TIMESTAMP NULL, verified_at TIMESTAMP NULL,

@ -0,0 +1,73 @@
package com.yau.digitalrmb.corporatewallet.application;
import com.yau.digitalrmb.corporatewallet.domain.DonationSupervision;
import com.yau.digitalrmb.corporatewallet.domain.DonationSupervisionRepository;
import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject;
import com.yau.digitalrmb.shared.exception.BusinessException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class DonationSupervisionCompletionTest {
private static final InstitutionKeySubject SUBJECT = new InstitutionKeySubject("learner-a", 1L, 2L);
@Mock private DonationSupervisionRepository repository;
@Mock private SalaryScoreService scoreService;
@InjectMocks private DonationSupervisionService service;
@Test
void archivedOutputCompletesTheEighthStepAfterSaving() {
DonationSupervision record = signed();
when(repository.findLatest("learner-a", 1L, 2L)).thenReturn(Optional.of(record));
SupervisionOutputResult output = service.output(SUBJECT);
assertThat(output.getStatus()).isEqualTo("已备案");
assertThat(record.getStatus()).isEqualTo(DonationSupervision.Status.OUTPUT);
org.mockito.InOrder order = inOrder(repository, scoreService);
order.verify(repository).update(record);
order.verify(scoreService).markStepCompleted("learner-a", 8);
}
@Test
void replayRepairsLegacyProgressWithoutReplacingTheArchive() {
DonationSupervision record = signed();
record.output("20261009120000", "RECORD_LEGACY", "existing-json");
when(repository.findLatest("learner-a", 1L, 2L)).thenReturn(Optional.of(record));
SupervisionOutputResult output = service.output(SUBJECT);
assertThat(output.getRecordNumber()).isEqualTo("RECORD_LEGACY");
assertThat(output.getApprovalTime()).isEqualTo("20261009120000");
assertThat(record.getOutputJson()).isEqualTo("existing-json");
verify(repository, never()).update(any());
verify(scoreService).markStepCompleted("learner-a", 8);
}
@Test
void unsignedRecordCannotCompleteTheModule() {
DonationSupervision record = DonationSupervision.create("learner-a", 1L, 2L);
when(repository.findLatest("learner-a", 1L, 2L)).thenReturn(Optional.of(record));
assertThatThrownBy(() -> service.output(SUBJECT)).isInstanceOf(BusinessException.class);
verifyNoInteractions(scoreService);
verify(repository, never()).update(any());
}
private DonationSupervision signed() {
DonationSupervision record = DonationSupervision.create("learner-a", 1L, 2L);
record.concatenate("APPROVAL_A", "DONATION_A", "教学监管机构", "SUPERVISE|DONATION_A");
record.computeDigest("SM3", "digest");
record.sign("SM2", "signature");
return record;
}
}

@ -0,0 +1,40 @@
package com.yau.digitalrmb.institutionidentity.application;
import com.yau.digitalrmb.institutionidentity.infrastructure.InstitutionSm2KeyMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@SpringBootTest
@ActiveProfiles("test")
@Transactional
class InstitutionKeyBatchIntegrationTest {
@Autowired InstitutionKeyService keys;
@SpyBean InstitutionSm2KeyMapper keyMapper;
@Test void signsAndVerifiesEveryCoinWithOneSubjectScopedKeyLookup() {
InstitutionKeySubject owner=new InstitutionKeySubject("batch-key-owner",1001,2001);
InstitutionKeySubject other=new InstitutionKeySubject("batch-key-other",1001,2001);
keys.centralBankKey(owner,"tester"); keys.centralBankKey(other,"tester");
List<String> texts=new ArrayList<>();
for(int i=0;i<500;i++) texts.add("COIN_"+i);
clearInvocations(keyMapper);
List<String> signatures=keys.signCentralBankMessages(owner,texts);
assertThat(signatures).hasSize(500).doesNotHaveDuplicates();
verify(keyMapper,times(1)).selectOne(any());
clearInvocations(keyMapper);
assertThat(keys.verifyCentralBankMessages(owner,texts,signatures)).isTrue();
verify(keyMapper,times(1)).selectOne(any());
assertThat(keys.verifyCentralBankMessages(other,texts,signatures)).isFalse();
texts.set(499,"TAMPERED");
assertThat(keys.verifyCentralBankMessages(owner,texts,signatures)).isFalse();
}
}

@ -0,0 +1,70 @@
package com.yau.digitalrmb.institutionidentity.application;
import com.yau.digitalrmb.institutionidentity.infrastructure.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class StandardCurrencyGenerationTest {
@Mock StandardCurrencyBatchMapper batchMapper;
@Mock StandardCurrencyMapper currencyMapper;
@Mock QuotaControlBitMapper quotaControlBitMapper;
@Mock InstitutionTrainingScoreService scoreService;
@InjectMocks StandardCurrencyService service;
@BeforeEach void initializeMappings() {
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
TableInfoHelper.initTableInfo(assistant, StandardCurrencyBatchEntity.class);
TableInfoHelper.initTableInfo(assistant, StandardCurrencyEntity.class);
TableInfoHelper.initTableInfo(assistant, QuotaControlBitEntity.class);
}
private StandardCurrencyBatchEntity batch(String status) {
StandardCurrencyBatchEntity b = new StandardCurrencyBatchEntity();
b.setId(1L); b.setQuotaControlBitId(2L); b.setBatchNumber("20261031_1");
b.setPrefix("DC"); b.setIdRule(StandardCurrencyService.ID_RULE); b.setCurrencyStatus("待生效");
b.setDenominationSummary("100.00:500"); b.setTotalAmount(new BigDecimal("50000"));
b.setTotalCount(500); b.setStatus(status);
when(batchMapper.selectOne(any())).thenReturn(b);
when(batchMapper.lockById(1L)).thenReturn(b);
return b;
}
@Test void writesFiveHundredCoinsInBatchesInsteadOfPerCoin() {
batch("CURRENCY_RULE_CONFIRMED");
QuotaControlBitEntity source = new QuotaControlBitEntity();
source.setId(2L); source.setInstitutionIdentifier("ORG_123456789ABC");
source.setBankSignature("bank"); source.setCentralBankSignatureSegment("central");
when(quotaControlBitMapper.selectOne(any())).thenReturn(source);
when(currencyMapper.selectList(any())).thenReturn(Collections.emptyList());
when(batchMapper.update(isNull(), any())).thenReturn(1);
service.generate(new InstitutionKeySubject("student",1,1), "student");
verify(currencyMapper, never()).insert(any(StandardCurrencyEntity.class));
verify(currencyMapper, times(3)).insertBatch(argThat((List<StandardCurrencyEntity> rows) ->
!rows.isEmpty() && rows.size() <= 200 && rows.stream().allMatch(c -> c.getId()!=null
&& c.getCreatedBy().equals("student") && !c.getDeleted())));
}
@Test void retryPreservesGeneratedCoinIdentifiersAndOwnership() {
batch("GENERATED");
when(currencyMapper.selectList(any())).thenReturn(Collections.emptyList());
service.generate(new InstitutionKeySubject("student",1,1), "student");
verifyNoInteractions(quotaControlBitMapper,scoreService);
verify(currencyMapper, never()).insertBatch(anyList());
verify(currencyMapper, never()).update(isNull(), any());
verify(batchMapper, never()).update(isNull(), any());
}
}

@ -24,9 +24,43 @@ import static org.assertj.core.api.Assertions.assertThat;
@ActiveProfiles("test") @ActiveProfiles("test")
@Transactional @Transactional
class DigitalCurrencyGenerationStockIntegrationTest { class DigitalCurrencyGenerationStockIntegrationTest {
@Autowired private com.yau.digitalrmb.institutionidentity.application.StandardCurrencyService generationService;
@Autowired private DigitalCurrencyGenerationModuleGateway gateway; @Autowired private DigitalCurrencyGenerationModuleGateway gateway;
@Autowired private JdbcTemplate jdbcTemplate; @Autowired private JdbcTemplate jdbcTemplate;
@Test
void generatesFullQuotaInBatchesAndRetryKeepsReservedCoins() {
jdbcTemplate.update("UPDATE quota_control_bit SET status='RECEIVED',bank_signature='BANK_SIG',central_bank_signature_segment='CENTRAL_SIG' WHERE id=81");
jdbcTemplate.update("INSERT INTO standard_currency_batch (id,quota_control_bit_id,batch_number,total_amount,total_count,denomination_summary,prefix,id_rule,currency_status,status,user_id,school_id,class_id,created_at,updated_at,created_by,updated_by,deleted) VALUES (8899,81,'20261031_test',50000,500,'100.00:500','DC','RULE','待生效','RULE_CONFIRMED','stock-user',1001,2001,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,'test','test',FALSE)");
InstitutionKeySubject subject = new InstitutionKeySubject("stock-user",1001,2001);
assertThat(generationService.generate(subject,"tester").getCurrencies()).hasSize(500);
List<Map<String,Object>> before = jdbcTemplate.queryForList("SELECT currency_id,complete_currency FROM standard_currency WHERE batch_id=8899 ORDER BY sequence_number");
jdbcTemplate.update("UPDATE standard_currency SET status='RESERVED' WHERE batch_id=8899 AND sequence_number=1");
assertThat(generationService.generate(subject,"tester").getCurrencies()).hasSize(500);
assertThat(jdbcTemplate.queryForList("SELECT currency_id,complete_currency FROM standard_currency WHERE batch_id=8899 ORDER BY sequence_number")).isEqualTo(before);
assertThat(jdbcTemplate.queryForObject("SELECT status FROM standard_currency WHERE batch_id=8899 AND sequence_number=1",String.class)).isEqualTo("RESERVED");
assertThat(jdbcTemplate.queryForObject("SELECT SUM(denomination) FROM standard_currency WHERE batch_id=8899",BigDecimal.class)).isEqualByComparingTo("50000");
jdbcTemplate.update("UPDATE standard_currency SET status='待生效' WHERE batch_id=8899");
UUID requestId=UUID.randomUUID();
IssuanceAuditActor actor=new IssuanceAuditActor("stock-user","tester");
List<DenominationItem> plan=Arrays.asList(new DenominationItem(new BigDecimal("100"),500));
assertThat(gateway.reserveGeneratedCurrencies(subject,81L,requestId,plan,actor)).hasSize(500);
gateway.releaseGeneratedCurrencies(requestId,actor);
List<GeneratedCurrencyStockItem> reserved=gateway.reserveGeneratedCurrencies(subject,81L,requestId,plan,actor);
assertThat(reserved).hasSize(500);
assertThat(gateway.reserveGeneratedCurrencies(subject,81L,requestId,plan,actor)).hasSize(500);
List<DraftDigitalCurrency> confirmed=new java.util.ArrayList<>();
Instant now=Instant.now();
for(GeneratedCurrencyStockItem coin:reserved) confirmed.add(new DraftDigitalCurrency(coin.getCurrencyId(),"ISSUE_TEST",confirmed.size()+1,
coin.getDenomination(),"ORG_001","DC","AVAILABLE",now,"stock-user","tester",coin.getSourceCurrencyId(),coin.getSourceBatchId(),
coin.getCompleteCurrency(),"CONTROL","SIGNATURE",coin.getCompleteCurrency(),"OWNERSHIP",coin.getCompleteCurrency()+"|OWNERSHIP",now,"stock-user","tester"));
seedAssetsForStockUser();
gateway.activateGeneratedCurrencies(subject,requestId,"BKCHCNBJ00001","ORG_001",confirmed,actor);
assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM commercial_bank_currency WHERE issuance_request_id=?",Integer.class,requestId.toString())).isEqualTo(500);
assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM issuance_source_currency_usage WHERE issuance_request_id=? AND status='ISSUED'",Integer.class,requestId.toString())).isEqualTo(500);
assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM central_bank_currency_ownership WHERE owner_id='BKCHCNBJ00001'",Integer.class)).isEqualTo(500);
}
@org.junit.jupiter.api.BeforeEach @org.junit.jupiter.api.BeforeEach
void seedForeignKeyParentsForRealMySqlSchema() { void seedForeignKeyParentsForRealMySqlSchema() {
for(int i=1;i<=2;i++) { for(int i=1;i<=2;i++) {

@ -96,6 +96,8 @@ class DigitalCurrencyProductionAndOwnershipServiceTest {
when(gateway.digest(org.mockito.ArgumentMatchers.anyString())).thenReturn("BATCH_DIGEST"); when(gateway.digest(org.mockito.ArgumentMatchers.anyString())).thenReturn("BATCH_DIGEST");
when(gateway.signOwnership(org.mockito.ArgumentMatchers.eq(subject), org.mockito.ArgumentMatchers.anyString())) when(gateway.signOwnership(org.mockito.ArgumentMatchers.eq(subject), org.mockito.ArgumentMatchers.anyString()))
.thenReturn("OWNERSHIP_SIGNATURE"); .thenReturn("OWNERSHIP_SIGNATURE");
when(gateway.signOwnershipBatch(org.mockito.ArgumentMatchers.eq(subject), org.mockito.ArgumentMatchers.anyList()))
.thenReturn(Collections.singletonList("OWNERSHIP_SIGNATURE"));
DigitalCurrencyOwnershipConfirmationService service = DigitalCurrencyOwnershipConfirmationService service =
new DigitalCurrencyOwnershipConfirmationService(repository, notificationRepository, gateway); new DigitalCurrencyOwnershipConfirmationService(repository, notificationRepository, gateway);
@ -150,7 +152,7 @@ class DigitalCurrencyProductionAndOwnershipServiceTest {
when(notificationRepository.findByRequestId(requestId)).thenReturn(Optional.of(notification(requestId))); when(notificationRepository.findByRequestId(requestId)).thenReturn(Optional.of(notification(requestId)));
when(gateway.digest(confirmationText)).thenReturn("BATCH_DIGEST"); when(gateway.digest(confirmationText)).thenReturn("BATCH_DIGEST");
when(gateway.verifyOwnership(subject, "BATCH_DIGEST", "CENTRAL_SIGNATURE")).thenReturn(true); when(gateway.verifyOwnership(subject, "BATCH_DIGEST", "CENTRAL_SIGNATURE")).thenReturn(true);
when(gateway.verifyOwnership(subject, "SOURCE_COMPLETE_CURRENCY", "COIN_SIGNATURE")).thenReturn(true); when(gateway.verifyOwnershipBatch(subject, Collections.singletonList("SOURCE_COMPLETE_CURRENCY"), Collections.singletonList("COIN_SIGNATURE"))).thenReturn(true);
when(gateway.digest(org.mockito.ArgumentMatchers.startsWith("OWNERSHIP_RECEIPT|"))) when(gateway.digest(org.mockito.ArgumentMatchers.startsWith("OWNERSHIP_RECEIPT|")))
.thenReturn("RECEIPT_DIGEST"); .thenReturn("RECEIPT_DIGEST");
when(gateway.signReceipt(subject, "RECEIPT_DIGEST")).thenReturn("RECEIPT_SIGNATURE"); when(gateway.signReceipt(subject, "RECEIPT_DIGEST")).thenReturn("RECEIPT_SIGNATURE");

@ -84,6 +84,24 @@ class WalletPrerequisiteProjectionServiceTest {
assertThat(encrypted).isNotEqualTo(keyPair.getPrivateKey()); assertThat(encrypted).isNotEqualTo(keyPair.getPrivateKey());
} }
@Test
@org.springframework.transaction.annotation.Transactional
void legacyDailyContractNumberCollisionKeepsOtherWalletUntouched() {
seedCompleted();
jdbc.update("UPDATE smart_contract_generation SET contract_id='CTR_20261031_001' WHERE user_id=?",SUBJECT_USER);
service.ensureForSubject(subject());
jdbc.update("INSERT INTO digital_wallet (wallet_id,user_id,wallet_type,status,balance,central_bank_confirmation_signature,opened_at,created_at,updated_at) SELECT 'WALLET_LEGACY_COLLISION',? ,wallet_type,status,balance,central_bank_confirmation_signature,opened_at,created_at,updated_at FROM digital_wallet WHERE wallet_id=?",OTHER_USER,WALLET_ID);
jdbc.update("UPDATE wallet_contract SET wallet_id='WALLET_LEGACY_COLLISION',daily_used_amount=45 WHERE contract_id='CTR_20261031_001'");
java.util.List<java.util.Map<String,Object>> before=jdbc.queryForList("SELECT * FROM wallet_contract WHERE wallet_id='WALLET_LEGACY_COLLISION'");
service.ensureForSubject(subject());
String projectedId=jdbc.queryForObject("SELECT contract_id FROM wallet_contract WHERE wallet_id=?",String.class,WALLET_ID);
assertThat(projectedId).startsWith("CTR_20261031_001_");
service.ensureForSubject(subject());
assertThat(jdbc.queryForObject("SELECT contract_id FROM wallet_contract WHERE wallet_id=?",String.class,WALLET_ID)).isEqualTo(projectedId);
assertThat(jdbc.queryForList("SELECT * FROM wallet_contract WHERE wallet_id='WALLET_LEGACY_COLLISION'")).isEqualTo(before);
assertThat(jdbc.queryForObject("SELECT contract_id FROM smart_contract_generation WHERE user_id=? AND deleted=FALSE",String.class,SUBJECT_USER)).isEqualTo("CTR_20261031_001");
}
@Test @Test
void userEnteredCardNumberTakesPrecedenceOverInvalidProfileCardNumber() { void userEnteredCardNumberTakesPrecedenceOverInvalidProfileCardNumber() {
seedCompleted(); seedCompleted();

@ -44,6 +44,24 @@ class SmartContractServiceTest {
@InjectMocks private SmartContractService service; @InjectMocks private SmartContractService service;
@Test
void contractNumbersAreUniqueAcrossLearnersAndStableOnReplay() {
InstitutionKeySubject other=new InstitutionKeySubject("other-step4-user",1001,2001);
SmartContractGeneration first=SmartContractGeneration.create(SUBJECT.getUserId(),1001,2001);
first.fillContractData("WALLET_ONE","二类钱包","50000","100000","500000","500000","长期有效","20261031090000");
first.computeContractDigest("FIRST_DIGEST");
SmartContractGeneration second=SmartContractGeneration.create(other.getUserId(),1001,2001);
second.fillContractData("WALLET_TWO","二类钱包","50000","100000","500000","500000","长期有效","20261031090000");
second.computeContractDigest("SECOND_DIGEST");
when(contractRepository.findLatest(SUBJECT.getUserId(),1001,2001)).thenReturn(Optional.of(first));
when(contractRepository.findLatest(other.getUserId(),1001,2001)).thenReturn(Optional.of(second));
service.outputContract(SUBJECT);
String id=first.getContractId();
service.outputContract(other); service.outputContract(SUBJECT);
assertThat(id).matches("CTR_[0-9]{8}_[0-9a-f]{32}").isNotEqualTo(second.getContractId());
assertThat(first.getContractId()).isEqualTo(id);
}
@Test @Test
void sendMarksContractSentAndActivatesCentralWallet() { void sendMarksContractSentAndActivatesCentralWallet() {
SmartContractGeneration contract = preparedContract(); SmartContractGeneration contract = preparedContract();

Loading…
Cancel
Save