feat:发行货币的功能开发

chore/issuance-comments-zh
jiazheng.zhao 4 months ago
parent cdd915609d
commit 919cb2ddb1

@ -0,0 +1,37 @@
package com.yau.digitalrmb.institutionidentity.application;
import com.yau.digitalrmb.institutionidentity.infrastructure.QuotaControlBitEntity;
import io.swagger.v3.oas.annotations.media.Schema;
@Schema(description = "中央银行接收额度控制位报文查询结果")
public class CentralBankQuotaControlBitResult {
@Schema(description = "确认状态:1-待确认,2-已确认", example = "2")
private final int status;
@Schema(description = "额度控制位编号", example = "QC_20260730_001")
private final String quotaId;
@Schema(description = "静态段")
private final String staticSegment;
@Schema(description = "动态段", example = "DYN_7G8H9I0J_20260730153600")
private final String dynamicSegment;
@Schema(description = "中央银行控制系统签名段")
private final String cbSignatureSegment;
@Schema(description = "商业银行第二私钥签名")
private final String bankSignature;
public CentralBankQuotaControlBitResult(QuotaControlBitEntity value) {
boolean confirmed = value != null && "RECEIVED".equals(value.getStatus());
status = confirmed ? 2 : 1;
quotaId = value == null ? null : value.getQuotaId();
staticSegment = value == null ? null : value.getStaticSegment();
dynamicSegment = value == null ? null : value.getDynamicSegment();
cbSignatureSegment = value == null ? null : value.getCentralBankSignatureSegment();
bankSignature = value == null ? null : value.getBankSignature();
}
public int getStatus() { return status; }
public String getQuotaId() { return quotaId; }
public String getStaticSegment() { return staticSegment; }
public String getDynamicSegment() { return dynamicSegment; }
public String getCbSignatureSegment() { return cbSignatureSegment; }
public String getBankSignature() { return bankSignature; }
}

@ -0,0 +1,17 @@
package com.yau.digitalrmb.institutionidentity.application;
import io.swagger.annotations.ApiModel;
import io.swagger.v3.oas.annotations.media.Schema;
@ApiModel(description = "央行控制系统签名段读取结果")
@Schema(description = "央行控制系统签名段读取结果")
public class CentralBankSignatureSegmentResult {
@Schema(description = "步骤七央行控制系统签名段", example = "CB_CTRL_30450220...")
private final String centralBankSignatureSegment;
public CentralBankSignatureSegmentResult(String centralBankSignatureSegment) {
this.centralBankSignatureSegment = centralBankSignatureSegment;
}
public String getCentralBankSignatureSegment() { return centralBankSignatureSegment; }
}

@ -0,0 +1,38 @@
package com.yau.digitalrmb.institutionidentity.application;
import com.yau.digitalrmb.institutionidentity.infrastructure.ControlSystemSignatureEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import java.math.BigDecimal;
@Schema(description = "商业银行接收控制系统签名报文结果")
public class CommercialBankControlSystemSignatureResult {
@Schema(description = "接收状态:1-未收到,2-已收到", example = "2")
private final int status;
@Schema(description = "控制系统签名编号", example = "CTRL_20260730_001")
private final String ctrlId;
@Schema(description = "交易金额", example = "1589.85")
private final BigDecimal amount;
@Schema(description = "机构标识", example = "ORG_3A4B5C6D7E8F")
private final String orgId;
@Schema(description = "交易信息标识")
private final String txnId;
@Schema(description = "中央银行控制系统SM2签名")
private final String cbCtrlSignature;
public CommercialBankControlSystemSignatureResult(ControlSystemSignatureEntity value) {
this.status = value != null && "SENT".equals(value.getStatus()) ? 2 : 1;
this.ctrlId = value == null ? null : value.getControlId();
this.amount = value == null ? null : value.getAmount();
this.orgId = value == null ? null : value.getInstitutionIdentifier();
this.txnId = value == null ? null : value.getTransactionIdentifier();
this.cbCtrlSignature = value == null ? null : value.getControlSignature();
}
public int getStatus() { return status; }
public String getCtrlId() { return ctrlId; }
public BigDecimal getAmount() { return amount; }
public String getOrgId() { return orgId; }
public String getTxnId() { return txnId; }
public String getCbCtrlSignature() { return cbCtrlSignature; }
}

@ -0,0 +1,17 @@
package com.yau.digitalrmb.institutionidentity.application;
import io.swagger.v3.oas.annotations.media.Schema;
@Schema(description = "步骤七控制系统签名SM3摘要结果")
public class ControlSystemDigestResult {
@Schema(description = "拼接请求原文的SM3摘要")
private final String digest;
public ControlSystemDigestResult(String digest) {
this.digest = digest;
}
public String getDigest() {
return digest;
}
}

@ -29,28 +29,25 @@ public class ControlSystemSignatureService {
@Resource private InstitutionTrainingErrorRecorder errorRecorder; @Resource private InstitutionTrainingErrorRecorder errorRecorder;
@Transactional @Transactional
public ControlSystemSignatureResult digest(String originalText, InstitutionKeySubject subject, String operator) { public ControlSystemDigestResult digest(String originalText, InstitutionKeySubject subject, String operator) {
TransactionInformationIdentifierEntity transaction = requireQuotaVerified(subject); TransactionInformationIdentifierEntity transaction = requireQuotaVerified(subject);
String normalizedOriginalText = validateOriginalText(originalText, transaction); String normalizedOriginalText = validateOriginalText(originalText, transaction, subject);
ControlSystemSignatureEntity current = latest(subject); ControlSystemSignatureEntity current = latest(subject);
if (current != null) { if (current != null) {
if (!current.getTransactionIdentifierId().equals(transaction.getId())) { if (!current.getTransactionIdentifierId().equals(transaction.getId())) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, throw new BusinessException(ErrorCode.VALIDATION_ERROR,
"当前实训已有步骤七控制系统签名记录,如需重新开始请先调用重新实训接口"); "当前实训已有步骤七控制系统签名记录,如需重新开始请先调用重新实训接口");
} }
if ("PREPARED".equals(current.getStatus())) { String digest = cryptography.sm3(normalizedOriginalText);
update(current, "PREPARED", "DIGESTED", operator, update(current, current.getStatus(), "DIGESTED", operator,
new LambdaUpdateWrapper<ControlSystemSignatureEntity>() new LambdaUpdateWrapper<ControlSystemSignatureEntity>()
.set(ControlSystemSignatureEntity::getOriginalText, normalizedOriginalText) .set(ControlSystemSignatureEntity::getOriginalText, normalizedOriginalText)
.set(ControlSystemSignatureEntity::getDigest, .set(ControlSystemSignatureEntity::getDigest, digest)
cryptography.sm3(normalizedOriginalText))); .set(ControlSystemSignatureEntity::getSigningKeyId, null)
return new ControlSystemSignatureResult(requireLatest(subject)); .set(ControlSystemSignatureEntity::getSignature, null)
} .set(ControlSystemSignatureEntity::getControlSignature, null)
if (!normalizedOriginalText.equals(current.getOriginalText())) { .set(ControlSystemSignatureEntity::getResponseMessage, null));
throw new BusinessException(ErrorCode.VALIDATION_ERROR, return new ControlSystemDigestResult(digest);
"步骤七已保存其他拼接请求原文,不能覆盖;如需重新开始请先调用重新实训接口");
}
return new ControlSystemSignatureResult(current);
} }
ControlSystemSignatureEntity value = new ControlSystemSignatureEntity(); ControlSystemSignatureEntity value = new ControlSystemSignatureEntity();
@ -72,35 +69,38 @@ public class ControlSystemSignatureService {
value.setUpdatedBy(operator); value.setUpdatedBy(operator);
value.setDeleted(false); value.setDeleted(false);
mapper.insert(value); mapper.insert(value);
return new ControlSystemSignatureResult(value); return new ControlSystemDigestResult(value.getDigest());
} }
@Transactional @Transactional
public ControlSystemSignatureResult sign(String privateKey, InstitutionKeySubject subject, String operator) { public ControlSystemSignatureResult sign(String privateKey, InstitutionKeySubject subject, String operator) {
ControlSystemSignatureEntity value = requireStatus(subject, "DIGESTED", "请先计算控制系统签名摘要"); ControlSystemSignatureEntity value = requireLatest(subject);
requireResult(value.getDigest(), "请先计算控制系统签名摘要");
String signature = keyService.signCentralBank(subject, privateKey, value.getDigest()); String signature = keyService.signCentralBank(subject, privateKey, value.getDigest());
if (signature == null) { if (signature == null) {
int errorSequence = errorRecorder.recordScoreError(subject.getUserId()); int errorSequence = errorRecorder.recordScoreError(subject.getUserId());
throw new BusinessException(ErrorCode.VALIDATION_ERROR, throw new BusinessException(ErrorCode.VALIDATION_ERROR,
"中央银行第一私钥不正确,本次实训第" + errorSequence + "次错误"); "中央银行第一私钥不正确,本次实训第" + errorSequence + "次错误");
} }
update(value, "DIGESTED", "SIGNED", operator, update(value, value.getStatus(), "SIGNED", operator,
new LambdaUpdateWrapper<ControlSystemSignatureEntity>() new LambdaUpdateWrapper<ControlSystemSignatureEntity>()
.set(ControlSystemSignatureEntity::getSigningKeyId, InstitutionKeyService.CENTRAL_FIRST_KEY) .set(ControlSystemSignatureEntity::getSigningKeyId, InstitutionKeyService.CENTRAL_FIRST_KEY)
.set(ControlSystemSignatureEntity::getSignature, signature) .set(ControlSystemSignatureEntity::getSignature, signature)
.set(ControlSystemSignatureEntity::getControlSignature, signature)); .set(ControlSystemSignatureEntity::getControlSignature, signature)
.set(ControlSystemSignatureEntity::getResponseMessage, null));
return new ControlSystemSignatureResult(requireLatest(subject)); return new ControlSystemSignatureResult(requireLatest(subject));
} }
@Transactional @Transactional
public ControlSystemSignatureResult packageResponse(InstitutionKeySubject subject, String operator) { public ControlSystemSignatureResult packageResponse(InstitutionKeySubject subject, String operator) {
ControlSystemSignatureEntity value = requireStatus(subject, "SIGNED", "请先完成中央银行控制系统签名"); ControlSystemSignatureEntity value = requireLatest(subject);
requireResult(value.getControlSignature(), "请先完成中央银行控制系统签名");
String message = "{\"ctrlId\":\"" + value.getControlId() + "\",\"amount\":\"" String message = "{\"ctrlId\":\"" + value.getControlId() + "\",\"amount\":\""
+ value.getAmount().setScale(2).toPlainString() + "\",\"orgId\":\"" + value.getAmount().setScale(2).toPlainString() + "\",\"orgId\":\""
+ value.getInstitutionIdentifier() + "\",\"txnId\":\"" + value.getInstitutionIdentifier() + "\",\"txnId\":\""
+ value.getTransactionIdentifier() + "\",\"cbCtrlSignature\":\"" + value.getTransactionIdentifier() + "\",\"cbCtrlSignature\":\""
+ value.getControlSignature() + "\"}"; + value.getControlSignature() + "\"}";
update(value, "SIGNED", "PACKAGED", operator, update(value, value.getStatus(), "PACKAGED", operator,
new LambdaUpdateWrapper<ControlSystemSignatureEntity>() new LambdaUpdateWrapper<ControlSystemSignatureEntity>()
.set(ControlSystemSignatureEntity::getResponseMessage, message)); .set(ControlSystemSignatureEntity::getResponseMessage, message));
return new ControlSystemSignatureResult(requireLatest(subject)); return new ControlSystemSignatureResult(requireLatest(subject));
@ -108,37 +108,49 @@ public class ControlSystemSignatureService {
@Transactional @Transactional
public ControlSystemSignatureResult send(InstitutionKeySubject subject, String operator) { public ControlSystemSignatureResult send(InstitutionKeySubject subject, String operator) {
ControlSystemSignatureEntity value = requireStatus(subject, "PACKAGED", "请先打包控制系统签名反馈报文"); ControlSystemSignatureEntity value = requireLatest(subject);
update(value, "PACKAGED", "SENT", operator, new LambdaUpdateWrapper<ControlSystemSignatureEntity>()); requireResult(value.getResponseMessage(), "请先打包控制系统签名反馈报文");
update(value, value.getStatus(), "SENT", operator, new LambdaUpdateWrapper<ControlSystemSignatureEntity>());
scoreService.markStepCompleted(subject.getUserId(), 7); scoreService.markStepCompleted(subject.getUserId(), 7);
return new ControlSystemSignatureResult(requireLatest(subject)); return new ControlSystemSignatureResult(requireLatest(subject));
} }
private String validateOriginalText(String originalText, TransactionInformationIdentifierEntity transaction) { @Transactional(readOnly = true)
public CommercialBankControlSystemSignatureResult commercialBankMessage(InstitutionKeySubject subject) {
return new CommercialBankControlSystemSignatureResult(latest(subject));
}
private String validateOriginalText(String originalText, TransactionInformationIdentifierEntity transaction,
InstitutionKeySubject subject) {
String value = originalText == null ? null : originalText.trim(); String value = originalText == null ? null : originalText.trim();
if (value == null || value.isEmpty()) { if (value == null || value.isEmpty()) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, "拼接请求原文不能为空"); throw dataError(subject, "拼接请求原文不能为空");
} }
String[] parts = value.split("\\|", -1); String[] parts = value.split("\\|", -1);
if (parts.length != 3) { if (parts.length != 3) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, throw dataError(subject, "拼接请求原文格式必须为:金额|机构标识|交易信息标识");
"拼接请求原文格式必须为:金额|机构标识|交易信息标识");
} }
BigDecimal amount; BigDecimal amount;
try { try {
amount = new BigDecimal(parts[0]); amount = new BigDecimal(parts[0]);
} catch (NumberFormatException exception) { } catch (NumberFormatException exception) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, "拼接请求原文中的金额格式不正确"); throw dataError(subject, "拼接请求原文中的金额格式不正确");
} }
if (amount.compareTo(transaction.getAmount()) != 0 if (amount.compareTo(transaction.getAmount()) != 0
|| !transaction.getInstitutionIdentifier().equals(parts[1]) || !transaction.getInstitutionIdentifier().equals(parts[1])
|| !transaction.getTransactionIdentifier().equals(parts[2])) { || !transaction.getTransactionIdentifier().equals(parts[2])) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, throw dataError(subject,
"拼接请求原文中的金额、机构标识或交易信息标识与当前用户前序数据不一致"); "拼接请求原文中的金额、机构标识或交易信息标识与当前用户前序数据不一致");
} }
return value; return value;
} }
private BusinessException dataError(InstitutionKeySubject subject, String message) {
int errorSequence = errorRecorder.recordScoreError(subject.getUserId());
return new BusinessException(ErrorCode.VALIDATION_ERROR,
message + ",本次实训第" + errorSequence + "次错误");
}
private TransactionInformationIdentifierEntity requireQuotaVerified(InstitutionKeySubject subject) { private TransactionInformationIdentifierEntity requireQuotaVerified(InstitutionKeySubject subject) {
TransactionInformationIdentifierEntity value = transactionMapper.selectOne( TransactionInformationIdentifierEntity value = transactionMapper.selectOne(
new LambdaQueryWrapper<TransactionInformationIdentifierEntity>() new LambdaQueryWrapper<TransactionInformationIdentifierEntity>()
@ -152,6 +164,12 @@ public class ControlSystemSignatureService {
return value; return value;
} }
private void requireResult(String value, String message) {
if (value == null || value.trim().isEmpty()) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, message);
}
}
private ControlSystemSignatureEntity requireStatus(InstitutionKeySubject subject, String status, String message) { private ControlSystemSignatureEntity requireStatus(InstitutionKeySubject subject, String status, String message) {
ControlSystemSignatureEntity value = requireLatest(subject); ControlSystemSignatureEntity value = requireLatest(subject);
if (!status.equals(value.getStatus())) { if (!status.equals(value.getStatus())) {

@ -32,7 +32,7 @@ public class CurrencyGenerationRequestService {
private InstitutionTrainingErrorRecorder errorRecorder; private InstitutionTrainingErrorRecorder errorRecorder;
@Transactional @Transactional
public CurrencyRequestResult generateDigest(BigDecimal amount, String deliveryNodeCode, public CurrencyDigestResult generateDigest(BigDecimal amount, String deliveryNodeCode,
String institutionIdentifier, String requestTimestamp, String institutionIdentifier, String requestTimestamp,
InstitutionKeySubject subject, String operator) { InstitutionKeySubject subject, String operator) {
IssuedInstitutionIdentifierResult identifier = identifierQueryService.requireLatestFeedbacked(subject); IssuedInstitutionIdentifierResult identifier = identifierQueryService.requireLatestFeedbacked(subject);
@ -69,7 +69,7 @@ public class CurrencyGenerationRequestService {
repository.update(request, expected, "DIGEST", expected == CurrencyGenerationRequest.Status.DIGESTED repository.update(request, expected, "DIGEST", expected == CurrencyGenerationRequest.Status.DIGESTED
? "修改当前货币生成请求并重新计算SM3摘要" ? "修改当前货币生成请求并重新计算SM3摘要"
: "初始化请求后使用SM3计算并保存请求摘要", operator); : "初始化请求后使用SM3计算并保存请求摘要", operator);
return new CurrencyRequestResult(request); return new CurrencyDigestResult(digest);
} }
@Transactional @Transactional

@ -5,45 +5,16 @@ import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
@ApiModel(description = "接口返回数据") @ApiModel(description = "机构标识申请SM3摘要结果")
@Schema(description = "接口返回数据") @Schema(description = "机构标识申请SM3摘要结果")
public class InstitutionDigestResult { public class InstitutionDigestResult {
@Schema(description = "机构标识申请编号")
private final long applicationId;
@Schema(description = "当前业务状态")
private final String status;
@Schema(description = "密码算法名称")
private final String algorithm;
@Schema(description = "参与摘要计算的完整拼接原文")
private final String concatenatedText;
@Schema(description = "SM3摘要值") @Schema(description = "SM3摘要值")
private final String digest; private final String digest;
public InstitutionDigestResult(long applicationId, String status, String algorithm, String concatenatedText, public InstitutionDigestResult(String digest) {
String digest) {
this.applicationId = applicationId;
this.status = status;
this.algorithm = algorithm;
this.concatenatedText = concatenatedText;
this.digest = digest; this.digest = digest;
} }
public long getApplicationId() {
return applicationId;
}
public String getStatus() {
return status;
}
public String getAlgorithm() {
return algorithm;
}
public String getConcatenatedText() {
return concatenatedText;
}
public String getDigest() { public String getDigest() {
return digest; return digest;
} }

@ -81,8 +81,7 @@ public class InstitutionIdentifierStepService {
? "修改当前最新一轮申请原文并重新计算SM3摘要" ? "修改当前最新一轮申请原文并重新计算SM3摘要"
: "创建本轮记录并使用SM3计算业务摘要", : "创建本轮记录并使用SM3计算业务摘要",
operator); operator);
return new InstitutionDigestResult(application.getId(), application.getStatus().name(), "SM3", return new InstitutionDigestResult(digest);
normalizedOriginalText, digest);
} }
@Transactional @Transactional

@ -13,13 +13,16 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.math.BigDecimal; import java.security.SecureRandom;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
@Service @Service
public class QuotaControlBitService { public class QuotaControlBitService {
private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyyMMdd"); private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyyMMdd");
private static final DateTimeFormatter TIMESTAMP = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
private static final char[] RANDOM_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
private static final SecureRandom RANDOM = new SecureRandom();
@Resource private ControlSystemSignatureMapper controlSignatureMapper; @Resource private ControlSystemSignatureMapper controlSignatureMapper;
@Resource private QuotaControlBitMapper mapper; @Resource private QuotaControlBitMapper mapper;
@ -29,21 +32,35 @@ public class QuotaControlBitService {
@Resource private InstitutionTrainingScoreService scoreService; @Resource private InstitutionTrainingScoreService scoreService;
@Transactional @Transactional
public QuotaControlBitResult staticSegment(BigDecimal amount, String institutionIdentifier, public QuotaControlStaticSegmentResult staticSegment(InstitutionKeySubject subject, String operator) {
String transactionIdentifier, InstitutionKeySubject subject,
String operator) {
ControlSystemSignatureEntity source = requireStepSeven(subject); ControlSystemSignatureEntity source = requireStepSeven(subject);
validateSourceInput(source, amount, institutionIdentifier, transactionIdentifier, subject);
QuotaControlBitEntity current = latest(subject); QuotaControlBitEntity current = latest(subject);
if (current != null) { if (current != null) {
if (!current.getControlSignatureId().equals(source.getId())) { if (!current.getControlSignatureId().equals(source.getId())) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, throw new BusinessException(ErrorCode.VALIDATION_ERROR,
"当前实训已有步骤八记录,如需重新开始请先调用重新实训接口"); "当前实训已有步骤八记录,如需重新开始请先调用重新实训接口");
} }
if (!"STATIC_READY".equals(current.getStatus())) { String originalText = source.getAmount().setScale(2).toPlainString() + "|"
throw new BusinessException(ErrorCode.VALIDATION_ERROR, "静态段已提交,不能重复修改后续流程数据"); + source.getInstitutionIdentifier() + "|" + source.getTransactionIdentifier();
} String segment = "STATIC_" + cryptography.sm3(originalText);
return new QuotaControlBitResult(current); update(current, current.getStatus(), "STATIC_READY", operator,
new LambdaUpdateWrapper<QuotaControlBitEntity>()
.set(QuotaControlBitEntity::getAmount, source.getAmount().setScale(2))
.set(QuotaControlBitEntity::getInstitutionIdentifier, source.getInstitutionIdentifier())
.set(QuotaControlBitEntity::getTransactionIdentifier, source.getTransactionIdentifier())
.set(QuotaControlBitEntity::getStaticOriginalText, originalText)
.set(QuotaControlBitEntity::getStaticSegment, segment)
.set(QuotaControlBitEntity::getRandomValue, null)
.set(QuotaControlBitEntity::getSegmentTimestamp, null)
.set(QuotaControlBitEntity::getDynamicSegment, null)
.set(QuotaControlBitEntity::getCentralBankSignatureSegment, null)
.set(QuotaControlBitEntity::getCompleteControlBit, null)
.set(QuotaControlBitEntity::getSigningKeyId, null)
.set(QuotaControlBitEntity::getHashAlgorithm, null)
.set(QuotaControlBitEntity::getBankSignature, null)
.set(QuotaControlBitEntity::getRequestMessage, null)
.set(QuotaControlBitEntity::getReceiveStatus, 1));
return new QuotaControlStaticSegmentResult(segment);
} }
QuotaControlBitEntity value = new QuotaControlBitEntity(); QuotaControlBitEntity value = new QuotaControlBitEntity();
value.setControlSignatureId(source.getId()); value.setControlSignatureId(source.getId());
@ -60,110 +77,164 @@ public class QuotaControlBitService {
value.setCreatedAt(LocalDateTime.now()); value.setUpdatedAt(value.getCreatedAt()); value.setCreatedAt(LocalDateTime.now()); value.setUpdatedAt(value.getCreatedAt());
value.setCreatedBy(operator); value.setUpdatedBy(operator); value.setDeleted(false); value.setCreatedBy(operator); value.setUpdatedBy(operator); value.setDeleted(false);
mapper.insert(value); mapper.insert(value);
return new QuotaControlBitResult(value); return new QuotaControlStaticSegmentResult(value.getStaticSegment());
} }
@Transactional @Transactional
public QuotaControlBitResult dynamicSegment(String randomValue, String timestamp, public QuotaControlDynamicSegmentResult dynamicSegment(InstitutionKeySubject subject, String operator) {
InstitutionKeySubject subject, String operator) { QuotaControlBitEntity value = requireLatest(subject);
QuotaControlBitEntity value = requireStatus(subject, "STATIC_READY", "请先生成静态段"); if (value.getStaticSegment() == null) {
update(value, "STATIC_READY", "DYNAMIC_READY", operator, throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先生成静态段");
}
String randomValue = randomValue();
String timestamp = LocalDateTime.now().format(TIMESTAMP);
String segment = "DYN_" + randomValue + "_" + timestamp;
update(value, value.getStatus(), "DYNAMIC_READY", operator,
new LambdaUpdateWrapper<QuotaControlBitEntity>() new LambdaUpdateWrapper<QuotaControlBitEntity>()
.set(QuotaControlBitEntity::getRandomValue, randomValue.toUpperCase()) .set(QuotaControlBitEntity::getRandomValue, randomValue)
.set(QuotaControlBitEntity::getSegmentTimestamp, timestamp) .set(QuotaControlBitEntity::getSegmentTimestamp, timestamp)
.set(QuotaControlBitEntity::getDynamicSegment, .set(QuotaControlBitEntity::getDynamicSegment, segment)
"DYN_" + randomValue.toUpperCase() + "_" + timestamp)); .set(QuotaControlBitEntity::getCentralBankSignatureSegment, null)
return new QuotaControlBitResult(requireLatest(subject)); .set(QuotaControlBitEntity::getCompleteControlBit, null)
.set(QuotaControlBitEntity::getSigningKeyId, null)
.set(QuotaControlBitEntity::getHashAlgorithm, null)
.set(QuotaControlBitEntity::getBankSignature, null)
.set(QuotaControlBitEntity::getRequestMessage, null)
.set(QuotaControlBitEntity::getReceiveStatus, 1));
return new QuotaControlDynamicSegmentResult(segment);
} }
@Transactional @Transactional
public QuotaControlBitResult readCentralBankSignature(InstitutionKeySubject subject, String operator) { public CentralBankSignatureSegmentResult readCentralBankSignature(InstitutionKeySubject subject, String operator) {
QuotaControlBitEntity value = requireStatus(subject, "DYNAMIC_READY", "请先生成动态段"); QuotaControlBitEntity value = requireLatest(subject);
requireResult(value.getDynamicSegment(), "请先生成动态段");
ControlSystemSignatureEntity source = requireStepSeven(subject); ControlSystemSignatureEntity source = requireStepSeven(subject);
if (!source.getId().equals(value.getControlSignatureId()) || source.getControlSignature() == null) { if (!source.getId().equals(value.getControlSignatureId()) || source.getControlSignature() == null) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, "步骤七央行控制系统签名数据不完整"); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "步骤七央行控制系统签名数据不完整");
} }
update(value, "DYNAMIC_READY", "CB_SIGNATURE_READY", operator, update(value, value.getStatus(), "CB_SIGNATURE_READY", operator,
new LambdaUpdateWrapper<QuotaControlBitEntity>().set( new LambdaUpdateWrapper<QuotaControlBitEntity>()
QuotaControlBitEntity::getCentralBankSignatureSegment, .set(QuotaControlBitEntity::getCentralBankSignatureSegment,
"CB_CTRL_" + source.getControlSignature())); "CB_CTRL_" + source.getControlSignature())
return new QuotaControlBitResult(requireLatest(subject)); .set(QuotaControlBitEntity::getCompleteControlBit, null)
.set(QuotaControlBitEntity::getSigningKeyId, null)
.set(QuotaControlBitEntity::getHashAlgorithm, null)
.set(QuotaControlBitEntity::getBankSignature, null)
.set(QuotaControlBitEntity::getRequestMessage, null)
.set(QuotaControlBitEntity::getReceiveStatus, 1));
return new CentralBankSignatureSegmentResult(
requireLatest(subject).getCentralBankSignatureSegment());
} }
@Transactional @Transactional
public QuotaControlBitResult assemble(InstitutionKeySubject subject, String operator) { public QuotaControlBitResult assemble(InstitutionKeySubject subject, String operator) {
QuotaControlBitEntity value = requireStatus(subject, "CB_SIGNATURE_READY", "请先读取央行签名段"); QuotaControlBitEntity value = requireLatest(subject);
requireResult(value.getStaticSegment(), "请先生成静态段");
requireResult(value.getDynamicSegment(), "请先生成动态段");
requireResult(value.getCentralBankSignatureSegment(), "请先读取央行签名段");
String complete = value.getStaticSegment() + "|" + value.getDynamicSegment() + "|" String complete = value.getStaticSegment() + "|" + value.getDynamicSegment() + "|"
+ value.getCentralBankSignatureSegment(); + value.getCentralBankSignatureSegment();
update(value, "CB_SIGNATURE_READY", "ASSEMBLED", operator, update(value, value.getStatus(), "ASSEMBLED", operator,
new LambdaUpdateWrapper<QuotaControlBitEntity>().set( new LambdaUpdateWrapper<QuotaControlBitEntity>()
QuotaControlBitEntity::getCompleteControlBit, complete)); .set(QuotaControlBitEntity::getCompleteControlBit, complete)
.set(QuotaControlBitEntity::getSigningKeyId, null)
.set(QuotaControlBitEntity::getHashAlgorithm, null)
.set(QuotaControlBitEntity::getBankSignature, null)
.set(QuotaControlBitEntity::getRequestMessage, null)
.set(QuotaControlBitEntity::getReceiveStatus, 1));
return new QuotaControlBitResult(requireLatest(subject)); return new QuotaControlBitResult(requireLatest(subject));
} }
@Transactional @Transactional
public QuotaControlBitResult sign(String privateKey, String algorithm, InstitutionKeySubject subject, public QuotaControlBitResult sign(String privateKey, String completeControlBit, String algorithm,
String operator) { InstitutionKeySubject subject, String operator) {
QuotaControlBitEntity value = requireStatus(subject, "ASSEMBLED", "请先拼接完整额度控制位"); QuotaControlBitEntity value = requireLatest(subject);
requireResult(value.getCompleteControlBit(), "请先拼接完整额度控制位");
String submittedControlBit = completeControlBit == null ? null : completeControlBit.trim();
if (!value.getCompleteControlBit().equals(submittedControlBit)) {
throw keyError(subject, "完整额度控制位与步骤八拼接结果不一致");
}
if (!"SM2".equalsIgnoreCase(algorithm == null ? "" : algorithm.trim())) { if (!"SM2".equalsIgnoreCase(algorithm == null ? "" : algorithm.trim())) {
throw keyError(subject, "签名算法必须选择SM2"); throw keyError(subject, "签名算法必须选择SM2");
} }
String signature = keyService.signCommercialBank(subject, privateKey, value.getCompleteControlBit()); String signature = keyService.signCommercialBank(subject, privateKey, submittedControlBit);
if (signature == null) { if (signature == null) {
throw keyError(subject, "签名必须使用当前实训主体的商业银行第二私钥"); throw keyError(subject, "签名必须使用当前实训主体的商业银行第二私钥");
} }
update(value, "ASSEMBLED", "SIGNED", operator, update(value, value.getStatus(), "SIGNED", operator,
new LambdaUpdateWrapper<QuotaControlBitEntity>() new LambdaUpdateWrapper<QuotaControlBitEntity>()
.set(QuotaControlBitEntity::getSigningKeyId, InstitutionKeyService.BANK_SECOND_KEY) .set(QuotaControlBitEntity::getSigningKeyId, InstitutionKeyService.BANK_SECOND_KEY)
.set(QuotaControlBitEntity::getHashAlgorithm, "SM2") .set(QuotaControlBitEntity::getHashAlgorithm, "SM2")
.set(QuotaControlBitEntity::getBankSignature, signature)); .set(QuotaControlBitEntity::getBankSignature, signature)
.set(QuotaControlBitEntity::getRequestMessage, null)
.set(QuotaControlBitEntity::getReceiveStatus, 1));
return new QuotaControlBitResult(requireLatest(subject)); return new QuotaControlBitResult(requireLatest(subject));
} }
@Transactional @Transactional
public QuotaControlBitResult packageRequest(InstitutionKeySubject subject, String operator) { public QuotaControlBitResult packageRequest(InstitutionKeySubject subject, String operator) {
QuotaControlBitEntity value = requireStatus(subject, "SIGNED", "请先完成商业银行签名确认"); QuotaControlBitEntity value = requireLatest(subject);
requireResult(value.getBankSignature(), "请先完成商业银行签名确认");
String message = "{\"quotaId\":\"" + value.getQuotaId() + "\",\"staticSegment\":\"" String message = "{\"quotaId\":\"" + value.getQuotaId() + "\",\"staticSegment\":\""
+ value.getStaticSegment() + "\",\"dynamicSegment\":\"" + value.getDynamicSegment() + value.getStaticSegment() + "\",\"dynamicSegment\":\"" + value.getDynamicSegment()
+ "\",\"cbSignatureSegment\":\"" + value.getCentralBankSignatureSegment() + "\",\"cbSignatureSegment\":\"" + value.getCentralBankSignatureSegment()
+ "\",\"bankSignature\":\"" + value.getBankSignature() + "\"}"; + "\",\"bankSignature\":\"" + value.getBankSignature() + "\"}";
update(value, "SIGNED", "PACKAGED", operator, update(value, value.getStatus(), "PACKAGED", operator,
new LambdaUpdateWrapper<QuotaControlBitEntity>().set(QuotaControlBitEntity::getRequestMessage, message)); new LambdaUpdateWrapper<QuotaControlBitEntity>()
.set(QuotaControlBitEntity::getRequestMessage, message)
.set(QuotaControlBitEntity::getReceiveStatus, 1));
return new QuotaControlBitResult(requireLatest(subject)); return new QuotaControlBitResult(requireLatest(subject));
} }
@Transactional @Transactional
public QuotaControlBitResult send(InstitutionKeySubject subject, String operator) { public QuotaControlBitResult send(InstitutionKeySubject subject, String operator) {
QuotaControlBitEntity value = requireStatus(subject, "PACKAGED", "请先打包额度控制位数据包报文"); QuotaControlBitEntity value = requireLatest(subject);
update(value, "PACKAGED", "SENT", operator, new LambdaUpdateWrapper<QuotaControlBitEntity>()); requireResult(value.getRequestMessage(), "请先打包额度控制位数据包报文");
return new QuotaControlBitResult(requireLatest(subject)); update(value, value.getStatus(), "RECEIVED", operator,
}
@Transactional
public QuotaControlBitResult receive(InstitutionKeySubject subject, String operator) {
QuotaControlBitEntity value = requireStatus(subject, "SENT", "商业银行尚未发送额度控制位数据包报文");
update(value, "SENT", "RECEIVED", operator,
new LambdaUpdateWrapper<QuotaControlBitEntity>().set(QuotaControlBitEntity::getReceiveStatus, 2)); new LambdaUpdateWrapper<QuotaControlBitEntity>().set(QuotaControlBitEntity::getReceiveStatus, 2));
scoreService.markStepCompleted(subject.getUserId(), 8); scoreService.markStepCompleted(subject.getUserId(), 8);
return new QuotaControlBitResult(requireLatest(subject)); return new QuotaControlBitResult(requireLatest(subject));
} }
@Transactional(readOnly = true)
public CentralBankQuotaControlBitResult centralBankMessage(InstitutionKeySubject subject) {
return new CentralBankQuotaControlBitResult(latest(subject));
}
@Transactional(readOnly = true)
public QuotaControlStaticSegmentResult queryStaticSegment(InstitutionKeySubject subject) {
String staticSegment = requireLatest(subject).getStaticSegment();
if (staticSegment == null) {
throw new BusinessException(ErrorCode.RESOURCE_NOT_FOUND, "当前尚未生成步骤八静态段");
}
return new QuotaControlStaticSegmentResult(staticSegment);
}
@Transactional(readOnly = true)
public QuotaControlDynamicSegmentResult queryDynamicSegment(InstitutionKeySubject subject) {
String dynamicSegment = requireLatest(subject).getDynamicSegment();
if (dynamicSegment == null) {
throw new BusinessException(ErrorCode.RESOURCE_NOT_FOUND, "当前尚未生成步骤八动态段");
}
return new QuotaControlDynamicSegmentResult(dynamicSegment);
}
@Transactional(readOnly = true) @Transactional(readOnly = true)
public QuotaControlBitResult detail(InstitutionKeySubject subject) { public QuotaControlBitResult detail(InstitutionKeySubject subject) {
return new QuotaControlBitResult(requireLatest(subject)); return new QuotaControlBitResult(requireLatest(subject));
} }
private void validateSourceInput(ControlSystemSignatureEntity source, BigDecimal amount, private String randomValue() {
String institutionIdentifier, String transactionIdentifier, StringBuilder value = new StringBuilder(8);
InstitutionKeySubject subject) { for (int index = 0; index < 8; index++) {
if (amount == null || source.getAmount().compareTo(amount) != 0) { value.append(RANDOM_CHARS[RANDOM.nextInt(RANDOM_CHARS.length)]);
throw keyError(subject, "用户输入的货币金额与前序步骤数据不一致");
} }
if (!source.getInstitutionIdentifier().equals(institutionIdentifier)) { return value.toString();
throw keyError(subject, "用户输入的机构标识与前序步骤数据不一致");
} }
if (!source.getTransactionIdentifier().equals(transactionIdentifier)) {
throw keyError(subject, "用户输入的交易信息标识与前序步骤数据不一致"); private void requireResult(String value, String message) {
if (value == null || value.trim().isEmpty()) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, message);
} }
} }

@ -0,0 +1,17 @@
package com.yau.digitalrmb.institutionidentity.application;
import io.swagger.v3.oas.annotations.media.Schema;
@Schema(description = "步骤八动态段生成结果")
public class QuotaControlDynamicSegmentResult {
@Schema(description = "由后端随机数和当前时间戳生成的动态段", example = "DYN_7G8H9I0J_20260730153600")
private final String dynamicSegment;
public QuotaControlDynamicSegmentResult(String dynamicSegment) {
this.dynamicSegment = dynamicSegment;
}
public String getDynamicSegment() {
return dynamicSegment;
}
}

@ -0,0 +1,17 @@
package com.yau.digitalrmb.institutionidentity.application;
import io.swagger.v3.oas.annotations.media.Schema;
@Schema(description = "步骤八静态段生成结果")
public class QuotaControlStaticSegmentResult {
@Schema(description = "由后端前序金额、机构标识和交易信息标识计算的SM3静态段")
private final String staticSegment;
public QuotaControlStaticSegmentResult(String staticSegment) {
this.staticSegment = staticSegment;
}
public String getStaticSegment() {
return staticSegment;
}
}

@ -0,0 +1,17 @@
package com.yau.digitalrmb.institutionidentity.application;
import io.swagger.v3.oas.annotations.media.Schema;
@Schema(description = "签名结果")
public class SignatureResult {
@Schema(description = "生成的签名值")
private final String signature;
public SignatureResult(String signature) {
this.signature = signature;
}
public String getSignature() {
return signature;
}
}

@ -49,14 +49,35 @@ public class StandardCurrencyService {
throw inputError(subject, "用户输入的货币总额与步骤八额度控制位金额不一致"); throw inputError(subject, "用户输入的货币总额与步骤八额度控制位金额不一致");
} }
StandardCurrencyBatchEntity current = latest(subject); StandardCurrencyBatchEntity current = latest(subject);
List<DenominationBreakdownResult> breakdown = decomposeAmount(source.getAmount());
if (current != null) { if (current != null) {
if (!current.getQuotaControlBitId().equals(source.getId())) { if (!current.getQuotaControlBitId().equals(source.getId())) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, throw new BusinessException(ErrorCode.VALIDATION_ERROR,
"当前实训已有步骤九记录,如需重新开始请先调用重新实训接口"); "当前实训已有步骤九记录,如需重新开始请先调用重新实训接口");
} }
return result(current); currencyMapper.update(null, new LambdaUpdateWrapper<StandardCurrencyEntity>()
.eq(StandardCurrencyEntity::getBatchId, current.getId())
.eq(StandardCurrencyEntity::getDeleted, false)
.set(StandardCurrencyEntity::getDeleted, true)
.set(StandardCurrencyEntity::getUpdatedAt, LocalDateTime.now())
.set(StandardCurrencyEntity::getUpdatedBy, operator));
int updated = batchMapper.update(null, new LambdaUpdateWrapper<StandardCurrencyBatchEntity>()
.eq(StandardCurrencyBatchEntity::getId, current.getId())
.eq(StandardCurrencyBatchEntity::getDeleted, false)
.set(StandardCurrencyBatchEntity::getTotalAmount,
source.getAmount().setScale(2, RoundingMode.UNNECESSARY))
.set(StandardCurrencyBatchEntity::getTotalCount,
breakdown.stream().mapToInt(DenominationBreakdownResult::getCount).sum())
.set(StandardCurrencyBatchEntity::getDenominationSummary, encode(breakdown))
.set(StandardCurrencyBatchEntity::getPrefix, null)
.set(StandardCurrencyBatchEntity::getIdRule, null)
.set(StandardCurrencyBatchEntity::getCurrencyStatus, null)
.set(StandardCurrencyBatchEntity::getStatus, "DECOMPOSED")
.set(StandardCurrencyBatchEntity::getUpdatedAt, LocalDateTime.now())
.set(StandardCurrencyBatchEntity::getUpdatedBy, operator));
if (updated != 1) throw stateChanged();
return result(requireLatest(subject));
} }
List<DenominationBreakdownResult> breakdown = decomposeAmount(source.getAmount());
StandardCurrencyBatchEntity batch = new StandardCurrencyBatchEntity(); StandardCurrencyBatchEntity batch = new StandardCurrencyBatchEntity();
batch.setQuotaControlBitId(source.getId()); batch.setQuotaControlBitId(source.getId());
batch.setBatchNumber(LocalDateTime.now().format(DATE) + "_" batch.setBatchNumber(LocalDateTime.now().format(DATE) + "_"
@ -80,7 +101,10 @@ public class StandardCurrencyService {
@Transactional @Transactional
public StandardCurrencyBatchResult confirmRule(String prefix, String idRule, String currencyStatus, public StandardCurrencyBatchResult confirmRule(String prefix, String idRule, String currencyStatus,
InstitutionKeySubject subject, String operator) { InstitutionKeySubject subject, String operator) {
StandardCurrencyBatchEntity batch = requireStatus(subject, "DECOMPOSED", "请先执行面额拆解"); StandardCurrencyBatchEntity batch = requireLatest(subject);
if (batch.getDenominationSummary() == null || batch.getTotalAmount() == null) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先执行面额拆解");
}
if (!"DC".equals(prefix == null ? null : prefix.trim().toUpperCase())) { if (!"DC".equals(prefix == null ? null : prefix.trim().toUpperCase())) {
throw inputError(subject, "币串前缀必须为DC"); throw inputError(subject, "币串前缀必须为DC");
} }
@ -92,7 +116,7 @@ public class StandardCurrencyService {
} }
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())
.eq(StandardCurrencyBatchEntity::getStatus, "DECOMPOSED") .eq(StandardCurrencyBatchEntity::getStatus, batch.getStatus())
.eq(StandardCurrencyBatchEntity::getDeleted, false) .eq(StandardCurrencyBatchEntity::getDeleted, false)
.set(StandardCurrencyBatchEntity::getPrefix, "DC") .set(StandardCurrencyBatchEntity::getPrefix, "DC")
.set(StandardCurrencyBatchEntity::getIdRule, ID_RULE) .set(StandardCurrencyBatchEntity::getIdRule, ID_RULE)
@ -106,13 +130,21 @@ public class StandardCurrencyService {
@Transactional @Transactional
public StandardCurrencyBatchResult generate(InstitutionKeySubject subject, String operator) { public StandardCurrencyBatchResult generate(InstitutionKeySubject subject, String operator) {
StandardCurrencyBatchEntity batch = requireStatus(subject, "RULE_CONFIRMED", "请先确认币串生成规则"); StandardCurrencyBatchEntity batch = requireLatest(subject);
if (batch.getPrefix() == null || batch.getIdRule() == null || batch.getCurrencyStatus() == null) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先确认币串生成规则");
}
QuotaControlBitEntity source = requireStepEight(subject); QuotaControlBitEntity source = requireStepEight(subject);
if (!source.getId().equals(batch.getQuotaControlBitId()) || source.getBankSignature() == null if (!source.getId().equals(batch.getQuotaControlBitId()) || source.getBankSignature() == null
|| source.getCentralBankSignatureSegment() == null) { || source.getCentralBankSignatureSegment() == null) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, "步骤八额度控制位签名数据不完整"); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "步骤八额度控制位签名数据不完整");
} }
List<BigDecimal> values = expand(decode(batch.getDenominationSummary())); List<BigDecimal> values = expand(decode(batch.getDenominationSummary()));
List<StandardCurrencyEntity> existing = currencyMapper.selectList(
new LambdaQueryWrapper<StandardCurrencyEntity>()
.eq(StandardCurrencyEntity::getBatchId, batch.getId())
.eq(StandardCurrencyEntity::getDeleted, false)
.orderByAsc(StandardCurrencyEntity::getSequenceNumber));
SecureRandom random = new SecureRandom(); SecureRandom random = new SecureRandom();
for (int i = 0; i < values.size(); i++) { for (int i = 0; i < values.size(); i++) {
int sequence = i + 1; int sequence = i + 1;
@ -120,6 +152,27 @@ public class StandardCurrencyService {
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);
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.setBatchId(batch.getId()); currency.setBatchId(batch.getId());
currency.setSequenceNumber(sequence); currency.setSequenceNumber(sequence);
@ -139,9 +192,10 @@ public class StandardCurrencyService {
currency.setDeleted(false); currency.setDeleted(false);
currencyMapper.insert(currency); currencyMapper.insert(currency);
} }
}
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())
.eq(StandardCurrencyBatchEntity::getStatus, "RULE_CONFIRMED") .eq(StandardCurrencyBatchEntity::getStatus, batch.getStatus())
.eq(StandardCurrencyBatchEntity::getDeleted, false) .eq(StandardCurrencyBatchEntity::getDeleted, false)
.set(StandardCurrencyBatchEntity::getStatus, "GENERATED") .set(StandardCurrencyBatchEntity::getStatus, "GENERATED")
.set(StandardCurrencyBatchEntity::getUpdatedAt, LocalDateTime.now()) .set(StandardCurrencyBatchEntity::getUpdatedAt, LocalDateTime.now())

@ -211,24 +211,10 @@ public class TransactionInformationIdentifierService {
TransactionInformationIdentifier.Status.QUOTA_PACKAGED, "请先打包步骤五额度请求报文"); TransactionInformationIdentifier.Status.QUOTA_PACKAGED, "请先打包步骤五额度请求报文");
TransactionInformationIdentifier.Status expected = value.getStatus(); TransactionInformationIdentifier.Status expected = value.getStatus();
invoke(value::sendQuotaRequest); invoke(value::sendQuotaRequest);
repository.update(value, expected, "QUOTA_SEND", "商业银行发送额度请求至央行", operator);
return new QuotaRequestMessageResult(value);
}
@Transactional
public CentralBankQuotaRequestResult receiveQuotaRequest(InstitutionKeySubject subject, String operator) {
TransactionInformationIdentifier value = requireLatest(subject);
if (value.getStatus().ordinal() >= TransactionInformationIdentifier.Status.QUOTA_RECEIVED.ordinal()) {
return new CentralBankQuotaRequestResult(value);
}
if (value.getStatus() != TransactionInformationIdentifier.Status.QUOTA_SENT) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, "商业银行尚未发送步骤五额度请求报文");
}
TransactionInformationIdentifier.Status expected = value.getStatus();
invoke(value::receiveQuotaRequest); invoke(value::receiveQuotaRequest);
repository.update(value, expected, "QUOTA_RECEIVE", "央行成功接收额度请求报文", operator); repository.update(value, expected, "QUOTA_SEND", "商业银行发送额度请求至央行,发送成功即视为央行已收到", operator);
scoreService.markStepCompleted(subject.getUserId(), 5); scoreService.markStepCompleted(subject.getUserId(), 5);
return new CentralBankQuotaRequestResult(value); return new QuotaRequestMessageResult(value);
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
@ -247,9 +233,12 @@ public class TransactionInformationIdentifierService {
@Transactional(readOnly = true) @Transactional(readOnly = true)
public QuotaVerificationOriginalTextResult quotaVerificationOriginalText(InstitutionKeySubject subject) { public QuotaVerificationOriginalTextResult quotaVerificationOriginalText(InstitutionKeySubject subject) {
TransactionInformationIdentifier value = requireStatus(subject, TransactionInformationIdentifier value = requireLatest(subject);
TransactionInformationIdentifier.Status.QUOTA_RECEIVED, if (value.getStatus().ordinal() < TransactionInformationIdentifier.Status.QUOTA_RECEIVED.ordinal()
|| value.getQuotaRequestMessage() == null) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR,
"步骤五额度请求尚未发送并由央行接收,不能进入步骤六"); "步骤五额度请求尚未发送并由央行接收,不能进入步骤六");
}
return new QuotaVerificationOriginalTextResult(value.getQuotaOriginalText()); return new QuotaVerificationOriginalTextResult(value.getQuotaOriginalText());
} }
@ -298,9 +287,11 @@ public class TransactionInformationIdentifierService {
@Transactional @Transactional
public QuotaVerificationComparisonResult compareQuotaDigests(InstitutionKeySubject subject, String operator) { public QuotaVerificationComparisonResult compareQuotaDigests(InstitutionKeySubject subject, String operator) {
TransactionInformationIdentifier value = requireStatus(subject, TransactionInformationIdentifier value = requireLatest(subject);
TransactionInformationIdentifier.Status.QUOTA_H2_RECOVERED, if (value.getQuotaRecomputedDigest() == null || value.getQuotaSignatureDigest() == null) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR,
"请先使用商业银行第二公钥验签获取H2"); "请先使用商业银行第二公钥验签获取H2");
}
TransactionInformationIdentifier.Status expected = value.getStatus(); TransactionInformationIdentifier.Status expected = value.getStatus();
invoke(value::compareQuotaDigests); invoke(value::compareQuotaDigests);
repository.update(value, expected, "QUOTA_COMPARE", repository.update(value, expected, "QUOTA_COMPARE",

@ -154,7 +154,9 @@ public class TransactionInformationIdentifier {
} }
public void assemble() { public void assemble() {
requireStatus(Status.DIGESTED, "请先使用SM3生成摘要"); if (digest == null || !digest.matches("[0-9A-F]{64}")) {
throw new IllegalStateException("请先使用SM3生成摘要");
}
this.transactionIdentifier = "TXN_" + digest; this.transactionIdentifier = "TXN_" + digest;
this.status = Status.ASSEMBLED; this.status = Status.ASSEMBLED;
} }
@ -217,7 +219,9 @@ public class TransactionInformationIdentifier {
} }
public void packageQuotaRequest(String message) { public void packageQuotaRequest(String message) {
requireStatus(Status.QUOTA_SIGNED, "请先使用商业银行第二私钥完成额度请求签名"); if (quotaSignature == null || quotaSignature.trim().isEmpty()) {
throw new IllegalStateException("请先使用商业银行第二私钥完成额度请求签名");
}
if (message == null || message.trim().isEmpty()) { if (message == null || message.trim().isEmpty()) {
throw new IllegalArgumentException("额度请求报文不能为空"); throw new IllegalArgumentException("额度请求报文不能为空");
} }
@ -226,12 +230,16 @@ public class TransactionInformationIdentifier {
} }
public void sendQuotaRequest() { public void sendQuotaRequest() {
requireStatus(Status.QUOTA_PACKAGED, "请先打包额度请求报文"); if (quotaRequestMessage == null || quotaRequestMessage.trim().isEmpty()) {
throw new IllegalStateException("请先打包额度请求报文");
}
this.status = Status.QUOTA_SENT; this.status = Status.QUOTA_SENT;
} }
public void receiveQuotaRequest() { public void receiveQuotaRequest() {
requireStatus(Status.QUOTA_SENT, "央行只能接收已发送的额度请求"); if (quotaRequestMessage == null || quotaRequestMessage.trim().isEmpty()) {
throw new IllegalStateException("央行只能接收已发送的额度请求");
}
this.status = Status.QUOTA_RECEIVED; this.status = Status.QUOTA_RECEIVED;
} }
@ -266,7 +274,9 @@ public class TransactionInformationIdentifier {
} }
public void compareQuotaDigests() { public void compareQuotaDigests() {
requireStatus(Status.QUOTA_H2_RECOVERED, "请先使用商业银行第二公钥验签获取H2"); if (quotaRecomputedDigest == null || quotaSignatureDigest == null) {
throw new IllegalStateException("请先使用商业银行第二公钥验签获取H2");
}
this.quotaDigestMatches = quotaRecomputedDigest != null this.quotaDigestMatches = quotaRecomputedDigest != null
&& quotaRecomputedDigest.equalsIgnoreCase(quotaSignatureDigest); && quotaRecomputedDigest.equalsIgnoreCase(quotaSignatureDigest);
if (!Boolean.TRUE.equals(quotaSignatureValid) || !this.quotaDigestMatches) { if (!Boolean.TRUE.equals(quotaSignatureValid) || !this.quotaDigestMatches) {

@ -8,11 +8,17 @@ import javax.validation.constraints.NotBlank;
public class QuotaControlSignRequest { public class QuotaControlSignRequest {
@NotBlank(message = "商业银行第二私钥不能为空") @NotBlank(message = "商业银行第二私钥不能为空")
private String privateKey; private String privateKey;
@NotBlank(message = "完整额度控制位不能为空")
@Schema(description = "前端拼接得到的完整额度控制位,格式为静态段|动态段|央行控制系统签名段",
example = "STATIC_7AD7D47A81F0230562F912AC5CFA6F44D5A851C978191F4DAB8241CF1BFD7971|DYN_YMUL9SQ0_20260807141518|CB_CTRL_30450220ABCDEF")
private String completeControlBit;
@NotBlank(message = "签名算法不能为空") @NotBlank(message = "签名算法不能为空")
@Schema(description = "必须为SM2", example = "SM2") @Schema(description = "必须为SM2", example = "SM2")
private String hashAlgorithm; private String hashAlgorithm;
public String getPrivateKey() { return privateKey; } public String getPrivateKey() { return privateKey; }
public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; }
public String getCompleteControlBit() { return completeControlBit; }
public void setCompleteControlBit(String completeControlBit) { this.completeControlBit = completeControlBit; }
public String getHashAlgorithm() { return hashAlgorithm; } public String getHashAlgorithm() { return hashAlgorithm; }
public void setHashAlgorithm(String hashAlgorithm) { this.hashAlgorithm = hashAlgorithm; } public void setHashAlgorithm(String hashAlgorithm) { this.hashAlgorithm = hashAlgorithm; }
} }

@ -11,6 +11,7 @@ import com.yau.digitalrmb.institutionidentity.application.InstitutionKeyPairResu
import com.yau.digitalrmb.institutionidentity.application.InstitutionKeyService; import com.yau.digitalrmb.institutionidentity.application.InstitutionKeyService;
import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject; import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject;
import com.yau.digitalrmb.institutionidentity.application.InstitutionVerificationProcessResult; import com.yau.digitalrmb.institutionidentity.application.InstitutionVerificationProcessResult;
import com.yau.digitalrmb.institutionidentity.application.SignatureResult;
import com.yau.digitalrmb.institutionidentity.interfaces.dto.ConfirmInstitutionIdentifierRequest; import com.yau.digitalrmb.institutionidentity.interfaces.dto.ConfirmInstitutionIdentifierRequest;
import com.yau.digitalrmb.institutionidentity.interfaces.dto.VerifyInstitutionApplicationRequest; import com.yau.digitalrmb.institutionidentity.interfaces.dto.VerifyInstitutionApplicationRequest;
import com.yau.digitalrmb.security.context.AuthContextHolder; import com.yau.digitalrmb.security.context.AuthContextHolder;
@ -81,11 +82,13 @@ public class CentralBankInstitutionIdentifierController {
@PostMapping("/applications/confirmation") @PostMapping("/applications/confirmation")
@Operation(summary = "央行签名确权并组装机构标识", @Operation(summary = "央行签名确权并组装机构标识",
description = "仅VERIFIED状态可操作;privateKey可选,传入时校验央行第一私钥。") description = "仅VERIFIED状态可操作;privateKey可选,传入时校验央行第一私钥。")
public ApiResponse<InstitutionIdentifierConfirmationResult> confirmIdentifier( public ApiResponse<SignatureResult> confirmIdentifier(
@Valid @RequestBody(required = false) ConfirmInstitutionIdentifierRequest request) { @Valid @RequestBody(required = false) ConfirmInstitutionIdentifierRequest request) {
JwtUser jwtUser = AuthContextHolder.get(); JwtUser jwtUser = AuthContextHolder.get();
return ApiResponse.success(verificationService.confirm(request == null ? null : request.getPrivateKey(), InstitutionIdentifierConfirmationResult result = verificationService.confirm(
InstitutionKeySubject.from(jwtUser), jwtUser.getUsername()), traceId()); request == null ? null : request.getPrivateKey(),
InstitutionKeySubject.from(jwtUser), jwtUser.getUsername());
return ApiResponse.success(new SignatureResult(result.getCentralBankSignature()), traceId());
} }
@GetMapping("/applications/final-identifier") @GetMapping("/applications/final-identifier")

@ -1,10 +1,9 @@
package com.yau.digitalrmb.institutionidentity.interfaces.rest; package com.yau.digitalrmb.institutionidentity.interfaces.rest;
import com.yau.digitalrmb.institutionidentity.application.CentralBankQuotaControlBitResult;
import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject; import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject;
import com.yau.digitalrmb.institutionidentity.application.QuotaControlBitResult;
import com.yau.digitalrmb.institutionidentity.application.QuotaControlBitService; import com.yau.digitalrmb.institutionidentity.application.QuotaControlBitService;
import com.yau.digitalrmb.security.context.AuthContextHolder; import com.yau.digitalrmb.security.context.AuthContextHolder;
import com.yau.digitalrmb.security.context.JwtUser;
import com.yau.digitalrmb.shared.api.ApiResponse; import com.yau.digitalrmb.shared.api.ApiResponse;
import com.yau.digitalrmb.shared.web.TraceIdFilter; import com.yau.digitalrmb.shared.web.TraceIdFilter;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
@ -20,17 +19,12 @@ import javax.annotation.Resource;
public class CentralBankQuotaControlBitController { public class CentralBankQuotaControlBitController {
@Resource private QuotaControlBitService service; @Resource private QuotaControlBitService service;
@PostMapping("/steps/receive")
@Operation(summary = "中央银行接收额度控制位数据包报文", description = "接收后receiveStatus由1变为2。")
public ApiResponse<QuotaControlBitResult> receive() {
JwtUser user = AuthContextHolder.get();
return ApiResponse.success(service.receive(InstitutionKeySubject.from(user), user.getUsername()), traceId());
}
@GetMapping @GetMapping
@Operation(summary = "查询央行接收状态和报文", description = "receiveStatus:1未收到,2已收到。") @Operation(summary = "查询中央银行接收额度控制位报文信息",
public ApiResponse<QuotaControlBitResult> detail() { description = "只读查询,不推进流程。商业银行未发送时status=1(待确认);发送成功后status=2(已确认),并返回额度控制位编号、静态段、动态段、央行签名段和商业银行签名。")
return ApiResponse.success(service.detail(InstitutionKeySubject.from(AuthContextHolder.get())), traceId()); public ApiResponse<CentralBankQuotaControlBitResult> detail() {
return ApiResponse.success(service.centralBankMessage(
InstitutionKeySubject.from(AuthContextHolder.get())), traceId());
} }
private String traceId() { return MDC.get(TraceIdFilter.MDC_KEY); } private String traceId() { return MDC.get(TraceIdFilter.MDC_KEY); }

@ -4,14 +4,12 @@ import com.yau.digitalrmb.institutionidentity.application.CentralBankQuotaReques
import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject; import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject;
import com.yau.digitalrmb.institutionidentity.application.TransactionInformationIdentifierService; import com.yau.digitalrmb.institutionidentity.application.TransactionInformationIdentifierService;
import com.yau.digitalrmb.security.context.AuthContextHolder; import com.yau.digitalrmb.security.context.AuthContextHolder;
import com.yau.digitalrmb.security.context.JwtUser;
import com.yau.digitalrmb.shared.api.ApiResponse; import com.yau.digitalrmb.shared.api.ApiResponse;
import com.yau.digitalrmb.shared.web.TraceIdFilter; import com.yau.digitalrmb.shared.web.TraceIdFilter;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.MDC; import org.slf4j.MDC;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@ -24,18 +22,9 @@ public class CentralBankQuotaRequestController {
@Resource @Resource
private TransactionInformationIdentifierService service; private TransactionInformationIdentifierService service;
@PostMapping("/steps/receive")
@Operation(summary = "中央银行接收额度请求报文",
description = "只接收商业银行已发送的报文,状态由QUOTA_SENT推进为QUOTA_RECEIVED。")
public ApiResponse<CentralBankQuotaRequestResult> receive() {
JwtUser user = AuthContextHolder.get();
return ApiResponse.success(service.receiveQuotaRequest(
InstitutionKeySubject.from(user), user.getUsername()), traceId());
}
@GetMapping @GetMapping
@Operation(summary = "查询中央银行接收状态和额度请求信息", @Operation(summary = "查询中央银行接收状态和额度请求信息",
description = "仅返回六项额度请求报文字段和status;status=1表示待确认,status=2表示已确认。") description = "央行端仅保留本接口。仅返回六项额度请求报文字段和status;商业银行未发送时status=1,发送后status=2。")
public ApiResponse<CentralBankQuotaRequestResult> detail() { public ApiResponse<CentralBankQuotaRequestResult> detail() {
return ApiResponse.success(service.centralBankQuotaRequest( return ApiResponse.success(service.centralBankQuotaRequest(
InstitutionKeySubject.from(AuthContextHolder.get())), traceId()); InstitutionKeySubject.from(AuthContextHolder.get())), traceId());

@ -0,0 +1,35 @@
package com.yau.digitalrmb.institutionidentity.interfaces.rest;
import com.yau.digitalrmb.institutionidentity.application.CommercialBankControlSystemSignatureResult;
import com.yau.digitalrmb.institutionidentity.application.ControlSystemSignatureService;
import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject;
import com.yau.digitalrmb.security.context.AuthContextHolder;
import com.yau.digitalrmb.shared.api.ApiResponse;
import com.yau.digitalrmb.shared.web.TraceIdFilter;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.MDC;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@RequestMapping("/api/v1/institution-identifiers/commercial-bank/control-system-signatures")
@Tag(name = "步骤七:商业银行接收控制系统签名报文")
public class CommercialBankControlSystemSignatureController {
@Resource private ControlSystemSignatureService service;
@GetMapping
@Operation(summary = "查询商业银行接收控制系统签名报文信息",
description = "只读查询,不推进流程。中央银行未发送时status=1;发送成功后status=2,并返回控制编号、金额、机构标识、交易信息标识和控制系统签名。")
public ApiResponse<CommercialBankControlSystemSignatureResult> detail() {
return ApiResponse.success(service.commercialBankMessage(
InstitutionKeySubject.from(AuthContextHolder.get())), traceId());
}
private String traceId() {
return MDC.get(TraceIdFilter.MDC_KEY);
}
}

@ -1,8 +1,10 @@
package com.yau.digitalrmb.institutionidentity.interfaces.rest; package com.yau.digitalrmb.institutionidentity.interfaces.rest;
import com.yau.digitalrmb.institutionidentity.application.ControlSystemDigestResult;
import com.yau.digitalrmb.institutionidentity.application.ControlSystemSignatureResult; import com.yau.digitalrmb.institutionidentity.application.ControlSystemSignatureResult;
import com.yau.digitalrmb.institutionidentity.application.ControlSystemSignatureService; import com.yau.digitalrmb.institutionidentity.application.ControlSystemSignatureService;
import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject; import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject;
import com.yau.digitalrmb.institutionidentity.application.SignatureResult;
import com.yau.digitalrmb.institutionidentity.interfaces.dto.ControlSystemDigestRequest; import com.yau.digitalrmb.institutionidentity.interfaces.dto.ControlSystemDigestRequest;
import com.yau.digitalrmb.institutionidentity.interfaces.dto.ControlSystemSignRequest; import com.yau.digitalrmb.institutionidentity.interfaces.dto.ControlSystemSignRequest;
import com.yau.digitalrmb.security.context.AuthContextHolder; import com.yau.digitalrmb.security.context.AuthContextHolder;
@ -29,16 +31,21 @@ public class ControlSystemSignatureController {
@PostMapping("/steps/digest") @PostMapping("/steps/digest")
@Operation(summary = "对拼接请求原文进行SM3哈希运算", @Operation(summary = "对拼接请求原文进行SM3哈希运算",
description = "前端提交页面输入框完整原文,格式为金额|机构标识|交易信息标识。后端按当前JWT主体校验三项前序数据,生成控制编号并对输入原文原样计算SM3摘要。") description = "前端提交页面输入框完整原文,格式为金额|机构标识|交易信息标识。后端按当前JWT主体校验三项前序数据,生成控制编号并对输入原文原样计算SM3摘要。")
public ApiResponse<ControlSystemSignatureResult> digest( public ApiResponse<ControlSystemDigestResult> digest(
@Valid @RequestBody ControlSystemDigestRequest request) { @Valid @RequestBody ControlSystemDigestRequest request) {
return execute((subject, operator) -> service.digest(request.getOriginalText(), subject, operator)); JwtUser user = AuthContextHolder.get();
return ApiResponse.success(service.digest(request.getOriginalText(), InstitutionKeySubject.from(user),
user.getUsername()), traceId());
} }
@PostMapping("/steps/sign") @PostMapping("/steps/sign")
@Operation(summary = "使用中央银行第一私钥生成签名") @Operation(summary = "使用中央银行第一私钥生成签名")
public ApiResponse<ControlSystemSignatureResult> sign( public ApiResponse<SignatureResult> sign(
@Valid @RequestBody ControlSystemSignRequest request) { @Valid @RequestBody ControlSystemSignRequest request) {
return execute((subject, operator) -> service.sign(request.getPrivateKey(), subject, operator)); JwtUser user = AuthContextHolder.get();
ControlSystemSignatureResult result = service.sign(request.getPrivateKey(),
InstitutionKeySubject.from(user), user.getUsername());
return ApiResponse.success(new SignatureResult(result.getSignature()), traceId());
} }
@PostMapping("/steps/package") @PostMapping("/steps/package")

@ -1,8 +1,10 @@
package com.yau.digitalrmb.institutionidentity.interfaces.rest; package com.yau.digitalrmb.institutionidentity.interfaces.rest;
import com.yau.digitalrmb.institutionidentity.application.CurrencyDigestResult;
import com.yau.digitalrmb.institutionidentity.application.CurrencyGenerationRequestService; import com.yau.digitalrmb.institutionidentity.application.CurrencyGenerationRequestService;
import com.yau.digitalrmb.institutionidentity.application.CurrencyRequestResult; import com.yau.digitalrmb.institutionidentity.application.CurrencyRequestResult;
import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject; import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject;
import com.yau.digitalrmb.institutionidentity.application.SignatureResult;
import com.yau.digitalrmb.institutionidentity.interfaces.dto.CurrencyRequestStepRequest; import com.yau.digitalrmb.institutionidentity.interfaces.dto.CurrencyRequestStepRequest;
import com.yau.digitalrmb.institutionidentity.interfaces.dto.GenerateCurrencyDigestRequest; import com.yau.digitalrmb.institutionidentity.interfaces.dto.GenerateCurrencyDigestRequest;
import com.yau.digitalrmb.security.context.AuthContextHolder; import com.yau.digitalrmb.security.context.AuthContextHolder;
@ -31,7 +33,7 @@ public class CurrencyGenerationRequestController {
@PostMapping("/steps/digest") @PostMapping("/steps/digest")
@Operation(summary = "生成请求SM3摘要", @Operation(summary = "生成请求SM3摘要",
description = "步骤二首个操作。前端提交金额、投放节点、步骤一反馈的ORG机构标识和页面当前时间戳;后端校验机构标识归属,按机构标识|金额|投放节点|时间戳拼接原文并全部持久化。同一ORG重复提交时更新同一条记录。") description = "步骤二首个操作。前端提交金额、投放节点、步骤一反馈的ORG机构标识和页面当前时间戳;后端校验机构标识归属,按机构标识|金额|投放节点|时间戳拼接原文并全部持久化。同一ORG重复提交时更新同一条记录。")
public ApiResponse<CurrencyRequestResult> digest( public ApiResponse<CurrencyDigestResult> digest(
@Valid @RequestBody GenerateCurrencyDigestRequest request) { @Valid @RequestBody GenerateCurrencyDigestRequest request) {
JwtUser jwtUser = AuthContextHolder.get(); JwtUser jwtUser = AuthContextHolder.get();
return ApiResponse.success(currencyRequestService.generateDigest(request.getAmount(), return ApiResponse.success(currencyRequestService.generateDigest(request.getAmount(),
@ -41,11 +43,12 @@ public class CurrencyGenerationRequestController {
@PostMapping("/steps/sign") @PostMapping("/steps/sign")
@Operation(summary = "使用商业银行第二私钥进行SM2签名") @Operation(summary = "使用商业银行第二私钥进行SM2签名")
public ApiResponse<CurrencyRequestResult> sign( public ApiResponse<SignatureResult> sign(
@Valid @RequestBody CurrencyRequestStepRequest request) { @Valid @RequestBody CurrencyRequestStepRequest request) {
JwtUser jwtUser = AuthContextHolder.get(); JwtUser jwtUser = AuthContextHolder.get();
return ApiResponse.success(currencyRequestService.sign(request.getPrivateKey(), CurrencyRequestResult result = currencyRequestService.sign(request.getPrivateKey(),
InstitutionKeySubject.from(jwtUser), jwtUser.getUsername()), traceId()); InstitutionKeySubject.from(jwtUser), jwtUser.getUsername());
return ApiResponse.success(new SignatureResult(result.getBankSignature()), traceId());
} }
@PostMapping("/steps/package") @PostMapping("/steps/package")

@ -7,6 +7,7 @@ import com.yau.digitalrmb.institutionidentity.application.CurrencyGenerationVeri
import com.yau.digitalrmb.institutionidentity.application.CurrencyQuotaVerificationResult; import com.yau.digitalrmb.institutionidentity.application.CurrencyQuotaVerificationResult;
import com.yau.digitalrmb.institutionidentity.application.CurrencyGenerationVerificationService; import com.yau.digitalrmb.institutionidentity.application.CurrencyGenerationVerificationService;
import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject; import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject;
import com.yau.digitalrmb.institutionidentity.application.SignatureResult;
import com.yau.digitalrmb.institutionidentity.interfaces.dto.CalculateCurrencyDigestRequest; import com.yau.digitalrmb.institutionidentity.interfaces.dto.CalculateCurrencyDigestRequest;
import com.yau.digitalrmb.institutionidentity.interfaces.dto.ConfirmCurrencyRequest; import com.yau.digitalrmb.institutionidentity.interfaces.dto.ConfirmCurrencyRequest;
import com.yau.digitalrmb.institutionidentity.interfaces.dto.CurrencyVerificationStepRequest; import com.yau.digitalrmb.institutionidentity.interfaces.dto.CurrencyVerificationStepRequest;
@ -81,13 +82,14 @@ public class CurrencyGenerationVerificationController {
@PostMapping("/steps/confirm") @PostMapping("/steps/confirm")
@Operation(summary = "央行第一私钥签名确权", @Operation(summary = "央行第一私钥签名确权",
description = "对应页面“签名确权”按钮。用户输入请求摘要和央行第一私钥;后端校验摘要与步骤二请求摘要一致后,使用该私钥对输入摘要执行SM2签名。只生成央行签名和确权时间,不打包报文。") description = "对应页面“签名确权”按钮。用户输入请求摘要和央行第一私钥;后端校验摘要与步骤二请求摘要一致后,使用该私钥对输入摘要执行SM2签名。只生成央行签名和确权时间,不打包报文。")
public ApiResponse<CurrencyConfirmationSignatureResult> confirm( public ApiResponse<SignatureResult> confirm(
@Valid @RequestBody ConfirmCurrencyRequest request) { @Valid @RequestBody ConfirmCurrencyRequest request) {
JwtUser user = AuthContextHolder.get(); JwtUser user = AuthContextHolder.get();
CurrencyConfirmationSignatureResult result = service.confirm(request.getVerificationId(), CurrencyConfirmationSignatureResult result = service.confirm(request.getVerificationId(),
request.getRequestDigest(), request.getPrivateKey(), InstitutionKeySubject.from(user), request.getRequestDigest(), request.getPrivateKey(), InstitutionKeySubject.from(user),
user.getUsername()); user.getUsername());
return ApiResponse.success(result, MDC.get(TraceIdFilter.MDC_KEY)); return ApiResponse.success(new SignatureResult(result.getCentralBankSignature()),
MDC.get(TraceIdFilter.MDC_KEY));
} }
@PostMapping("/steps/package-response") @PostMapping("/steps/package-response")

@ -11,6 +11,7 @@ import com.yau.digitalrmb.institutionidentity.application.InstitutionKeyPairResu
import com.yau.digitalrmb.institutionidentity.application.InstitutionKeyService; import com.yau.digitalrmb.institutionidentity.application.InstitutionKeyService;
import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject; import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject;
import com.yau.digitalrmb.institutionidentity.application.InstitutionSignatureResult; import com.yau.digitalrmb.institutionidentity.application.InstitutionSignatureResult;
import com.yau.digitalrmb.institutionidentity.application.SignatureResult;
import com.yau.digitalrmb.institutionidentity.application.InstitutionTrainingResetResult; import com.yau.digitalrmb.institutionidentity.application.InstitutionTrainingResetResult;
import com.yau.digitalrmb.institutionidentity.application.InstitutionTrainingResetService; import com.yau.digitalrmb.institutionidentity.application.InstitutionTrainingResetService;
import com.yau.digitalrmb.institutionidentity.interfaces.dto.GenerateInstitutionIdentifierRequest; import com.yau.digitalrmb.institutionidentity.interfaces.dto.GenerateInstitutionIdentifierRequest;
@ -84,11 +85,12 @@ public class InstitutionIdentifierController {
@PostMapping("/steps/sign") @PostMapping("/steps/sign")
@Operation(summary = "使用商业银行第二私钥进行SM2签名", @Operation(summary = "使用商业银行第二私钥进行SM2签名",
description = "仅DIGESTED状态可操作,完成后保存签名并进入SIGNED状态。") description = "仅DIGESTED状态可操作,完成后保存签名并进入SIGNED状态。")
public ApiResponse<InstitutionSignatureResult> sign( public ApiResponse<SignatureResult> sign(
@Valid @RequestBody InstitutionIdentifierStepRequest request) { @Valid @RequestBody InstitutionIdentifierStepRequest request) {
JwtUser jwtUser = AuthContextHolder.get(); JwtUser jwtUser = AuthContextHolder.get();
return ApiResponse.success(stepService.sign(request.getPrivateKey(), InstitutionSignatureResult result = stepService.sign(request.getPrivateKey(),
InstitutionKeySubject.from(jwtUser), jwtUser.getUsername()), traceId()); InstitutionKeySubject.from(jwtUser), jwtUser.getUsername());
return ApiResponse.success(new SignatureResult(result.getSignature()), traceId());
} }
@PostMapping("/steps/package") @PostMapping("/steps/package")

@ -1,11 +1,13 @@
package com.yau.digitalrmb.institutionidentity.interfaces.rest; package com.yau.digitalrmb.institutionidentity.interfaces.rest;
import com.yau.digitalrmb.institutionidentity.application.CentralBankSignatureSegmentResult;
import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject; import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject;
import com.yau.digitalrmb.institutionidentity.application.QuotaControlBitResult; import com.yau.digitalrmb.institutionidentity.application.QuotaControlBitResult;
import com.yau.digitalrmb.institutionidentity.application.QuotaControlBitService; import com.yau.digitalrmb.institutionidentity.application.QuotaControlBitService;
import com.yau.digitalrmb.institutionidentity.interfaces.dto.QuotaControlDynamicRequest; import com.yau.digitalrmb.institutionidentity.application.QuotaControlDynamicSegmentResult;
import com.yau.digitalrmb.institutionidentity.application.QuotaControlStaticSegmentResult;
import com.yau.digitalrmb.institutionidentity.application.SignatureResult;
import com.yau.digitalrmb.institutionidentity.interfaces.dto.QuotaControlSignRequest; import com.yau.digitalrmb.institutionidentity.interfaces.dto.QuotaControlSignRequest;
import com.yau.digitalrmb.institutionidentity.interfaces.dto.QuotaControlStaticRequest;
import com.yau.digitalrmb.security.context.AuthContextHolder; import com.yau.digitalrmb.security.context.AuthContextHolder;
import com.yau.digitalrmb.security.context.JwtUser; import com.yau.digitalrmb.security.context.JwtUser;
import com.yau.digitalrmb.shared.api.ApiResponse; import com.yau.digitalrmb.shared.api.ApiResponse;
@ -25,22 +27,46 @@ public class QuotaControlBitController {
@Resource private QuotaControlBitService service; @Resource private QuotaControlBitService service;
@PostMapping("/steps/static-segment") @PostMapping("/steps/static-segment")
@Operation(summary = "生成静态段", description = "用户输入金额、机构标识和交易信息标识;后端与步骤七数据逐项校验后计算SM3静态段。") @Operation(summary = "生成静态段",
public ApiResponse<QuotaControlBitResult> staticSegment(@Valid @RequestBody QuotaControlStaticRequest request) { description = "无需请求体。后端按当前JWT主体读取步骤七金额、机构标识和交易信息标识,计算SM3并仅返回staticSegment。")
return execute((s, o) -> service.staticSegment(request.getAmount(), request.getInstitutionIdentifier(), public ApiResponse<QuotaControlStaticSegmentResult> staticSegment() {
request.getTransactionIdentifier(), s, o)); JwtUser user = AuthContextHolder.get();
return ApiResponse.success(service.staticSegment(
InstitutionKeySubject.from(user), user.getUsername()), traceId());
} }
@PostMapping("/steps/dynamic-segment") @PostMapping("/steps/dynamic-segment")
@Operation(summary = "生成动态段", description = "用户输入8位随机数和14位时间戳。") @Operation(summary = "生成动态段",
public ApiResponse<QuotaControlBitResult> dynamicSegment(@Valid @RequestBody QuotaControlDynamicRequest request) { description = "无需请求体。后端生成8位随机值和当前14位时间戳,并仅返回dynamicSegment。")
return execute((s, o) -> service.dynamicSegment(request.getRandomValue(), request.getTimestamp(), s, o)); public ApiResponse<QuotaControlDynamicSegmentResult> dynamicSegment() {
JwtUser user = AuthContextHolder.get();
return ApiResponse.success(service.dynamicSegment(
InstitutionKeySubject.from(user), user.getUsername()), traceId());
}
@GetMapping("/segments/static")
@Operation(summary = "查询静态段",
description = "按当前JWT实训主体查询已生成的步骤八静态段,仅返回staticSegment,不重新计算且不推进状态。")
public ApiResponse<QuotaControlStaticSegmentResult> queryStaticSegment() {
return ApiResponse.success(service.queryStaticSegment(
InstitutionKeySubject.from(AuthContextHolder.get())), traceId());
}
@GetMapping("/segments/dynamic")
@Operation(summary = "查询动态段",
description = "按当前JWT实训主体查询已生成的步骤八动态段,仅返回dynamicSegment,不重新生成且不推进状态。")
public ApiResponse<QuotaControlDynamicSegmentResult> queryDynamicSegment() {
return ApiResponse.success(service.queryDynamicSegment(
InstitutionKeySubject.from(AuthContextHolder.get())), traceId());
} }
@PostMapping("/steps/read-central-bank-signature") @PostMapping("/steps/read-central-bank-signature")
@Operation(summary = "读取步骤七央行控制系统签名段") @Operation(summary = "读取步骤七央行控制系统签名段",
public ApiResponse<QuotaControlBitResult> readCentralBankSignature() { description = "成功响应的data仅返回centralBankSignatureSegment。")
return execute((s, o) -> service.readCentralBankSignature(s, o)); public ApiResponse<CentralBankSignatureSegmentResult> readCentralBankSignature() {
JwtUser user = AuthContextHolder.get();
return ApiResponse.success(service.readCentralBankSignature(
InstitutionKeySubject.from(user), user.getUsername()), traceId());
} }
@PostMapping("/steps/assemble") @PostMapping("/steps/assemble")
@ -48,9 +74,13 @@ public class QuotaControlBitController {
public ApiResponse<QuotaControlBitResult> assemble() { return execute((s, o) -> service.assemble(s, o)); } public ApiResponse<QuotaControlBitResult> assemble() { return execute((s, o) -> service.assemble(s, o)); }
@PostMapping("/steps/sign") @PostMapping("/steps/sign")
@Operation(summary = "商业银行第二私钥签名确认", description = "前端提交完整商业银行第二SM2私钥;错误私钥或错误算法会累计实训错误次数。") @Operation(summary = "商业银行第二私钥签名确认",
public ApiResponse<QuotaControlBitResult> sign(@Valid @RequestBody QuotaControlSignRequest request) { description = "前端提交完整额度控制位、商业银行第二SM2私钥和SM2算法。后端校验完整额度控制位与步骤八拼接结果一致后进行签名;错误内容、私钥或算法会累计实训错误次数。")
return execute((s, o) -> service.sign(request.getPrivateKey(), request.getHashAlgorithm(), s, o)); public ApiResponse<SignatureResult> sign(@Valid @RequestBody QuotaControlSignRequest request) {
JwtUser user = AuthContextHolder.get();
QuotaControlBitResult result = service.sign(request.getPrivateKey(), request.getCompleteControlBit(),
request.getHashAlgorithm(), InstitutionKeySubject.from(user), user.getUsername());
return ApiResponse.success(new SignatureResult(result.getBankSignature()), traceId());
} }
@PostMapping("/steps/package") @PostMapping("/steps/package")

@ -71,7 +71,7 @@ public class QuotaRequestController {
@PostMapping("/steps/send") @PostMapping("/steps/send")
@Operation(summary = "商业银行发送额度请求报文", @Operation(summary = "商业银行发送额度请求报文",
description = "仅将报文发送状态推进为QUOTA_SENT,央行需调用独立接收接口。") description = "发送成功即视为央行已收到,央行查询状态由1(未发送)变为2(已发送)。")
public ApiResponse<QuotaRequestMessageResult> send() { public ApiResponse<QuotaRequestMessageResult> send() {
JwtUser user = AuthContextHolder.get(); JwtUser user = AuthContextHolder.get();
return ApiResponse.success(service.sendQuotaRequest( return ApiResponse.success(service.sendQuotaRequest(

@ -158,7 +158,7 @@ class CurrencyGenerationVerificationControllerTest {
mvc.perform(post(BASE_PATH + "/steps/confirm").header("Authorization", authorization) mvc.perform(post(BASE_PATH + "/steps/confirm").header("Authorization", authorization)
.contentType("application/json").content(confirmStep(verificationId, requestMapper.selectById(requestId).getRequestDigest(), centralPrivateKey))) .contentType("application/json").content(confirmStep(verificationId, requestMapper.selectById(requestId).getRequestDigest(), centralPrivateKey)))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.centralBankSignature") .andExpect(jsonPath("$.data.signature")
.value(org.hamcrest.Matchers.matchesPattern("[0-9A-F]+"))) .value(org.hamcrest.Matchers.matchesPattern("[0-9A-F]+")))
.andExpect(jsonPath("$.data.length()").value(1)) .andExpect(jsonPath("$.data.length()").value(1))
.andExpect(jsonPath("$.data.status").doesNotExist()) .andExpect(jsonPath("$.data.status").doesNotExist())
@ -171,7 +171,7 @@ class CurrencyGenerationVerificationControllerTest {
.contentType("application/json").content(confirmStep(verificationId, .contentType("application/json").content(confirmStep(verificationId,
requestMapper.selectById(requestId).getRequestDigest(), centralPrivateKey))) requestMapper.selectById(requestId).getRequestDigest(), centralPrivateKey)))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.centralBankSignature").value(centralBankSignature)) .andExpect(jsonPath("$.data.signature").value(centralBankSignature))
.andExpect(jsonPath("$.data.length()").value(1)); .andExpect(jsonPath("$.data.length()").value(1));
assertThat(verificationMapper.selectById(verificationId).getConfirmationTime()).isEqualTo(confirmationTime); assertThat(verificationMapper.selectById(verificationId).getConfirmationTime()).isEqualTo(confirmationTime);
mvc.perform(post(BASE_PATH + "/steps/verify-quota").header("Authorization", authorization) mvc.perform(post(BASE_PATH + "/steps/verify-quota").header("Authorization", authorization)

@ -287,7 +287,9 @@ class InstitutionIdentifierControllerTest {
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.content("{\"bankCode\":\"BKCHCNBJ20101|20260730143218\"}")) .content("{\"bankCode\":\"BKCHCNBJ20101|20260730143218\"}"))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value("DIGESTED")); .andExpect(jsonPath("$.data.digest").value(
org.hamcrest.Matchers.matchesPattern("[0-9A-F]{64}")))
.andExpect(jsonPath("$.data.length()").value(1));
InstitutionSm2KeyEntity bankKey = keyMapper.selectList(null).stream() InstitutionSm2KeyEntity bankKey = keyMapper.selectList(null).stream()
.filter(key -> InstitutionKeyService.BANK_SECOND_KEY.equals(key.getKeyId())) .filter(key -> InstitutionKeyService.BANK_SECOND_KEY.equals(key.getKeyId()))
@ -299,9 +301,8 @@ class InstitutionIdentifierControllerTest {
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.content("{\"privateKey\":\"" + privateKey + "\"}")) .content("{\"privateKey\":\"" + privateKey + "\"}"))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value("SIGNED")) .andExpect(jsonPath("$.data.signature").isNotEmpty())
.andExpect(jsonPath("$.data.keyId").value(InstitutionKeyService.BANK_SECOND_KEY)) .andExpect(jsonPath("$.data.length()").value(1));
.andExpect(jsonPath("$.data.signature").isNotEmpty());
} }
@Test @Test
@ -500,9 +501,8 @@ class InstitutionIdentifierControllerTest {
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.content("{\"privateKey\":\"" + privateKey + "\"}")) .content("{\"privateKey\":\"" + privateKey + "\"}"))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value("SIGNED")) .andExpect(jsonPath("$.data.signature").isNotEmpty())
.andExpect(jsonPath("$.data.signatureAlgorithm").value("SM2_WITH_SM3")) .andExpect(jsonPath("$.data.length()").value(1));
.andExpect(jsonPath("$.data.signatureHashAlgorithm").value("SM3"));
mvc.perform(get(BASE_PATH + "/applications/commercial-bank") mvc.perform(get(BASE_PATH + "/applications/commercial-bank")
.header("Authorization", authorization)) .header("Authorization", authorization))
@ -562,11 +562,8 @@ class InstitutionIdentifierControllerTest {
mvc.perform(post(BASE_PATH + "/applications/confirmation") mvc.perform(post(BASE_PATH + "/applications/confirmation")
.header("Authorization", authorization)) .header("Authorization", authorization))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value("ISSUED")) .andExpect(jsonPath("$.data.signature").isNotEmpty())
.andExpect(jsonPath("$.data.signingKeyId") .andExpect(jsonPath("$.data.length()").value(1));
.value(InstitutionKeyService.CENTRAL_FIRST_KEY))
.andExpect(jsonPath("$.data.signatureAlgorithm").value("SM2_WITH_SM3"))
.andExpect(jsonPath("$.data.institutionIdentifier").value(org.hamcrest.Matchers.startsWith("ORG_")));
mvc.perform(get(BASE_PATH + "/applications/final-identifier") mvc.perform(get(BASE_PATH + "/applications/final-identifier")
.header("Authorization", authorization)) .header("Authorization", authorization))
@ -619,29 +616,20 @@ class InstitutionIdentifierControllerTest {
String issuedOrg = jdbcTemplate.queryForObject( String issuedOrg = jdbcTemplate.queryForObject(
"SELECT institution_identifier FROM institution_identifier_application WHERE id = ?", "SELECT institution_identifier FROM institution_identifier_application WHERE id = ?",
String.class, applicationId); String.class, applicationId);
String digestResponse = mvc.perform(post(BASE_PATH + "/currency-requests/steps/digest") mvc.perform(post(BASE_PATH + "/currency-requests/steps/digest")
.header("Authorization", authorization) .header("Authorization", authorization)
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.content("{\"amount\":1589.85,\"deliveryNodeCode\":\"SYS_DC_001\"," .content("{\"amount\":1589.85,\"deliveryNodeCode\":\"SYS_DC_001\","
+ "\"institutionIdentifier\":\"" + issuedOrg + "\"," + "\"institutionIdentifier\":\"" + issuedOrg + "\","
+ "\"requestTimestamp\":\"20260730153218\"}")) + "\"requestTimestamp\":\"20260730153218\"}"))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value("DIGESTED")) .andExpect(jsonPath("$.data.digest")
.andExpect(jsonPath("$.data.requestDigest")
.value(org.hamcrest.Matchers.matchesPattern("[0-9A-F]{64}"))) .value(org.hamcrest.Matchers.matchesPattern("[0-9A-F]{64}")))
.andExpect(jsonPath("$.data.identifierApplicationId").value(applicationId)) .andExpect(jsonPath("$.data.length()").value(1));
.andExpect(jsonPath("$.data.institutionIdentifier")
.value(org.hamcrest.Matchers.startsWith("ORG_")))
.andExpect(jsonPath("$.data.fullInstitutionIdentifier")
.value(org.hamcrest.Matchers.matchesPattern("[0-9A-F]{64}")))
.andExpect(jsonPath("$.data.amount").value(1589.85))
.andExpect(jsonPath("$.data.deliveryNodeCode").value("SYS_DC_001"))
.andExpect(jsonPath("$.data.requestTimestamp").value("20260730153218"))
.andExpect(jsonPath("$.data.requestOriginalText")
.value(issuedOrg + "|1589.85|SYS_DC_001|20260730153218"))
.andReturn().getResponse().getContentAsString();
Number currencyRequestId = JsonPath.read(digestResponse, "$.data.requestId"); Number currencyRequestId = jdbcTemplate.queryForObject(
"SELECT id FROM currency_generation_request WHERE institution_identifier = ? AND deleted = FALSE",
Number.class, issuedOrg);
java.util.Map<String, Object> storedRequest = jdbcTemplate.queryForMap( java.util.Map<String, Object> storedRequest = jdbcTemplate.queryForMap(
"SELECT institution_identifier, amount, delivery_node_code, request_timestamp, " "SELECT institution_identifier, amount, delivery_node_code, request_timestamp, "
+ "request_original_text, request_digest FROM currency_generation_request WHERE id = ?", + "request_original_text, request_digest FROM currency_generation_request WHERE id = ?",
@ -668,22 +656,20 @@ class InstitutionIdentifierControllerTest {
.andExpect(jsonPath("$.data.requestDigest") .andExpect(jsonPath("$.data.requestDigest")
.value(storedRequest.get("request_digest"))); .value(storedRequest.get("request_digest")));
String secondDigestResponse = mvc.perform(post(BASE_PATH + "/currency-requests/steps/digest") mvc.perform(post(BASE_PATH + "/currency-requests/steps/digest")
.header("Authorization", authorization) .header("Authorization", authorization)
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.content("{\"amount\":2000.00,\"deliveryNodeCode\":\"SYS_DC_002\"," .content("{\"amount\":2000.00,\"deliveryNodeCode\":\"SYS_DC_002\","
+ "\"institutionIdentifier\":\"" + issuedOrg + "\"," + "\"institutionIdentifier\":\"" + issuedOrg + "\","
+ "\"requestTimestamp\":\"20260730160000\"}")) + "\"requestTimestamp\":\"20260730160000\"}"))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.requestId").value(currencyRequestId.longValue())) .andExpect(jsonPath("$.data.digest")
.andExpect(jsonPath("$.data.amount").value(2000.00)) .value(org.hamcrest.Matchers.matchesPattern("[0-9A-F]{64}")))
.andExpect(jsonPath("$.data.deliveryNodeCode").value("SYS_DC_002")) .andExpect(jsonPath("$.data.length()").value(1));
.andExpect(jsonPath("$.data.requestTimestamp").value("20260730160000")) Number repeatedRequestId = jdbcTemplate.queryForObject(
.andExpect(jsonPath("$.data.requestOriginalText") "SELECT id FROM currency_generation_request WHERE institution_identifier = ? AND deleted = FALSE",
.value(issuedOrg + "|2000.00|SYS_DC_002|20260730160000")) Number.class, issuedOrg);
.andReturn().getResponse().getContentAsString(); assertThat(repeatedRequestId.longValue()).isEqualTo(currencyRequestId.longValue());
assertThat(JsonPath.<Number>read(secondDigestResponse, "$.data.requestId").longValue())
.isEqualTo(currencyRequestId.longValue());
Integer requestCount = jdbcTemplate.queryForObject( Integer requestCount = jdbcTemplate.queryForObject(
"SELECT COUNT(*) FROM currency_generation_request WHERE institution_identifier = ? AND deleted = FALSE", "SELECT COUNT(*) FROM currency_generation_request WHERE institution_identifier = ? AND deleted = FALSE",
Integer.class, issuedOrg); Integer.class, issuedOrg);
@ -707,10 +693,9 @@ class InstitutionIdentifierControllerTest {
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.content("{\"privateKey\":\"" + privateKey + "\"}")) .content("{\"privateKey\":\"" + privateKey + "\"}"))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value("SIGNED")) .andExpect(jsonPath("$.data.signature")
.andExpect(jsonPath("$.data.signingKeyId").value(InstitutionKeyService.BANK_SECOND_KEY)) .value(org.hamcrest.Matchers.matchesPattern("[0-9A-F]+")))
.andExpect(jsonPath("$.data.bankSignature") .andExpect(jsonPath("$.data.length()").value(1));
.value(org.hamcrest.Matchers.matchesPattern("[0-9A-F]+")));
mvc.perform(post(BASE_PATH + "/currency-requests/steps/package") mvc.perform(post(BASE_PATH + "/currency-requests/steps/package")
.header("Authorization", authorization)) .header("Authorization", authorization))
@ -861,9 +846,8 @@ class InstitutionIdentifierControllerTest {
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.content("{\"privateKey\":\"" + privateKey + "\"}")) .content("{\"privateKey\":\"" + privateKey + "\"}"))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value("ISSUED")) .andExpect(jsonPath("$.data.signature").isNotEmpty())
.andExpect(jsonPath("$.data.signingKeyId") .andExpect(jsonPath("$.data.length()").value(1));
.value(InstitutionKeyService.CENTRAL_FIRST_KEY));
} }
private long advanceToVerified(String bankCode) throws Exception { private long advanceToVerified(String bankCode) throws Exception {
@ -916,17 +900,19 @@ class InstitutionIdentifierControllerTest {
} }
private long digest(String bankCode) throws Exception { private long digest(String bankCode) throws Exception {
String response = mvc.perform(post(BASE_PATH + "/steps/digest") mvc.perform(post(BASE_PATH + "/steps/digest")
.header("Authorization", authorization) .header("Authorization", authorization)
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.content("{\"bankCode\":\"" + bankCode + "|20260730143218\"}")) .content("{\"bankCode\":\"" + bankCode + "|20260730143218\"}"))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.applicationId").isNumber())
.andExpect(jsonPath("$.data.status").value("DIGESTED"))
.andExpect(jsonPath("$.data.algorithm").value("SM3"))
.andExpect(jsonPath("$.data.digest").isNotEmpty()) .andExpect(jsonPath("$.data.digest").isNotEmpty())
.andReturn().getResponse().getContentAsString(); .andExpect(jsonPath("$.data.length()").value(1))
Number applicationId = JsonPath.read(response, "$.data.applicationId"); .andExpect(jsonPath("$.data.applicationId").doesNotExist())
return applicationId.longValue(); .andExpect(jsonPath("$.data.status").doesNotExist())
.andExpect(jsonPath("$.data.algorithm").doesNotExist());
return applicationMapper.selectList(null).stream()
.max(java.util.Comparator.comparing(InstitutionIdentifierApplicationEntity::getCreatedAt)
.thenComparing(InstitutionIdentifierApplicationEntity::getId))
.orElseThrow(() -> new AssertionError("机构标识申请记录未创建")).getId();
} }
} }

@ -60,6 +60,8 @@ class TransactionInformationIdentifierControllerTest {
"/api/v1/institution-identifiers/quota-verifications"; "/api/v1/institution-identifiers/quota-verifications";
private static final String CONTROL_SIGNATURE_BASE_PATH = private static final String CONTROL_SIGNATURE_BASE_PATH =
"/api/v1/institution-identifiers/control-system-signatures"; "/api/v1/institution-identifiers/control-system-signatures";
private static final String COMMERCIAL_BANK_CONTROL_SIGNATURE_BASE_PATH =
"/api/v1/institution-identifiers/commercial-bank/control-system-signatures";
private static final String QUOTA_CONTROL_BASE_PATH = private static final String QUOTA_CONTROL_BASE_PATH =
"/api/v1/institution-identifiers/quota-control-bits"; "/api/v1/institution-identifiers/quota-control-bits";
private static final String CENTRAL_QUOTA_CONTROL_BASE_PATH = private static final String CENTRAL_QUOTA_CONTROL_BASE_PATH =
@ -280,6 +282,10 @@ class TransactionInformationIdentifierControllerTest {
.andExpect(jsonPath("$.data.signature").isNotEmpty()) .andExpect(jsonPath("$.data.signature").isNotEmpty())
.andExpect(jsonPath("$.data.status").doesNotExist()) .andExpect(jsonPath("$.data.status").doesNotExist())
.andExpect(jsonPath("$.data.quotaRequestMessage").doesNotExist()); .andExpect(jsonPath("$.data.quotaRequestMessage").doesNotExist());
mvc.perform(get(CENTRAL_QUOTA_REQUEST_BASE_PATH).header("Authorization", authorization))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value(1))
.andExpect(jsonPath("$.data.length()").value(7));
mvc.perform(post(QUOTA_BASE_PATH + "/steps/send").header("Authorization", authorization)) mvc.perform(post(QUOTA_BASE_PATH + "/steps/send").header("Authorization", authorization))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.length()").value(6)) .andExpect(jsonPath("$.data.length()").value(6))
@ -296,7 +302,7 @@ class TransactionInformationIdentifierControllerTest {
.andExpect(jsonPath("$.data.length()").value(6)); .andExpect(jsonPath("$.data.length()").value(6));
mvc.perform(get(CENTRAL_QUOTA_REQUEST_BASE_PATH).header("Authorization", authorization)) mvc.perform(get(CENTRAL_QUOTA_REQUEST_BASE_PATH).header("Authorization", authorization))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value(1)) .andExpect(jsonPath("$.data.status").value(2))
.andExpect(jsonPath("$.data.quotaRequestId").isNotEmpty()) .andExpect(jsonPath("$.data.quotaRequestId").isNotEmpty())
.andExpect(jsonPath("$.data.amount").value(1589.85)) .andExpect(jsonPath("$.data.amount").value(1589.85))
.andExpect(jsonPath("$.data.orgId").value("ORG_3A4B5C6D7E8F")) .andExpect(jsonPath("$.data.orgId").value("ORG_3A4B5C6D7E8F"))
@ -307,15 +313,7 @@ class TransactionInformationIdentifierControllerTest {
.andExpect(jsonPath("$.data.requestMessage").doesNotExist()); .andExpect(jsonPath("$.data.requestMessage").doesNotExist());
mvc.perform(post(CENTRAL_QUOTA_REQUEST_BASE_PATH + "/steps/receive") mvc.perform(post(CENTRAL_QUOTA_REQUEST_BASE_PATH + "/steps/receive")
.header("Authorization", authorization)) .header("Authorization", authorization))
.andExpect(status().isOk()) .andExpect(status().isNotFound());
.andExpect(jsonPath("$.data.status").value(2))
.andExpect(jsonPath("$.data.quotaRequestId").isNotEmpty())
.andExpect(jsonPath("$.data.orgId").value("ORG_3A4B5C6D7E8F"))
.andExpect(jsonPath("$.data.length()").value(7));
mvc.perform(post(CENTRAL_QUOTA_REQUEST_BASE_PATH + "/steps/receive")
.header("Authorization", authorization))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value(2));
TransactionInformationIdentifierEntity persisted = transactionMapper.selectList(null).get(0); TransactionInformationIdentifierEntity persisted = transactionMapper.selectList(null).get(0);
assertThat(persisted.getStatus()).isEqualTo("QUOTA_RECEIVED"); assertThat(persisted.getStatus()).isEqualTo("QUOTA_RECEIVED");
@ -328,7 +326,7 @@ class TransactionInformationIdentifierControllerTest {
.extracting(TransactionInformationIdentifierOperationLogEntity::getOperation) .extracting(TransactionInformationIdentifierOperationLogEntity::getOperation)
.containsExactly("DIGEST", "ASSEMBLE", "QUOTA_DIGEST", "QUOTA_SIGN", .containsExactly("DIGEST", "ASSEMBLE", "QUOTA_DIGEST", "QUOTA_SIGN",
"QUOTA_DIGEST", "QUOTA_SIGN", "QUOTA_SIGN", "QUOTA_DIGEST", "QUOTA_SIGN", "QUOTA_SIGN",
"QUOTA_PACKAGE", "QUOTA_SEND", "QUOTA_RECEIVE"); "QUOTA_PACKAGE", "QUOTA_SEND");
} }
@Test @Test
@ -395,51 +393,105 @@ class TransactionInformationIdentifierControllerTest {
assertThat(verified.getQuotaSignatureValid()).isTrue(); assertThat(verified.getQuotaSignatureValid()).isTrue();
assertThat(verified.getQuotaDigestMatches()).isTrue(); assertThat(verified.getQuotaDigestMatches()).isTrue();
mvc.perform(post(VERIFICATION_BASE_PATH + "/steps/concatenate-original-text")
.header("Authorization", authorization))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.originalText").value(verificationOriginalText));
mvc.perform(post(VERIFICATION_BASE_PATH + "/steps/hash")
.header("Authorization", authorization)
.contentType("application/json")
.content("{\"originalText\":\"" + verificationOriginalText + "\"}"))
.andExpect(status().isOk());
assertThat(transactionMapper.selectList(null).get(0).getQuotaSignatureDigest()).isNull();
mvc.perform(post(VERIFICATION_BASE_PATH + "/steps/recover-signature-digest")
.header("Authorization", authorization).contentType("application/json")
.content("{\"publicKey\":\"" + bankPublicKey + "\"}"))
.andExpect(status().isOk());
mvc.perform(post(VERIFICATION_BASE_PATH + "/steps/compare-digests")
.header("Authorization", authorization))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.h1EqualsH2").value(true));
mvc.perform(post(VERIFICATION_BASE_PATH + "/steps/compare-digests")
.header("Authorization", authorization))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.h1EqualsH2").value(true));
assertThat(transactionMapper.selectList(null)).hasSize(1);
assertThat(transactionMapper.selectList(null).get(0).getId()).isEqualTo(stepSixRecordId);
verified = transactionMapper.selectList(null).get(0);
mvc.perform(post(CONTROL_SIGNATURE_BASE_PATH + "/steps/prepare") mvc.perform(post(CONTROL_SIGNATURE_BASE_PATH + "/steps/prepare")
.header("Authorization", authorization)) .header("Authorization", authorization))
.andExpect(status().isNotFound()); .andExpect(status().isNotFound());
String controlOriginalText = verified.getAmount().setScale(2).toPlainString() + "|" String controlOriginalText = verified.getAmount().setScale(2).toPlainString() + "|"
+ verified.getInstitutionIdentifier() + "|" + verified.getTransactionIdentifier(); + verified.getInstitutionIdentifier() + "|" + verified.getTransactionIdentifier();
mvc.perform(post(CONTROL_SIGNATURE_BASE_PATH + "/steps/digest")
.header("Authorization", authorization)
.contentType("application/json")
.content("{\"originalText\":\"999.00|"
+ verified.getInstitutionIdentifier() + "|" + verified.getTransactionIdentifier()
+ "\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.allOf(
org.hamcrest.Matchers.containsString("与当前用户前序数据不一致"),
org.hamcrest.Matchers.containsString("第2次错误"))));
assertThat(controlSignatureMapper.selectList(null)).isEmpty();
String firstDigest = mvc.perform(post(CONTROL_SIGNATURE_BASE_PATH + "/steps/digest") String firstDigest = mvc.perform(post(CONTROL_SIGNATURE_BASE_PATH + "/steps/digest")
.header("Authorization", authorization) .header("Authorization", authorization)
.contentType("application/json") .contentType("application/json")
.content("{\"originalText\":\"" + controlOriginalText + "\"}")) .content("{\"originalText\":\"" + controlOriginalText + "\"}"))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value("DIGESTED"))
.andExpect(jsonPath("$.data.originalText").value(controlOriginalText))
.andExpect(jsonPath("$.data.digest").value(cryptography.sm3(controlOriginalText))) .andExpect(jsonPath("$.data.digest").value(cryptography.sm3(controlOriginalText)))
.andExpect(jsonPath("$.data.controlId").value(org.hamcrest.Matchers.matchesPattern( .andExpect(jsonPath("$.data.length()").value(1))
"CTRL_\\d{8}_\\d{3}"))) .andExpect(jsonPath("$.data.status").doesNotExist())
.andExpect(jsonPath("$.data.originalText").doesNotExist())
.andExpect(jsonPath("$.data.controlId").doesNotExist())
.andReturn().getResponse().getContentAsString(); .andReturn().getResponse().getContentAsString();
String repeatedDigest = mvc.perform(post(CONTROL_SIGNATURE_BASE_PATH + "/steps/digest") String repeatedDigest = mvc.perform(post(CONTROL_SIGNATURE_BASE_PATH + "/steps/digest")
.header("Authorization", authorization) .header("Authorization", authorization)
.contentType("application/json") .contentType("application/json")
.content("{\"originalText\":\"" + controlOriginalText + "\"}")) .content("{\"originalText\":\"" + controlOriginalText + "\"}"))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
assertThat(com.jayway.jsonpath.JsonPath.<Number>read(repeatedDigest, "$.data.id").longValue()) assertThat(com.jayway.jsonpath.JsonPath.<String>read(repeatedDigest, "$.data.digest"))
.isEqualTo(com.jayway.jsonpath.JsonPath.<Number>read(firstDigest, "$.data.id").longValue()); .isEqualTo(com.jayway.jsonpath.JsonPath.<String>read(firstDigest, "$.data.digest"));
assertThat(controlSignatureMapper.selectList(null)).hasSize(1); assertThat(controlSignatureMapper.selectList(null)).hasSize(1);
mvc.perform(post(CONTROL_SIGNATURE_BASE_PATH + "/steps/sign") mvc.perform(post(CONTROL_SIGNATURE_BASE_PATH + "/steps/sign")
.header("Authorization", authorization) .header("Authorization", authorization)
.contentType("application/json") .contentType("application/json")
.content("{\"privateKey\":\"WRONG_CENTRAL_PRIVATE_KEY\"}")) .content("{\"privateKey\":\"WRONG_CENTRAL_PRIVATE_KEY\"}"))
.andExpect(status().isBadRequest()) .andExpect(status().isBadRequest())
.andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("第2次错误"))); .andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("第3次错误")));
mvc.perform(post(CONTROL_SIGNATURE_BASE_PATH + "/steps/sign") mvc.perform(post(CONTROL_SIGNATURE_BASE_PATH + "/steps/sign")
.header("Authorization", authorization) .header("Authorization", authorization)
.contentType("application/json") .contentType("application/json")
.content("{\"privateKey\":\"" + centralPrivateKey + "\"}")) .content("{\"privateKey\":\"" + centralPrivateKey + "\"}"))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value("SIGNED")) .andExpect(jsonPath("$.data.signature").value(org.hamcrest.Matchers.matchesPattern("[0-9A-F]+")))
.andExpect(jsonPath("$.data.signingKeyId").value(InstitutionKeyService.CENTRAL_FIRST_KEY)) .andExpect(jsonPath("$.data.length()").value(1));
.andExpect(jsonPath("$.data.signature").value(org.hamcrest.Matchers.matchesPattern("[0-9A-F]+")));
mvc.perform(post(CONTROL_SIGNATURE_BASE_PATH + "/steps/package").header("Authorization", authorization)) mvc.perform(post(CONTROL_SIGNATURE_BASE_PATH + "/steps/package").header("Authorization", authorization))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value("PACKAGED")) .andExpect(jsonPath("$.data.status").value("PACKAGED"))
.andExpect(jsonPath("$.data.responseMessage").value(org.hamcrest.Matchers.containsString( .andExpect(jsonPath("$.data.responseMessage").value(org.hamcrest.Matchers.containsString(
"\"cbCtrlSignature\""))); "\"cbCtrlSignature\"")));
mvc.perform(get(COMMERCIAL_BANK_CONTROL_SIGNATURE_BASE_PATH).header("Authorization", authorization))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value(1))
.andExpect(jsonPath("$.data.ctrlId").isNotEmpty())
.andExpect(jsonPath("$.data.amount").value(1589.85))
.andExpect(jsonPath("$.data.orgId").value("ORG_3A4B5C6D7E8F"))
.andExpect(jsonPath("$.data.txnId").value(org.hamcrest.Matchers.startsWith("TXN_")))
.andExpect(jsonPath("$.data.cbCtrlSignature").isNotEmpty())
.andExpect(jsonPath("$.data.length()").value(6));
mvc.perform(post(CONTROL_SIGNATURE_BASE_PATH + "/steps/send").header("Authorization", authorization)) mvc.perform(post(CONTROL_SIGNATURE_BASE_PATH + "/steps/send").header("Authorization", authorization))
.andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("SENT")); .andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("SENT"));
mvc.perform(get(COMMERCIAL_BANK_CONTROL_SIGNATURE_BASE_PATH).header("Authorization", authorization))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value(2))
.andExpect(jsonPath("$.data.ctrlId").isNotEmpty())
.andExpect(jsonPath("$.data.amount").value(1589.85))
.andExpect(jsonPath("$.data.orgId").value("ORG_3A4B5C6D7E8F"))
.andExpect(jsonPath("$.data.txnId").value(org.hamcrest.Matchers.startsWith("TXN_")))
.andExpect(jsonPath("$.data.cbCtrlSignature").isNotEmpty())
.andExpect(jsonPath("$.data.length()").value(6));
ControlSystemSignatureEntity persisted = controlSignatureMapper.selectList(null).get(0); ControlSystemSignatureEntity persisted = controlSignatureMapper.selectList(null).get(0);
TransactionInformationIdentifierEntity transaction = transactionMapper.selectList(null).get(0); TransactionInformationIdentifierEntity transaction = transactionMapper.selectList(null).get(0);
@ -458,7 +510,7 @@ class TransactionInformationIdentifierControllerTest {
new LambdaQueryWrapper<StuModuleScoreDetailsEntity>() new LambdaQueryWrapper<StuModuleScoreDetailsEntity>()
.eq(StuModuleScoreDetailsEntity::getUserId, USER_ID) .eq(StuModuleScoreDetailsEntity::getUserId, USER_ID)
.eq(StuModuleScoreDetailsEntity::getSerialNumber, 3)); .eq(StuModuleScoreDetailsEntity::getSerialNumber, 3));
assertThat(score.getCompletionStatus()).isEqualTo("2"); assertThat(score.getCompletionStatus()).isEqualTo("3");
} }
@Test @Test
@ -466,64 +518,155 @@ class TransactionInformationIdentifierControllerTest {
flowsStepSixDataThroughCentralBankSignatureAndCommercialBankReceive(); flowsStepSixDataThroughCentralBankSignatureAndCommercialBankReceive();
InstitutionKeySubject subject = new InstitutionKeySubject(USER_ID, SCHOOL_ID, CLASS_ID); InstitutionKeySubject subject = new InstitutionKeySubject(USER_ID, SCHOOL_ID, CLASS_ID);
String bankPrivateKey = keyService.commercialBankKey(subject, "module-four-tester").getPrivateKey(); String bankPrivateKey = keyService.commercialBankKey(subject, "module-four-tester").getPrivateKey();
String transactionIdentifier = transactionMapper.selectList(null).get(0).getTransactionIdentifier(); mvc.perform(get(CENTRAL_QUOTA_CONTROL_BASE_PATH).header("Authorization", authorization))
.andExpect(status().isOk())
mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/static-segment") .andExpect(jsonPath("$.data.status").value(1))
.header("Authorization", authorization).contentType("application/json") .andExpect(jsonPath("$.data.quotaId").value(org.hamcrest.Matchers.nullValue()))
.content("{\"amount\":1590.85,\"institutionIdentifier\":\"ORG_3A4B5C6D7E8F\"," + .andExpect(jsonPath("$.data.length()").value(6));
"\"transactionIdentifier\":\"" + transactionIdentifier + "\"}")) mvc.perform(get(QUOTA_CONTROL_BASE_PATH + "/segments/static")
.andExpect(status().isBadRequest()) .header("Authorization", authorization))
.andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("第3次错误"))); .andExpect(status().isNotFound())
mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/static-segment") .andExpect(jsonPath("$.message").value("当前没有步骤八额度控制位记录"));
.header("Authorization", authorization).contentType("application/json") mvc.perform(get(QUOTA_CONTROL_BASE_PATH + "/segments/dynamic")
.content("{\"amount\":1589.85,\"institutionIdentifier\":\"ORG_3A4B5C6D7E8F\"," + .header("Authorization", authorization))
"\"transactionIdentifier\":\"" + transactionIdentifier + "\"}")) .andExpect(status().isNotFound())
.andExpect(jsonPath("$.message").value("当前没有步骤八额度控制位记录"));
String staticSegmentResponse = mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/static-segment")
.header("Authorization", authorization))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value("STATIC_READY"))
.andExpect(jsonPath("$.data.staticSegment").value( .andExpect(jsonPath("$.data.staticSegment").value(
org.hamcrest.Matchers.matchesPattern("STATIC_[0-9A-F]{64}"))) org.hamcrest.Matchers.matchesPattern("STATIC_[0-9A-F]{64}")))
.andExpect(jsonPath("$.data.receiveStatus").value(1)); .andExpect(jsonPath("$.data.length()").value(1))
mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/dynamic-segment") .andExpect(jsonPath("$.data.status").doesNotExist())
.header("Authorization", authorization).contentType("application/json") .andReturn().getResponse().getContentAsString();
.content("{\"randomValue\":\"7G8H9I0J\",\"timestamp\":\"20260730153600\"}")) String staticSegment = com.jayway.jsonpath.JsonPath.read(staticSegmentResponse, "$.data.staticSegment");
mvc.perform(get(QUOTA_CONTROL_BASE_PATH + "/segments/static")
.header("Authorization", authorization))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.dynamicSegment").value("DYN_7G8H9I0J_20260730153600")); .andExpect(jsonPath("$.data.staticSegment").value(staticSegment))
.andExpect(jsonPath("$.data.length()").value(1));
mvc.perform(get(QUOTA_CONTROL_BASE_PATH + "/segments/dynamic")
.header("Authorization", authorization))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.message").value("当前尚未生成步骤八动态段"));
String firstDynamicSegmentResponse = mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/dynamic-segment")
.header("Authorization", authorization))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.dynamicSegment").value(
org.hamcrest.Matchers.matchesPattern("DYN_[A-Z0-9]{8}_\\d{14}")))
.andExpect(jsonPath("$.data.length()").value(1))
.andExpect(jsonPath("$.data.status").doesNotExist())
.andReturn().getResponse().getContentAsString();
String firstDynamicSegment = com.jayway.jsonpath.JsonPath.read(
firstDynamicSegmentResponse, "$.data.dynamicSegment");
mvc.perform(get(QUOTA_CONTROL_BASE_PATH + "/segments/dynamic")
.header("Authorization", authorization))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.dynamicSegment").value(firstDynamicSegment))
.andExpect(jsonPath("$.data.length()").value(1));
long stepEightRecordId = quotaControlBitMapper.selectList(null).get(0).getId();
String secondDynamicSegmentResponse = mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/dynamic-segment")
.header("Authorization", authorization))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.dynamicSegment").value(
org.hamcrest.Matchers.matchesPattern("DYN_[A-Z0-9]{8}_\\d{14}")))
.andReturn().getResponse().getContentAsString();
String secondDynamicSegment = com.jayway.jsonpath.JsonPath.read(
secondDynamicSegmentResponse, "$.data.dynamicSegment");
assertThat(secondDynamicSegment).isNotEqualTo(firstDynamicSegment);
assertThat(quotaControlBitMapper.selectList(null)).hasSize(1);
assertThat(quotaControlBitMapper.selectList(null).get(0).getId()).isEqualTo(stepEightRecordId);
mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/read-central-bank-signature") mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/read-central-bank-signature")
.header("Authorization", authorization)) .header("Authorization", authorization))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.centralBankSignatureSegment").value( .andExpect(jsonPath("$.data.centralBankSignatureSegment").value(
org.hamcrest.Matchers.startsWith("CB_CTRL_"))); org.hamcrest.Matchers.startsWith("CB_CTRL_")))
.andExpect(jsonPath("$.data.length()").value(1))
.andExpect(jsonPath("$.data.status").doesNotExist())
.andExpect(jsonPath("$.data.completeControlBit").doesNotExist());
mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/assemble").header("Authorization", authorization)) mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/assemble").header("Authorization", authorization))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data.completeControlBit").value( .andExpect(jsonPath("$.data.completeControlBit").value(org.hamcrest.Matchers.allOf(
org.hamcrest.Matchers.containsString("|DYN_7G8H9I0J_20260730153600|CB_CTRL_"))); org.hamcrest.Matchers.containsString("|DYN_"),
org.hamcrest.Matchers.containsString("|CB_CTRL_"))));
String completeControlBit = quotaControlBitMapper.selectList(null).get(0).getCompleteControlBit();
mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/sign") mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/sign")
.header("Authorization", authorization).contentType("application/json") .header("Authorization", authorization).contentType("application/json")
.content("{\"privateKey\":\"" + bankPrivateKey + "\",\"hashAlgorithm\":\"SM3\"}")) .content("{\"privateKey\":\"" + bankPrivateKey + "\",\"completeControlBit\":\""
+ completeControlBit + "\",\"hashAlgorithm\":\"SM3\"}"))
.andExpect(status().isBadRequest()) .andExpect(status().isBadRequest())
.andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("第4次错误"))); .andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("第4次错误")));
mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/sign") mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/sign")
.header("Authorization", authorization).contentType("application/json") .header("Authorization", authorization).contentType("application/json")
.content("{\"privateKey\":\"WRONG_BANK_PRIVATE_KEY\",\"hashAlgorithm\":\"SM2\"}")) .content("{\"privateKey\":\"" + bankPrivateKey + "\",\"completeControlBit\":\""
+ completeControlBit + "_TAMPERED\",\"hashAlgorithm\":\"SM2\"}"))
.andExpect(status().isBadRequest()) .andExpect(status().isBadRequest())
.andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("第5次错误"))); .andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.allOf(
org.hamcrest.Matchers.containsString("完整额度控制位与步骤八拼接结果不一致"),
org.hamcrest.Matchers.containsString("第5次错误"))));
mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/sign") mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/sign")
.header("Authorization", authorization).contentType("application/json") .header("Authorization", authorization).contentType("application/json")
.content("{\"privateKey\":\"" + bankPrivateKey + "\",\"hashAlgorithm\":\"SM2\"}")) .content("{\"privateKey\":\"WRONG_BANK_PRIVATE_KEY\",\"completeControlBit\":\""
.andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("SIGNED")) + completeControlBit + "\",\"hashAlgorithm\":\"SM2\"}"))
.andExpect(jsonPath("$.data.bankSignature").value(org.hamcrest.Matchers.matchesPattern("[0-9A-F]+"))); .andExpect(status().isBadRequest())
.andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("第6次错误")));
mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/sign")
.header("Authorization", authorization).contentType("application/json")
.content("{\"privateKey\":\"" + bankPrivateKey + "\",\"completeControlBit\":\""
+ completeControlBit + "\",\"hashAlgorithm\":\"SM2\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.signature").value(org.hamcrest.Matchers.matchesPattern("[0-9A-F]+")))
.andExpect(jsonPath("$.data.length()").value(1));
mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/package").header("Authorization", authorization)) mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/package").header("Authorization", authorization))
.andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("PACKAGED")) .andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("PACKAGED"))
.andExpect(jsonPath("$.data.requestMessage").value(org.hamcrest.Matchers.containsString("\"quotaId\""))); .andExpect(jsonPath("$.data.requestMessage").value(org.hamcrest.Matchers.containsString("\"quotaId\"")));
mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/static-segment")
.header("Authorization", authorization))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.staticSegment").value(
org.hamcrest.Matchers.matchesPattern("STATIC_[0-9A-F]{64}")));
QuotaControlBitEntity resetByStatic = quotaControlBitMapper.selectList(null).get(0);
assertThat(resetByStatic.getId()).isEqualTo(stepEightRecordId);
assertThat(resetByStatic.getStatus()).isEqualTo("STATIC_READY");
assertThat(resetByStatic.getDynamicSegment()).isNull();
assertThat(resetByStatic.getCentralBankSignatureSegment()).isNull();
assertThat(resetByStatic.getCompleteControlBit()).isNull();
assertThat(resetByStatic.getBankSignature()).isNull();
assertThat(resetByStatic.getRequestMessage()).isNull();
mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/dynamic-segment")
.header("Authorization", authorization)).andExpect(status().isOk());
mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/read-central-bank-signature")
.header("Authorization", authorization)).andExpect(status().isOk());
mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/assemble")
.header("Authorization", authorization)).andExpect(status().isOk());
String regeneratedCompleteControlBit = quotaControlBitMapper.selectList(null).get(0).getCompleteControlBit();
mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/sign")
.header("Authorization", authorization).contentType("application/json")
.content("{\"privateKey\":\"" + bankPrivateKey + "\",\"completeControlBit\":\""
+ regeneratedCompleteControlBit + "\",\"hashAlgorithm\":\"SM2\"}"))
.andExpect(status().isOk());
mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/package").header("Authorization", authorization))
.andExpect(status().isOk());
mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/send").header("Authorization", authorization)) mvc.perform(post(QUOTA_CONTROL_BASE_PATH + "/steps/send").header("Authorization", authorization))
.andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("SENT"))
.andExpect(jsonPath("$.data.receiveStatus").value(1));
mvc.perform(get(CENTRAL_QUOTA_CONTROL_BASE_PATH).header("Authorization", authorization))
.andExpect(status().isOk()).andExpect(jsonPath("$.data.receiveStatus").value(1));
mvc.perform(post(CENTRAL_QUOTA_CONTROL_BASE_PATH + "/steps/receive").header("Authorization", authorization))
.andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("RECEIVED")) .andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("RECEIVED"))
.andExpect(jsonPath("$.data.receiveStatus").value(2)); .andExpect(jsonPath("$.data.receiveStatus").value(2));
mvc.perform(get(CENTRAL_QUOTA_CONTROL_BASE_PATH).header("Authorization", authorization))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value(2))
.andExpect(jsonPath("$.data.quotaId").value(org.hamcrest.Matchers.startsWith("QC_")))
.andExpect(jsonPath("$.data.staticSegment").value(
org.hamcrest.Matchers.matchesPattern("STATIC_[0-9A-F]{64}")))
.andExpect(jsonPath("$.data.dynamicSegment").value(
org.hamcrest.Matchers.matchesPattern("DYN_[A-Z0-9]{8}_\\d{14}")))
.andExpect(jsonPath("$.data.cbSignatureSegment").value(
org.hamcrest.Matchers.startsWith("CB_CTRL_")))
.andExpect(jsonPath("$.data.bankSignature").value(
org.hamcrest.Matchers.matchesPattern("[0-9A-F]+")))
.andExpect(jsonPath("$.data.length()").value(6));
mvc.perform(post(CENTRAL_QUOTA_CONTROL_BASE_PATH + "/steps/receive")
.header("Authorization", authorization))
.andExpect(status().isNotFound());
QuotaControlBitEntity stored = quotaControlBitMapper.selectList(null).get(0); QuotaControlBitEntity stored = quotaControlBitMapper.selectList(null).get(0);
assertThat(stored.getStatus()).isEqualTo("RECEIVED"); assertThat(stored.getStatus()).isEqualTo("RECEIVED");
@ -533,7 +676,7 @@ class TransactionInformationIdentifierControllerTest {
StuModuleScoreDetailsEntity score = scoreMapper.selectOne(new LambdaQueryWrapper<StuModuleScoreDetailsEntity>() StuModuleScoreDetailsEntity score = scoreMapper.selectOne(new LambdaQueryWrapper<StuModuleScoreDetailsEntity>()
.eq(StuModuleScoreDetailsEntity::getUserId, USER_ID) .eq(StuModuleScoreDetailsEntity::getUserId, USER_ID)
.eq(StuModuleScoreDetailsEntity::getSerialNumber, 3)); .eq(StuModuleScoreDetailsEntity::getSerialNumber, 3));
assertThat(score.getCompletionStatus()).isEqualTo("5"); assertThat(score.getCompletionStatus()).isEqualTo("6");
} }
@Test @Test
@ -544,7 +687,7 @@ class TransactionInformationIdentifierControllerTest {
.header("Authorization", authorization).contentType("application/json") .header("Authorization", authorization).contentType("application/json")
.content("{\"amount\":1590.85}")) .content("{\"amount\":1590.85}"))
.andExpect(status().isBadRequest()) .andExpect(status().isBadRequest())
.andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("第6次错误"))); .andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("第7次错误")));
mvc.perform(post(STANDARD_CURRENCY_BASE_PATH + "/steps/decompose") mvc.perform(post(STANDARD_CURRENCY_BASE_PATH + "/steps/decompose")
.header("Authorization", authorization).contentType("application/json") .header("Authorization", authorization).contentType("application/json")
.content("{\"amount\":1589.85}")) .content("{\"amount\":1589.85}"))
@ -560,7 +703,7 @@ class TransactionInformationIdentifierControllerTest {
.content("{\"prefix\":\"RMB\",\"idRule\":\"批次号+枚序号+随机校验码\"," + .content("{\"prefix\":\"RMB\",\"idRule\":\"批次号+枚序号+随机校验码\"," +
"\"currencyStatus\":\"待生效\"}")) "\"currencyStatus\":\"待生效\"}"))
.andExpect(status().isBadRequest()) .andExpect(status().isBadRequest())
.andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("第7次错误"))); .andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("第8次错误")));
mvc.perform(post(STANDARD_CURRENCY_BASE_PATH + "/steps/confirm-rule") mvc.perform(post(STANDARD_CURRENCY_BASE_PATH + "/steps/confirm-rule")
.header("Authorization", authorization).contentType("application/json") .header("Authorization", authorization).contentType("application/json")
.content("{\"prefix\":\"DC\",\"idRule\":\"批次号+枚序号+随机校验码\"," + .content("{\"prefix\":\"DC\",\"idRule\":\"批次号+枚序号+随机校验码\"," +
@ -586,10 +729,18 @@ class TransactionInformationIdentifierControllerTest {
assertThat(currencies.stream().map(StandardCurrencyEntity::getDenomination) assertThat(currencies.stream().map(StandardCurrencyEntity::getDenomination)
.reduce(BigDecimal.ZERO, BigDecimal::add)).isEqualByComparingTo("1589.85"); .reduce(BigDecimal.ZERO, BigDecimal::add)).isEqualByComparingTo("1589.85");
assertThat(currencies.stream().map(StandardCurrencyEntity::getCurrencyId).distinct().count()).isEqualTo(27); assertThat(currencies.stream().map(StandardCurrencyEntity::getCurrencyId).distinct().count()).isEqualTo(27);
List<Long> currencyIds = currencies.stream().map(StandardCurrencyEntity::getId)
.collect(java.util.stream.Collectors.toList());
long batchId = standardCurrencyBatchMapper.selectList(null).get(0).getId();
mvc.perform(post(STANDARD_CURRENCY_BASE_PATH + "/steps/generate").header("Authorization", authorization)) mvc.perform(post(STANDARD_CURRENCY_BASE_PATH + "/steps/generate").header("Authorization", authorization))
.andExpect(status().isBadRequest()) .andExpect(status().isOk())
.andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("当前状态:GENERATED"))); .andExpect(jsonPath("$.data.status").value("GENERATED"))
.andExpect(jsonPath("$.data.currencies.length()").value(27));
assertThat(standardCurrencyBatchMapper.selectList(null)).hasSize(1);
assertThat(standardCurrencyBatchMapper.selectList(null).get(0).getId()).isEqualTo(batchId);
assertThat(standardCurrencyMapper.selectList(null)).hasSize(27); assertThat(standardCurrencyMapper.selectList(null)).hasSize(27);
assertThat(standardCurrencyMapper.selectList(null).stream().map(StandardCurrencyEntity::getId)
.collect(java.util.stream.Collectors.toList())).containsExactlyElementsOf(currencyIds);
} }
@Test @Test
@ -642,9 +793,9 @@ class TransactionInformationIdentifierControllerTest {
.contentType("application/json") .contentType("application/json")
.content("{\"originalText\":\"1589.85|ORG_3A4B5C6D7E8F|TXN_" .content("{\"originalText\":\"1589.85|ORG_3A4B5C6D7E8F|TXN_"
+ "7A8B9C0D1E2F3A4B5C6D7E8F9A0B1C2D3E4F5A6B7C8D9E0F1A2B3C4D5E6F\"}")) + "7A8B9C0D1E2F3A4B5C6D7E8F9A0B1C2D3E4F5A6B7C8D9E0F1A2B3C4D5E6F\"}"))
.andExpect(status().isBadRequest()) .andExpect(status().isNotFound())
.andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString( .andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString(
"请先接收步骤五额度请求报文"))); "当前没有额度请求记录")));
} }
@Test @Test

Loading…
Cancel
Save