代理租赁实现
This commit is contained in:
1 parent
1c0544afe0
commit
2a9f1c4c7c
38 files changed
+5824
-6
No files matched your search
@@ -37,3 +37,10 @@
|
|||||||
- sql/rent_init.sql
|
- sql/rent_init.sql
|
||||||
- docs/rental/schema-design.md
|
- docs/rental/schema-design.md
|
||||||
- docs/rental/table-functional-flows.md
|
- docs/rental/table-functional-flows.md
|
||||||
|
|
||||||
|
## 三端实现结论(2026-10-22)
|
||||||
|
|
||||||
|
- 当前工作区已实现后端、Vue及本地Node Agent,不再仅为设计文档。完整运行与接口说明见docs/rental/implementation.md。
|
||||||
|
- 普通TRON RPC不能提供任意确认区块的历史资源状态,自动交付核验依赖独立历史证明服务;缺失时必须人工隔离,不能以当前资源比率假装历史交付成功。
|
||||||
|
- 原交易未知时保留资金与SUN占位,恢复仅查询或重播原签名交易,不能创建替代交易。
|
||||||
|
- 本地验证结果与外部验收边界见docs/rental/validation-implementation.md;未对现有数据库或链上资产执行操作。
|
||||||
@@ -1,5 +1,18 @@
|
|||||||
# 工作记录
|
# 工作记录
|
||||||
|
|
||||||
|
## 三端功能实现(2026-10-22)
|
||||||
|
|
||||||
|
- 用户授权按 V2.2 实现前端、后端与本地 Agent Node,保持 JDK8 和清晰中文注释。
|
||||||
|
- 已新增事务仓储、四域HMAC/AES-GCM、订单冻结、供应商应收/手续费、退款/结算审批、钱包挑战、任务调度/回收/核验、WSS会话及回调队列实现。
|
||||||
|
- 当前工作区16个租赁API JS已经存在(用户新增),前端将按最新内容接业务接口。
|
||||||
|
- 三端主体已实现;16个管理页及3个用户页替换为统一业务组件,原页面备份在C:\Users\Administrator\AppData\Local\Temp\rental-vue-before-business-73daa005b1164f1283061eab6e6919b7。
|
||||||
|
- JDK8系统模块编译与管理端全依赖编译通过;第一轮后端10项、第二轮15项隔离测试通过;Agent10项测试通过;前端独立输出目录生产构建通过。
|
||||||
|
- 已修正MySQL JSON规范化后的任务HMAC原文、Socket旧会话fencing、未知构建禁止重建、本地落盘失败后重新fsync、失败扫描饥饿及BIGINT/USDT/UTC响应精度。
|
||||||
|
- 新增菜单SQL、外部配置profile、Agent环境模板和完整运行文档;不执行数据库初始化、主网或NILE广播。真实MySQL/浏览器TronLink/WSS公网/历史节点仍未联调。
|
||||||
|
- 首轮JDK8编译发现Trident地址类型与Base58方法差异,正在修正;尚未完成三端验证。
|
||||||
|
- 前端上轮删除13个无直接userId的用户CRUD页面,保留16个管理页面和3个用户页面;缺少租赁API JS。
|
||||||
|
- 复用当前计划,不查询 Git 历史,不操作真实链上交易或现有数据库。
|
||||||
|
|
||||||
## 设计审查
|
## 设计审查
|
||||||
|
|
||||||
- 已读取项目规则、15 表 SQL 及业务说明;仅以当前工作区为依据,无 Git 历史查询。
|
- 已读取项目规则、15 表 SQL 及业务说明;仅以当前工作区为依据,无 Git 历史查询。
|
||||||
@@ -31,3 +44,11 @@
|
|||||||
- 首轮机械删除误判注解中的{id}边界,已修正脚本并清理两类残片;静态检查确认每个无userId模块仅8个后台端点,有userId模块保留7个用户端点,所有端点均有权限注解。
|
- 首轮机械删除误判注解中的{id}边界,已修正脚本并清理两类残片;静态检查确认每个无userId模块仅8个后台端点,有userId模块保留7个用户端点,所有端点均有权限注解。
|
||||||
- 16模块158处方法引用存在性检查通过;13个无userId模块不再有isUser、getUserId/setUserId、checkUser等模板引用。
|
- 16模块158处方法引用存在性检查通过;13个无userId模块不再有isUser、getUserId/setUserId、checkUser等模板引用。
|
||||||
- 默认JDK17触发现有Lombok模块访问错误,切换JAVA_HOME=C:\Java\jdk1.8.0_481后,mvn -o -pl ruoyi-system -am -DskipTests compile -q退出0。
|
- 默认JDK17触发现有Lombok模块访问错误,切换JAVA_HOME=C:\Java\jdk1.8.0_481后,mvn -o -pl ruoyi-system -am -DskipTests compile -q退出0。
|
||||||
|
|
||||||
|
## 三端业务实现完成(2026-10-22)
|
||||||
|
|
||||||
|
- 新增租赁后端业务服务、JWT/HMAC入口、WSS任务通道、资金事务及独立链上核验;旧通用CRUD入口禁用,防止绕过业务规则。
|
||||||
|
- Vue统一业务组件接入16个运营及3个用户菜单;本地Node24 Agent实现加密持久化、先落盘再广播、原交易恢复及默认禁广播。
|
||||||
|
- 最终修正调度主键轮转及恢复失败退避,避免故障记录阻塞后续扫描;Java四空格格式整理,拆分多变量声明。
|
||||||
|
- JDK8后端回归88项,0失败、4项原有测试跳过;最终格式整理后租赁专项23项再次通过。Agent10项、Schema12项通过,Vue ESLint及生产构建通过。
|
||||||
|
- 运行说明implementation.md及验证记录validation-implementation.md已完成。没有执行数据库脚本或真实广播;MySQL、公网WSS、浏览器TronLink和NILE联调仍属部署验收边界,历史证明服务为外部依赖。
|
||||||
@@ -6,11 +6,26 @@
|
|||||||
|
|
||||||
## Next Step
|
## Next Step
|
||||||
|
|
||||||
已完成生成代码清理及JDK8编译验证,交付40个相关Java文件的修改。
|
三端实现及本地验证完成;实际数据库迁移、公网WSS及NILE端到端验收按部署说明执行。
|
||||||
|
|
||||||
## Current Phase
|
## Current Phase
|
||||||
|
|
||||||
全部完成(含生成代码清理)
|
Phase 7:验证和部署文档
|
||||||
|
|
||||||
|
### Phase 5: 业务后端与可靠任务
|
||||||
|
|
||||||
|
- **Status:** complete
|
||||||
|
- 实现应用/节点认证、钱包授权、资金事务、订单、调度、独立核验、回收、退款、结算与回调。
|
||||||
|
|
||||||
|
### Phase 6: 本地 Agent 与 Vue
|
||||||
|
|
||||||
|
- **Status:** complete
|
||||||
|
- 本地持久化原签名交易、默认禁广播、WSS 恢复;前端补齐 API、业务操作及权限。
|
||||||
|
|
||||||
|
### Phase 7: 验证和部署文档
|
||||||
|
|
||||||
|
- **Status:** complete
|
||||||
|
- JDK8 编译、资金/并发/恢复测试、前端构建及 Agent 测试;记录未获得外部环境的验证边界。
|
||||||
|
|
||||||
### Phase 1: 设计审查
|
### Phase 1: 设计审查
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
## 平台简介
|
## 平台简介
|
||||||
|
|
||||||
|
能量与带宽租赁模块:三端配置、业务API、Agent安装及验收边界见[租赁实现说明](docs/rental/implementation.md);初始化结构见[租赁SQL](sql/rent_init.sql),菜单权限见[租赁菜单SQL](sql/rent_menu.sql)。默认不启动租赁调度与节点通道,本地Agent默认禁止广播。
|
||||||
|
|
||||||
susdt是一套全部开源的快速开发平台,毫无保留给个人及企业免费使用。
|
susdt是一套全部开源的快速开发平台,毫无保留给个人及企业免费使用。
|
||||||
|
|
||||||
* 前端采用Vue、Element UI。
|
* 前端采用Vue、Element UI。
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
# 能量与带宽出租业务复核与修正 V2.2
|
# 能量与带宽出租业务复核与修正 V2.2
|
||||||
|
|
||||||
|
说明:本文保留设计复核阶段记录。后续新增的Java/Vue/Node.js实现、部署步骤及当前验证边界见[implementation.md](implementation.md),不把历史“未实现”陈述视为当前代码状态。
|
||||||
|
|
||||||
## 1. 结论与适用范围
|
## 1. 结论与适用范围
|
||||||
|
|
||||||
原 V2.1 的独立余额、供应商本地签名、链上独立核验、未知隔离、履约和回收分离方向可保留,但退款、人工付款、资源快照和多单回收存在实质缺口。V2.2 已在 [初始化 SQL](../../sql/rent_init.sql)、[主设计](schema-design.md) 和[逐表说明](table-functional-flows.md)中同步修正,表数由 15 增至 16。
|
原 V2.1 的独立余额、供应商本地签名、链上独立核验、未知隔离、履约和回收分离方向可保留,但退款、人工付款、资源快照和多单回收存在实质缺口。V2.2 已在 [初始化 SQL](../../sql/rent_init.sql)、[主设计](schema-design.md) 和[逐表说明](table-functional-flows.md)中同步修正,表数由 15 增至 16。
|
||||||
|
|||||||
@@ -0,0 +1,136 @@
|
|||||||
|
# 租赁模块三端实现与运行说明
|
||||||
|
|
||||||
|
本文对应当前工作区的 V2.2 实现。设计依据仍为 [schema-design.md](schema-design.md) 和 [rent_init.sql](../../sql/rent_init.sql)。代码交付不等于生产迁移或真实链上验收;本次没有修改现有数据库,没有执行任何真实广播。
|
||||||
|
|
||||||
|
## 1. 三端职责
|
||||||
|
|
||||||
|
| 端 | 入口 | 职责 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Java 8 后端 | `ruoyi-system/.../rental` | 归属及权限、钱包控制权、固定套餐、冻结与不可变流水、任务调度、独立核验、回收、退款、人工结算、持久回调 |
|
||||||
|
| Vue 2 前端 | `usdt-ui/src/views/rental` | 商户/供应商工作台与运营操作;原16个管理菜单和3个用户菜单路径保留,复用业务组件 |
|
||||||
|
| 本地 Node.js Agent | `rent-agent/src` | 主动WSS连接、双向签名心跳、加密可靠日志、钱包本地限制、只构建签名一次、原交易恢复 |
|
||||||
|
|
||||||
|
本地 Agent 使用 Node.js 24 和锁定版本的 TronWeb 6.0.4。这里的 Node 既是供应节点角色,也明确采用 Node.js 实现;不修改示例 JavaFX 钱包程序,不要求供应商运行完整TRON节点。
|
||||||
|
|
||||||
|
核心链路:商户下单冻结USDT → 后端按可信动态资源参数预留SUN → 推送冻结任务意图 → Agent先保存再ACK、复核后本地签名、原交易落盘后广播 → 云端独立核验 → 达标且未到期则扣款及记供应商净应收 → 到期按原SUN撤销 → 资源实际恢复后释放地址对占位。
|
||||||
|
|
||||||
|
生成器的 `/system/rentXxx` 接口已由 `RentalLegacyGuard` 拒绝,包括读取、导出及写入。这样既防止任意覆盖余额/状态,也防止旧凭证导出接口泄露密文。新页面使用 `/rental`,不要再调用旧CRUD。旧Service/Mapper保留作为已生成基础代码,业务链路不调用其任意修改方法。
|
||||||
|
|
||||||
|
## 2. 数据库、菜单和后端配置
|
||||||
|
|
||||||
|
1. 新环境检查MySQL5.7.8+/8.0配置后执行 `sql/rent_init.sql`。已有旧表不能靠 `IF NOT EXISTS` 升级,必须按实际结构和在途数据编写增量迁移;本次未运行脚本。
|
||||||
|
2. 执行 `sql/rent_menu.sql` 创建租赁工作台、16个运营查询菜单及按钮权限,不自动向任何现有角色授权。通过若依角色管理分配商户、供应商、运营、退款申请人、独立财务审批人。
|
||||||
|
3. 使用 JDK8;在 Spring Boot 配置中包含 `rental` profile,载入 `application-rental.yml`。通过环境变量注入配置。默认 `RENT_ENABLED=false`,不开调度或节点Socket。
|
||||||
|
4. `RENT_MASTER_KEY` 必须为外部生成的32字节随机密钥的Base64。不要使用测试代码中的零值密钥,也不要把实际值提交到仓库。`RENT_MASTER_KEY_VERSION` 标识当前版本;当前运行实例必须保留解密历史Secret所需的相同主密钥。本实现不自动迁移主密钥版本,换主密钥前须另行完成离线重封装。
|
||||||
|
5. 配置 `RENT_NILE_RPC` / `RENT_MAINNET_RPC`、可选 `RENT_RPC_KEY`,以及每个网络的租赁USDT收款地址 `RENT_NILE_DEPOSIT` / `RENT_MAINNET_DEPOSIT`。USDT合约地址复用 `TronServiceProvider.getServiceForNetwork()`,不随支付全局网络切换。
|
||||||
|
6. 单实例Socket入口启用 `RENT_ENABLED=true`,通过HTTPS反向代理暴露 `/node/v1/socket`。代理保留WebSocket Upgrade,读超时大于45秒,对API及Socket入口设置连接数和速率限制。首版不承诺跨实例Socket路由;数据库持久事实可以多worker争抢,但节点WSS须固定一个入口实例。
|
||||||
|
|
||||||
|
可在本地用以下命令生成随机主密钥,仅把输出放入安全配置:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
node -e "console.log(require('node:crypto').randomBytes(32).toString('base64'))"
|
||||||
|
```
|
||||||
|
|
||||||
|
UTC字段使用 `LocalDateTime` 显式按UTC写入,不改变支付业务的LOCAL JDBC连接时区。租赁HTTP响应把BIGINT和USDT转为字符串,防止浏览器浮点数丢精度;时间输出UTC ISO8601,响应设置 `Cache-Control: no-store`。
|
||||||
|
|
||||||
|
## 3. 首次开通流程
|
||||||
|
|
||||||
|
1. 商户进入租赁工作台,创建应用,开通所需网络的租赁账户,在凭证页为本人APP签发Secret并立即安全保存。充值发到配置的租赁收款地址后,运营填写原USDT交易哈希、Transfer日志序号及精确金额审核;后端独立校验合约、接收地址、金额及确认深度,同一日志不能给不同用户重复入账。
|
||||||
|
2. 供应商注册节点,运营用不同账号审核通过;供应商为本人NODE创建凭证。节点审核与连接在线是两个不同状态。
|
||||||
|
3. 供应商绑定公开钱包,TronLink切换到该地址,点击一次性消息验证。挑战绑定平台域、用户、钱包、网络、nonce及有效期;后端恢复地址并原子消费挑战。此步骤不广播、不收取验证费。
|
||||||
|
4. 运营审核钱包;供应商分别开启能量/带宽出租并设置SUN本金留存。平台不接受钱包私钥。Agent首版只支持owner权限单签,不自动处理多签或自定义active权限;不满足时拒绝执行。
|
||||||
|
5. 运营新增不可变套餐版本,显式填写正数量、正冗余、租期、售价、供应商毛收入、0至100之间的正手续费率及正费用预算,然后审核上架。改价新增版本,不覆盖旧订单快照。
|
||||||
|
6. Agent启动且同步完成后节点才ONLINE;对应钱包可信快照有效时才可调度。
|
||||||
|
|
||||||
|
## 4. Agent安装与恢复
|
||||||
|
|
||||||
|
在 `rent-agent` 目录执行:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
npm ci --ignore-scripts
|
||||||
|
node --env-file=.env src/index.js
|
||||||
|
```
|
||||||
|
|
||||||
|
复制 `.env.example` 为本机 `.env` 并填写。`.env`、`data` 和 `node_modules` 已忽略提交。私钥只留在本地;日志密钥 `RENT_JOURNAL_KEY` 必须与云端主密钥、API Secret分离。填写本人 `RENT_NODE_ID`、`RENT_NODE_NO`、NODE凭证、网络RPC和本地额度。默认 `RENT_ALLOW_BROADCAST=false`,任务会明确拒绝为未构建;供应商在本地审核后才可改为true并重新启动。平台无法替本地开启广播。
|
||||||
|
|
||||||
|
`RENT_MAX_SUN`、`RENT_MAX_FEE_SUN` 为每笔上限;`RENT_ENERGY_ENABLED` / `RENT_BANDWIDTH_ENABLED` 是本地独立出租开关,默认false,需供应商明确开启。关闭某类出租不阻止原授权本金回收,但全局广播关闭仍不广播。两个资源各有留存本金;另有 `RENT_TRX_RETAIN_SUN` 费用留存。Agent查询实时 `getTransactionFee`,用600字节保守预算检查原生交易费用,构建后再次限制实际原文和签名预留不超过预算字节;这是本地预算策略,不是协议的 `fee_limit` 硬上限。SDK无法精确表示的整数超过 `Number.MAX_SAFE_INTEGER` 时直接拒绝,绝不转成不精确数字广播。
|
||||||
|
|
||||||
|
本地 `journal.gcm` 保存完整原任务、原签名交易、txId和待ACK事件,使用AES-256-GCM;写临时文件、fsync、原子rename,成功后才ACK或广播。重复任务相同内容只恢复,内容变化拒绝。广播超时、断线、租约过期或重启均不能构造新交易;过期原交易只查询。无已保存交易的BUILDING/UNKNOWN保持隔离,不重新构建。未知不等于失败。
|
||||||
|
|
||||||
|
同一数据目录用 `agent.lock` 排除并发进程。正常关闭会先停止接单并等待RPC归档,再释放锁。崩溃保留锁:先确认原进程已退出、只有一套Agent使用该钱包、备份整个加密数据目录,再人工移除该精确锁文件后重启。不得删除日志“重置”任务。丢失日志密钥、签名交易或原Secret时停止接单并核对云端与链上,不按空记录重新执行。
|
||||||
|
|
||||||
|
凭证轮换时通过 `RENT_OLD_KEYS` 保留仍有在途任务的旧 `api_key:secret` JSON映射。云端新连接使用当前ACTIVE凭证,历史任务内层意图使用原凭证验签。REVOKED不再投递;历史链上独立核验继续进行。
|
||||||
|
|
||||||
|
## 5. HTTP业务接口
|
||||||
|
|
||||||
|
所有 `/rental` 接口使用若依JWT及明确 `rent:*` 权限,用户归属由服务端关联查询决定。分页每页50条,页码从1开始。
|
||||||
|
|
||||||
|
| 接口 | 功能 |
|
||||||
|
| --- | --- |
|
||||||
|
| `GET /rental/mine/{resource}` | 本人的应用、节点、钱包、订单、资金及公开上架套餐 |
|
||||||
|
| `GET /rental/manage/{resource}` | 运营16表脱敏查询,不返回Secret、签名或挑战 |
|
||||||
|
| `POST /rental/register/{app,node,wallet}` | 创建本人业务主体 |
|
||||||
|
| `POST /rental/credential/issue`、`/{id}/revoke` | 凭证轮换、吊销;Secret仅一次展示 |
|
||||||
|
| `POST /rental/wallet/{id}/{challenge,prove,policy}` | 钱包挑战、TronLink验证和出租策略 |
|
||||||
|
| `POST /rental/package`、`/status/{resource}/{id}` | 套餐版本创建及运营审核启停 |
|
||||||
|
| `POST /rental/account/open`、`/account/{id}/topup` | 开户及独立校验充值 |
|
||||||
|
| `POST /rental/order`、`/order/{id}/cancel` | 订单幂等冻结及未派单取消 |
|
||||||
|
| `POST /rental/order/{id}/refund`、`/refund/{id}/review` | 退款申请、不同账号审批和内部入账 |
|
||||||
|
| `POST /rental/settlement` | 按同一供应商同网络的订单净来源建立结算 |
|
||||||
|
| `POST /rental/settlement/{id}/{approve,reject,pay,unknown,confirm}` | 独立审批、原付款授权及核验;PAYING/UNKNOWN不可拒绝释放 |
|
||||||
|
| `POST /rental/wallet/{id}/refresh`、`/task/{id}/verify` | 可信快照和原交易独立核验 |
|
||||||
|
| `POST /rental/task/{id}/attach` | 只给原在途任务补充已独立核对的原交易哈希 |
|
||||||
|
| `POST /rental/order/{id}/resolve` | 仅MANUAL_REVIEW、HELD且回收DONE的异常单可解冻终结 |
|
||||||
|
| `POST /rental/webhook/{id}/retry` | 人工修正配置后重新投递DEAD事件,原编号和业务内容不变 |
|
||||||
|
| `GET /rental/reconcile?afterId=0` | 分批核对余额与不可变流水、钱包SUN预留与任务占用 |
|
||||||
|
|
||||||
|
每天UTC02:00自动进行账账核对,发现差异只告警,不直接修复余额或释放未知本金。运营可在资金账户/流水页主动执行完整分页核对。
|
||||||
|
|
||||||
|
结算 `pay` 先持久化唯一 `payout_no` 及本次收款地址,再由人工付款;重试返回原授权,不产生新的付款。`confirm` 根据原授权收款地址、账户网络及精确USDT金额核对原交易日志。后端不自动对外出金。
|
||||||
|
|
||||||
|
## 6. 外部商户签名接口
|
||||||
|
|
||||||
|
`POST /api/rental/v1/create`、`query`、`packages`,仅JSON,最多64KiB,不允许查询串。请求头为 `X-Rent-Key`、`X-Rent-Timestamp`(Unix毫秒)、`X-Rent-Nonce`、`X-Rent-Signature`。认证窗口前后60秒,nonce保留180秒后可清理。
|
||||||
|
|
||||||
|
签名原文用换行连接,末尾不加换行:
|
||||||
|
|
||||||
|
```text
|
||||||
|
RENT_HMAC_SHA256_V1
|
||||||
|
API
|
||||||
|
api_key
|
||||||
|
timestamp
|
||||||
|
nonce
|
||||||
|
POST
|
||||||
|
/api/rental/v1/create
|
||||||
|
SHA256(实际UTF-8请求体)的小写十六进制
|
||||||
|
```
|
||||||
|
|
||||||
|
使用Secret做HMAC-SHA256,输出小写64位十六进制。scope为API/NODE/TASK/WEBHOOK,不能互换;不共用支付MD5。下单字段:`package_id`、`merchant_order_no`、`receiver_address`,可选 `notify_url` 和与套餐一致的 `resource_type`。APP和用户从凭证推导。`query` 用 `merchant_order_no`;`packages` 用 `network`。
|
||||||
|
|
||||||
|
跨语言固定向量:Secret=`test-secret`、scope=`API`、key=`test-key`、timestamp=`1700000000123`、nonce=`abcdefghijklmnop`、method=`POST`、path=`/api/rental/v1/create`、body=`{"amount":"1.000000"}`,结果为 `47241a34f0813881384317eafbfc068dc9f7c6061a8fe269cb815e7820d48430`。此值仅用于测试,不是有效运行凭证。
|
||||||
|
|
||||||
|
回调使用相同请求头但scope=WEBHOOK;仅HTTPS公网443、无用户信息/fragment/query,实际DNS连接地址逐个检查,不跟随重定向。HTTP200且正文精确为 `ok` 才确认。最多10次,失败指数退避,终止为DEAD;每次新timestamp/nonce,业务event_no、payload和订单事件序号不变。商户按event_no去重并按序号识别乱序。无回调地址的事件直接确认,不发HTTP。
|
||||||
|
|
||||||
|
## 7. WSS协议与历史资源证明
|
||||||
|
|
||||||
|
通道 `/node/v1/socket`:CHALLENGE → AUTH → 签名AUTH_OK → 分页SYNC_STATE/SYNC_ACK → ONLINE。未同步不得接新单。外层帧的 `body` 是原始JSON字符串;信封含 `api_key,timestamp,nonce,body,signature`,NODE域、method=FRAME、path固定。body含type、方向、session_id、session_epoch、sequence、message_id、payload。双方向序号各自从1递增。每15秒签名PING/PONG,45秒超时断开,nonce重复或旧会话帧拒绝。
|
||||||
|
|
||||||
|
TASK_PUSH中保留稳定delivery_message_id、原api_key/intent/timestamp/nonce/signature。TASK域、method=PUSH、path=`/node/v1/task`。任务intent为按键排序的紧凑JSON;任务字段只含ASCII字符串/布尔值。MySQL JSON规范化后由后端按同一规则重建,再传输原意图,不改变授权内容。
|
||||||
|
|
||||||
|
Agent事件先落本地可靠队列,云端同事务以 `NODE:nodeId:eventId` 去重后RESULT_ACK。ACK只说明持久接收,ACCEPTED只说明本地接受,BUILT/BROADCASTED/RESULT只说明执行线索。云端另查交易合约、owner/receiver、网络、资源类型、非锁定、SUN、回执、确认深度和关系,不能凭节点消息扣款。
|
||||||
|
|
||||||
|
普通TRON RPC没有任意确认区块的资源历史查询,因此自动交付核验要求 `RENT_NILE_HISTORY` / `RENT_MAINNET_HISTORY` 指向运营自行部署、独立于供应商的可信历史证明服务。后端向 `/rental/resource-proof` POST `network,tx_id,block_height,owner,receiver,resource_type`,服务必须基于该实际区块状态返回:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"tx_id":"原交易哈希","block_height":123,"baseline_sun":0,"after_sun":1300000000,"total_limit":60000000,"total_weight":1000000}
|
||||||
|
```
|
||||||
|
|
||||||
|
示例参数不代表当前链。证明服务是外部基础设施契约,仓库没有伪造历史状态或用当前L/W替代的实现。**未配置历史服务时,可以确认真实委托,但订单转MANUAL_REVIEW、保留HELD资金并按原SUN回收,不自动记SUCCESS或供应商收入。** 交易已确认而交付不足、核验时已过期,同样人工隔离。可在确认回收DONE后通过受保护的resolve解冻。外部擅自变更委托关系会告警并转人工,不能任意释放关系占位。
|
||||||
|
|
||||||
|
## 8. 验证与边界
|
||||||
|
|
||||||
|
具体命令、结果及尚未验收的外部条件见 [validation-implementation.md](validation-implementation.md)。
|
||||||
|
|
||||||
|
已提供后端 `RentalBusinessTest` 与 Agent `test/agent.test.js`,分别覆盖资金/并发/状态机/协议和本地加密持久化/原交易恢复。H2测试从权威16表DDL只替换H2不支持的存储及JSON声明,保留字段与唯一键;不等同真实MySQL并发验收。Socket测试使用可控会话,不等同公网TLS/半开连接验收。前端构建输出到独立目录,不覆盖现有dist。
|
||||||
|
|
||||||
|
未接入项目数据库、实际部署WSS、真实TronLink浏览器签名、NILE委托/回收或历史证明服务进行联调;这些必须在专用测试环境验收后再启用业务。本实现不自动开放主网广播、不自动建设历史节点、不自动出金。
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# 能量/带宽出租表结构与业务流程 V2.2
|
# 能量/带宽出租表结构与业务流程 V2.2
|
||||||
|
|
||||||
状态:设计稿,未执行现有数据库变更、未实现租赁业务服务。当前权威 DDL 为 [rent_init.sql](../../sql/rent_init.sql),共 16 张 rent_ 表。V2.2 复核结果、事务协议、迁移要求和验收场景见 [业务复核与修正说明](business-review-v2.2.md),逐表说明见 [table-functional-flows.md](table-functional-flows.md)。本版不表示生产数据库已经迁移。
|
状态:V2.2设计基线;当前已新增后端、Vue及本地Node.js Agent实现,运行配置、接口与验证边界见[三端实现说明](implementation.md)。未执行现有数据库迁移或真实链上广播。当前权威 DDL 为 [rent_init.sql](../../sql/rent_init.sql),共16张表;历史设计复核见[业务复核与修正说明](business-review-v2.2.md),逐表说明见[table-functional-flows.md](table-functional-flows.md)。下文“本次仅设计”描述设计审查阶段,不替代当前实现记录。
|
||||||
|
|
||||||
## 1. 简化范围和保留边界
|
## 1. 简化范围和保留边界
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
## 1. 文档依据与业务范围
|
## 1. 文档依据与业务范围
|
||||||
|
|
||||||
本文依据 [rent_init.sql](../../sql/rent_init.sql) 及 [schema-design.md](schema-design.md) 的 V2.2 设计整理,覆盖全部 16 张 `rent_` 表。复核发现、并发协议和迁移要求见 [business-review-v2.2.md](business-review-v2.2.md)。本文描述设计约定,不代表数据库迁移、业务服务或链上执行已经完成。
|
本文依据 [rent_init.sql](../../sql/rent_init.sql) 及 [schema-design.md](schema-design.md) 的 V2.2 设计整理,覆盖全部16张表。复核发现、并发协议和迁移要求见 [business-review-v2.2.md](business-review-v2.2.md)。三端实现已新增,入口、配置及验证边界见[implementation.md](implementation.md);没有执行数据库迁移或真实链上广播。
|
||||||
|
|
||||||
业务范围:商户通过内部 USDT 余额购买固定能量或带宽套餐,平台选择供应商钱包,由供应商本地 Agent 签名广播,云端独立核验后扣款、确认供应商应收;租期结束再回收资源。充值和供应商付款由人工审核处理。
|
业务范围:商户通过内部 USDT 余额购买固定能量或带宽套餐,平台选择供应商钱包,由供应商本地 Agent 签名广播,云端独立核验后扣款、确认供应商应收;租期结束再回收资源。充值和供应商付款由人工审核处理。
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# 租赁三端实现验证记录
|
||||||
|
|
||||||
|
验证日期:2026-10-22。以当前工作区为准,不比较历史提交,不操作业务数据库,不执行真实链上广播。
|
||||||
|
|
||||||
|
## 已执行验证
|
||||||
|
|
||||||
|
| 范围 | 命令或方法 | 结果 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Java后端回归 | JDK8,`mvn -o -pl ruoyi-admin -am test -q` | 88项,0失败、0错误,4项原有手动/外网测试跳过 |
|
||||||
|
| 新增租赁业务 | `RentalBusinessTest` | 23项,覆盖资金事务、并发、退款/结算、认证、任务恢复及可控Socket |
|
||||||
|
| 本地Agent | Node24,`node --test test/agent.test.js` | 10项通过;`node --check src/index.js`通过 |
|
||||||
|
| Vue页面 | 新增API、租赁组件及原菜单包装页ESLint | 通过 |
|
||||||
|
| Vue生产构建 | `vue-cli-service build --mode production --dest D:/myprojects/usdt/.codex-rental-build` | 通过,仅既有Browserslist及体积提示;未覆盖原dist |
|
||||||
|
| SQL与文档 | `python docs/rental/check_schema.py` | 12项通过 |
|
||||||
|
|
||||||
|
后端完成回归后仅进行了变量声明拆分及格式整理,另对最终租赁代码重跑23项业务测试。调度采用主键轮转,避免无资源订单占满扫描窗口;资源恢复查询失败也推进重试时间,避免故障记录阻塞后续记录。
|
||||||
|
|
||||||
|
## 验证的实际边界
|
||||||
|
|
||||||
|
- H2事务与并发测试不等于真实MySQL隔离级别、锁等待和部署迁移验收。初始化及菜单SQL均未执行。
|
||||||
|
- 可控Socket测试不等于公网WSS、TLS代理、网络半开或真实供应商设备联调。
|
||||||
|
- 前端完成静态检查及生产构建,尚未完成真实浏览器TronLink及全链路人工验收。
|
||||||
|
- 尚未执行NILE或MAINNET真实委托、回收和USDT转账。
|
||||||
|
- 历史资源证明服务是外部依赖,仓库未实现历史节点基础设施。未配置时委托进入人工核对、保留冻结资金,不自动确认收入;实际回收完成后才允许受保护的解冻操作。
|
||||||
|
- 供应商私钥仅在本地Agent使用;广播默认关闭。退款为内部余额操作,外部结算付款由人工执行并核验原交易,不自动出金。
|
||||||
|
|
||||||
|
部署步骤及环境变量见 [implementation.md](implementation.md);Agent安装及本地限制见 [Agent README](../../../rent-agent/README.md)。启用前应在独立NILE环境完成上述外部联调。
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
# 通过spring.profiles.include=rental载入。本文件不存任何实际密钥或链上广播授权。
|
||||||
|
rental:
|
||||||
|
enabled: ${RENT_ENABLED:false}
|
||||||
|
domain: ${RENT_DOMAIN:localhost}
|
||||||
|
master-key: ${RENT_MASTER_KEY:}
|
||||||
|
master-key-version: ${RENT_MASTER_KEY_VERSION:v1}
|
||||||
|
confirmations: ${RENT_CONFIRMATIONS:19}
|
||||||
|
rpc:
|
||||||
|
nile: ${RENT_NILE_RPC:https://nile.trongrid.io}
|
||||||
|
mainnet: ${RENT_MAINNET_RPC:https://api.trongrid.io}
|
||||||
|
api-key: ${RENT_RPC_KEY:}
|
||||||
|
history:
|
||||||
|
nile: ${RENT_NILE_HISTORY:}
|
||||||
|
mainnet: ${RENT_MAINNET_HISTORY:}
|
||||||
|
deposit-address:
|
||||||
|
nile: ${RENT_NILE_DEPOSIT:}
|
||||||
|
mainnet: ${RENT_MAINNET_DEPOSIT:}
|
||||||
@@ -142,6 +142,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
|||||||
.antMatchers("/api/v1/wallet/**").permitAll()
|
.antMatchers("/api/v1/wallet/**").permitAll()
|
||||||
.antMatchers("/api/v1/order/**").permitAll()
|
.antMatchers("/api/v1/order/**").permitAll()
|
||||||
.antMatchers("/api/v1/payout/**").permitAll()
|
.antMatchers("/api/v1/payout/**").permitAll()
|
||||||
|
// 租赁商户及节点另用四域HMAC认证;绝不共用支付MD5签名。
|
||||||
|
.antMatchers("/api/rental/v1/**", "/node/v1/socket").permitAll()
|
||||||
.antMatchers("/api/telegram/webhook").permitAll()
|
.antMatchers("/api/telegram/webhook").permitAll()
|
||||||
.antMatchers("/system/demoUsdt/**").permitAll()
|
.antMatchers("/system/demoUsdt/**").permitAll()
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
|
|||||||
@@ -24,6 +24,22 @@
|
|||||||
</dependencies>
|
</dependencies>
|
||||||
</dependencyManagement>
|
</dependencyManagement>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
<!-- 租赁节点出站WebSocket协议,版本沿用Spring Boot依赖管理。 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-websocket</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.squareup.okhttp3</groupId>
|
||||||
|
<artifactId>okhttp</artifactId>
|
||||||
|
<version>3.14.9</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
<version>1.4.199</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
<!-- 钱包信封加密单元测试依赖,仅测试作用域。 -->
|
<!-- 钱包信封加密单元测试依赖,仅测试作用域。 -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ public class RentCredential extends BaseEntity
|
|||||||
private String apiKey;
|
private String apiKey;
|
||||||
|
|
||||||
/** AES-GCM加密封装的API Secret,含IV和tag;禁止返回或记录明文 */
|
/** AES-GCM加密封装的API Secret,含IV和tag;禁止返回或记录明文 */
|
||||||
@Excel(name = "AES-GCM加密封装的API Secret,含IV和tag;禁止返回或记录明文")
|
@com.fasterxml.jackson.annotation.JsonIgnore
|
||||||
private String apiSecret;
|
private String apiSecret;
|
||||||
|
|
||||||
/** 外部AES主密钥版本,不存主密钥 */
|
/** 外部AES主密钥版本,不存主密钥 */
|
||||||
@@ -184,7 +184,6 @@ public class RentCredential extends BaseEntity
|
|||||||
.append("ownerType", getOwnerType())
|
.append("ownerType", getOwnerType())
|
||||||
.append("ownerId", getOwnerId())
|
.append("ownerId", getOwnerId())
|
||||||
.append("apiKey", getApiKey())
|
.append("apiKey", getApiKey())
|
||||||
.append("apiSecret", getApiSecret())
|
|
||||||
.append("masterKeyVersion", getMasterKeyVersion())
|
.append("masterKeyVersion", getMasterKeyVersion())
|
||||||
.append("status", getStatus())
|
.append("status", getStatus())
|
||||||
.append("expiresAt", getExpiresAt())
|
.append("expiresAt", getExpiresAt())
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import static com.ruoyi.system.rental.RentalValues.*;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.ruoyi.common.core.domain.AjaxResult;
|
||||||
|
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
|
||||||
|
/** 商户HTTPS API,仅接受JSON POST;HMAC覆盖实际UTF-8请求体,禁止二次序列化验签。 */
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/rental/v1")
|
||||||
|
public class RentalApiController {
|
||||||
|
private final RentalIdentity identity;
|
||||||
|
private final RentalStore store;
|
||||||
|
private final RentalOrders orders;
|
||||||
|
private final ObjectMapper json;
|
||||||
|
|
||||||
|
public RentalApiController(
|
||||||
|
RentalIdentity identity, RentalStore store, RentalOrders orders, ObjectMapper json) {
|
||||||
|
this.identity = identity;
|
||||||
|
this.store = store;
|
||||||
|
this.orders = orders;
|
||||||
|
this.json = json;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping(value = "/{operation}", consumes = "application/json")
|
||||||
|
public AjaxResult execute(@PathVariable String operation, HttpServletRequest request)
|
||||||
|
throws Exception {
|
||||||
|
require(
|
||||||
|
Arrays.asList("create", "query", "packages").contains(operation)
|
||||||
|
&& request.getQueryString() == null,
|
||||||
|
"接口或查询参数不支持");
|
||||||
|
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||||
|
byte[] buffer = new byte[4096];
|
||||||
|
int size;
|
||||||
|
while ((size = request.getInputStream().read(buffer)) != -1) {
|
||||||
|
require(output.size() + size <= 65536, "请求体超过64KiB");
|
||||||
|
output.write(buffer, 0, size);
|
||||||
|
}
|
||||||
|
String body =
|
||||||
|
StandardCharsets.UTF_8
|
||||||
|
.newDecoder()
|
||||||
|
.onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
|
||||||
|
.decode(java.nio.ByteBuffer.wrap(output.toByteArray()))
|
||||||
|
.toString();
|
||||||
|
RentalJson.bounded(body);
|
||||||
|
Map<String, Object> credential =
|
||||||
|
identity.authenticate(
|
||||||
|
request.getHeader("X-Rent-Key"),
|
||||||
|
"APP",
|
||||||
|
"API",
|
||||||
|
Long.parseLong(request.getHeader("X-Rent-Timestamp")),
|
||||||
|
request.getHeader("X-Rent-Nonce"),
|
||||||
|
"POST",
|
||||||
|
request.getRequestURI(),
|
||||||
|
body,
|
||||||
|
request.getHeader("X-Rent-Signature"));
|
||||||
|
Map<String, Object> app = store.get("app", number(credential, "owner_id"), false);
|
||||||
|
require("ACTIVE".equals(text(app, "status")), "应用已禁用");
|
||||||
|
Map<String, Object> data =
|
||||||
|
json.readValue(body, new TypeReference<Map<String, Object>>() {});
|
||||||
|
if ("packages".equals(operation)) {
|
||||||
|
List<Map<String, Object>> products =
|
||||||
|
store.rows(
|
||||||
|
"SELECT"
|
||||||
|
+ " id,package_code,revision,name,network,resource_type,resource_quantity,duration_seconds,sale_amount"
|
||||||
|
+ " FROM rent_package WHERE status='ACTIVE' AND network=? ORDER BY"
|
||||||
|
+ " id",
|
||||||
|
network(input(data, "network", 16)));
|
||||||
|
return AjaxResult.success(products);
|
||||||
|
}
|
||||||
|
Map<String, Object> order;
|
||||||
|
if ("create".equals(operation)) {
|
||||||
|
order = orders.create(number(app, "id"), number(app, "user_id"), data);
|
||||||
|
} else {
|
||||||
|
order =
|
||||||
|
store.one(
|
||||||
|
"SELECT * FROM rent_order WHERE app_id=? AND merchant_order_no=?",
|
||||||
|
app.get("id"),
|
||||||
|
input(data, "merchant_order_no", 64));
|
||||||
|
require(order != null, "订单不存在");
|
||||||
|
}
|
||||||
|
return AjaxResult.success(
|
||||||
|
map(
|
||||||
|
"order_no",
|
||||||
|
order.get("order_no"),
|
||||||
|
"merchant_order_no",
|
||||||
|
order.get("merchant_order_no"),
|
||||||
|
"network",
|
||||||
|
order.get("network"),
|
||||||
|
"resource_type",
|
||||||
|
order.get("resource_type"),
|
||||||
|
"resource_quantity",
|
||||||
|
order.get("resource_quantity"),
|
||||||
|
"receiver_address",
|
||||||
|
order.get("receiver_address"),
|
||||||
|
"status",
|
||||||
|
order.get("status"),
|
||||||
|
"reclaim_status",
|
||||||
|
order.get("reclaim_status"),
|
||||||
|
"amount",
|
||||||
|
order.get("sale_amount"),
|
||||||
|
"refunded_amount",
|
||||||
|
order.get("refunded_amount")));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,308 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import static com.ruoyi.system.rental.RentalValues.*;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
import okhttp3.*;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.tron.trident.core.ApiWrapper;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 云端只读链上适配器,不持有私钥且不调用广播接口。 普通TRON RPC不提供任意历史资源状态;确认区块资源证明必须来自配置的受信历史节点。
|
||||||
|
* 缺少历史证据时保留真实交易与资金占位,禁止用当前参数冒充历史交付成功。
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class RentalChain {
|
||||||
|
@Value("${rental.rpc.nile:https://nile.trongrid.io}")
|
||||||
|
private String nile;
|
||||||
|
|
||||||
|
@Value("${rental.rpc.mainnet:https://api.trongrid.io}")
|
||||||
|
private String mainnet;
|
||||||
|
|
||||||
|
@Value("${rental.history.nile:}")
|
||||||
|
private String nileHistory;
|
||||||
|
|
||||||
|
@Value("${rental.history.mainnet:}")
|
||||||
|
private String mainHistory;
|
||||||
|
|
||||||
|
@Value("${rental.rpc.api-key:}")
|
||||||
|
private String apiKey;
|
||||||
|
|
||||||
|
@Value("${rental.confirmations:19}")
|
||||||
|
private long confirmations;
|
||||||
|
|
||||||
|
private final ObjectMapper json;
|
||||||
|
|
||||||
|
@org.springframework.beans.factory.annotation.Autowired
|
||||||
|
private com.ruoyi.system.service.TronServiceProvider tronServices;
|
||||||
|
|
||||||
|
private final OkHttpClient client =
|
||||||
|
new OkHttpClient.Builder()
|
||||||
|
.connectTimeout(5, TimeUnit.SECONDS)
|
||||||
|
.readTimeout(8, TimeUnit.SECONDS)
|
||||||
|
.callTimeout(12, TimeUnit.SECONDS)
|
||||||
|
.retryOnConnectionFailure(false)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
public RentalChain(ObjectMapper json) {
|
||||||
|
this.json = json;
|
||||||
|
}
|
||||||
|
|
||||||
|
public JsonNode call(String network, String path, Map<String, Object> body) {
|
||||||
|
return request("NILE".equals(network(network)) ? nile : mainnet, path, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonNode request(String base, String path, Map<String, Object> body) {
|
||||||
|
try {
|
||||||
|
Request request =
|
||||||
|
new Request.Builder()
|
||||||
|
.url(base + path)
|
||||||
|
.header("TRON-PRO-API-KEY", apiKey)
|
||||||
|
.post(
|
||||||
|
RequestBody.create(
|
||||||
|
MediaType.parse("application/json"),
|
||||||
|
json.writeValueAsString(body)))
|
||||||
|
.build();
|
||||||
|
try (Response response = client.newCall(request).execute()) {
|
||||||
|
return json.readTree(RentalHttp.body(response));
|
||||||
|
}
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new IllegalStateException("链上查询失败,保留原业务状态");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private long block(JsonNode row) {
|
||||||
|
return row.path("block_header").path("raw_data").path("number").asLong(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> snapshot(String network, String address) {
|
||||||
|
long before = block(call(network, "/wallet/getnowblock", map()));
|
||||||
|
JsonNode resources =
|
||||||
|
call(
|
||||||
|
network,
|
||||||
|
"/wallet/getaccountresource",
|
||||||
|
map("address", address, "visible", true));
|
||||||
|
long energy =
|
||||||
|
call(
|
||||||
|
network,
|
||||||
|
"/wallet/getcandelegatedmaxsize",
|
||||||
|
map("owner_address", address, "type", 1, "visible", true))
|
||||||
|
.path("max_size")
|
||||||
|
.asLong(-1);
|
||||||
|
long bandwidth =
|
||||||
|
call(
|
||||||
|
network,
|
||||||
|
"/wallet/getcandelegatedmaxsize",
|
||||||
|
map("owner_address", address, "type", 0, "visible", true))
|
||||||
|
.path("max_size")
|
||||||
|
.asLong(-1);
|
||||||
|
long after = block(call(network, "/wallet/getnowblock", map()));
|
||||||
|
require(
|
||||||
|
before >= 0 && before == after && energy >= 0 && bandwidth >= 0,
|
||||||
|
"快照跨区块或本金查询不完整,请重试");
|
||||||
|
Map<String, Object> result =
|
||||||
|
map(
|
||||||
|
"snapshot_block_height",
|
||||||
|
after,
|
||||||
|
"energy_delegatable_sun",
|
||||||
|
energy,
|
||||||
|
"bandwidth_delegatable_sun",
|
||||||
|
bandwidth,
|
||||||
|
"energy_available",
|
||||||
|
Math.max(
|
||||||
|
0,
|
||||||
|
resources.path("EnergyLimit").asLong()
|
||||||
|
- resources.path("EnergyUsed").asLong()),
|
||||||
|
"bandwidth_available",
|
||||||
|
Math.max(
|
||||||
|
0,
|
||||||
|
resources.path("NetLimit").asLong()
|
||||||
|
- resources.path("NetUsed").asLong()),
|
||||||
|
"total_energy_limit",
|
||||||
|
resources.path("TotalEnergyLimit").asLong(),
|
||||||
|
"total_energy_weight",
|
||||||
|
resources.path("TotalEnergyWeight").asLong(),
|
||||||
|
"total_bandwidth_limit",
|
||||||
|
resources.path("TotalNetLimit").asLong(),
|
||||||
|
"total_bandwidth_weight",
|
||||||
|
resources.path("TotalNetWeight").asLong(),
|
||||||
|
"snapshot_at",
|
||||||
|
now(),
|
||||||
|
"snapshot_expires_at",
|
||||||
|
after(15));
|
||||||
|
require(
|
||||||
|
number(result, "total_energy_limit") > 0
|
||||||
|
&& number(result, "total_energy_weight") > 0
|
||||||
|
&& number(result, "total_bandwidth_limit") > 0
|
||||||
|
&& number(result, "total_bandwidth_weight") > 0,
|
||||||
|
"全网参数不完整");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long relation(String network, String owner, String receiver, String resource) {
|
||||||
|
JsonNode rows =
|
||||||
|
call(
|
||||||
|
network,
|
||||||
|
"/wallet/getdelegatedresourcev2",
|
||||||
|
map("fromAddress", owner, "toAddress", receiver, "visible", true))
|
||||||
|
.path("delegatedResource");
|
||||||
|
long total = 0;
|
||||||
|
for (JsonNode row : rows) {
|
||||||
|
total =
|
||||||
|
Math.addExact(
|
||||||
|
total,
|
||||||
|
row.path(
|
||||||
|
"ENERGY".equals(resource)
|
||||||
|
? "frozen_balance_for_energy"
|
||||||
|
: "frozen_balance_for_bandwidth")
|
||||||
|
.asLong());
|
||||||
|
}
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 返回CONFIRMED仅代表交易真实成功;历史资源证据不足时delivery_proven=false。 */
|
||||||
|
public Map<String, Object> verify(
|
||||||
|
Map<String, Object> task, String txId, String owner, String receiver) {
|
||||||
|
require(txId.matches("[0-9a-fA-F]{64}"), "交易哈希无效");
|
||||||
|
String network = text(task, "network");
|
||||||
|
JsonNode tx = call(network, "/wallet/gettransactionbyid", map("value", txId));
|
||||||
|
JsonNode receipt =
|
||||||
|
call(network, "/walletsolidity/gettransactioninfobyid", map("value", txId));
|
||||||
|
require(
|
||||||
|
txId.equalsIgnoreCase(tx.path("txID").asText()) && receipt.has("blockNumber"),
|
||||||
|
"交易尚未确认,不能判定未执行");
|
||||||
|
long height = receipt.path("blockNumber").asLong();
|
||||||
|
long head = block(call(network, "/walletsolidity/getnowblock", map()));
|
||||||
|
require(head - height + 1 >= confirmations, "确认深度不足");
|
||||||
|
JsonNode contracts = tx.path("raw_data").path("contract");
|
||||||
|
require(contracts.size() == 1, "交易合约数量异常");
|
||||||
|
JsonNode contract = contracts.get(0);
|
||||||
|
JsonNode value = contract.path("parameter").path("value");
|
||||||
|
String expected =
|
||||||
|
"DELEGATE".equals(text(task, "task_type"))
|
||||||
|
? "DelegateResourceContract"
|
||||||
|
: "UnDelegateResourceContract";
|
||||||
|
require(
|
||||||
|
expected.equals(contract.path("type").asText())
|
||||||
|
&& !value.path("lock").asBoolean(false)
|
||||||
|
&& contract.path("Permission_id").asInt(0) == 0
|
||||||
|
&& hexAddress(owner).equalsIgnoreCase(value.path("owner_address").asText())
|
||||||
|
&& hexAddress(receiver)
|
||||||
|
.equalsIgnoreCase(value.path("receiver_address").asText())
|
||||||
|
&& number(task, "delegate_sun") == value.path("balance").asLong()
|
||||||
|
&& text(task, "resource_type")
|
||||||
|
.equals(value.path("resource").asText("BANDWIDTH")),
|
||||||
|
"链上交易参数与任务意图不符");
|
||||||
|
require(tx.path("ret").size() == 1, "缺少执行回执");
|
||||||
|
if (!"SUCCESS".equals(tx.path("ret").get(0).path("contractRet").asText())) {
|
||||||
|
return map("status", "FAILED");
|
||||||
|
}
|
||||||
|
long after = relation(network, owner, receiver, text(task, "resource_type"));
|
||||||
|
boolean delegate = "DELEGATE".equals(text(task, "task_type"));
|
||||||
|
require(after == (delegate ? number(task, "delegate_sun") : 0), "当前地址对关系与原委托本金不符,需要人工核对");
|
||||||
|
Map<String, Object> result =
|
||||||
|
map(
|
||||||
|
"status",
|
||||||
|
"CONFIRMED",
|
||||||
|
"block_height",
|
||||||
|
height,
|
||||||
|
"block_time",
|
||||||
|
java.time.LocalDateTime.ofInstant(
|
||||||
|
java.time.Instant.ofEpochMilli(
|
||||||
|
receipt.path("blockTimeStamp").asLong()),
|
||||||
|
java.time.ZoneOffset.UTC),
|
||||||
|
"after_sun",
|
||||||
|
after,
|
||||||
|
"delivery_proven",
|
||||||
|
!delegate);
|
||||||
|
String history = "NILE".equals(network) ? nileHistory : mainHistory;
|
||||||
|
if (delegate && !history.isEmpty()) {
|
||||||
|
JsonNode proof =
|
||||||
|
request(
|
||||||
|
history,
|
||||||
|
"/rental/resource-proof",
|
||||||
|
map(
|
||||||
|
"network",
|
||||||
|
network,
|
||||||
|
"tx_id",
|
||||||
|
txId,
|
||||||
|
"block_height",
|
||||||
|
height,
|
||||||
|
"owner",
|
||||||
|
owner,
|
||||||
|
"receiver",
|
||||||
|
receiver,
|
||||||
|
"resource_type",
|
||||||
|
text(task, "resource_type")));
|
||||||
|
require(
|
||||||
|
height == proof.path("block_height").asLong(-1)
|
||||||
|
&& txId.equalsIgnoreCase(proof.path("tx_id").asText())
|
||||||
|
&& proof.path("baseline_sun").asLong(-1) == 0
|
||||||
|
&& proof.path("after_sun").asLong(-1) == number(task, "delegate_sun"),
|
||||||
|
"历史关系证据不匹配");
|
||||||
|
long limit = proof.path("total_limit").asLong(),
|
||||||
|
weight = proof.path("total_weight").asLong();
|
||||||
|
result.put("verified_total_limit", limit);
|
||||||
|
result.put("verified_total_weight", weight);
|
||||||
|
result.put(
|
||||||
|
"verified_resource_quantity",
|
||||||
|
quantity(number(task, "delegate_sun"), limit, weight));
|
||||||
|
result.put("delivery_proven", true);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String hexAddress(String address) {
|
||||||
|
return ApiWrapper.toHex(ApiWrapper.parseAddress(address));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 人工充值/付款依据必须由配置网络的USDT Transfer日志独立核对。 */
|
||||||
|
public Map<String, Object> transfer(
|
||||||
|
String network, String txId, int index, String to, BigDecimal expected) {
|
||||||
|
network(network);
|
||||||
|
RentalOrders.address(to);
|
||||||
|
require(index >= 0 && txId.matches("[0-9a-fA-F]{64}"), "付款凭据无效");
|
||||||
|
JsonNode receipt =
|
||||||
|
call(network, "/walletsolidity/gettransactioninfobyid", map("value", txId));
|
||||||
|
require(
|
||||||
|
receipt.has("blockNumber")
|
||||||
|
&& block(call(network, "/walletsolidity/getnowblock", map()))
|
||||||
|
- receipt.path("blockNumber").asLong()
|
||||||
|
+ 1
|
||||||
|
>= confirmations
|
||||||
|
&& receipt.path("log").size() > index,
|
||||||
|
"付款未确认或日志不存在");
|
||||||
|
JsonNode log = receipt.path("log").get(index);
|
||||||
|
String contract = tronServices.getServiceForNetwork(network).contractAddress();
|
||||||
|
require(
|
||||||
|
hexAddress(contract).substring(2).equalsIgnoreCase(log.path("address").asText())
|
||||||
|
&& log.path("topics").size() == 3
|
||||||
|
&& "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
|
||||||
|
.equalsIgnoreCase(log.path("topics").get(0).asText())
|
||||||
|
&& log.path("topics")
|
||||||
|
.get(2)
|
||||||
|
.asText()
|
||||||
|
.endsWith(hexAddress(to).substring(2).toLowerCase(Locale.ROOT))
|
||||||
|
&& new BigDecimal(new java.math.BigInteger(log.path("data").asText(), 16))
|
||||||
|
.movePointLeft(6)
|
||||||
|
.compareTo(expected)
|
||||||
|
== 0
|
||||||
|
&& !"FAILED".equals(receipt.path("result").asText())
|
||||||
|
&& "SUCCESS"
|
||||||
|
.equals(receipt.path("receipt").path("result").asText("SUCCESS")),
|
||||||
|
"USDT付款日志不匹配");
|
||||||
|
return map(
|
||||||
|
"reference",
|
||||||
|
network + ":" + txId.toLowerCase(Locale.ROOT) + ":" + index,
|
||||||
|
"receipt",
|
||||||
|
receipt);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,354 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import static com.ruoyi.system.rental.RentalValues.*;
|
||||||
|
|
||||||
|
import com.ruoyi.common.core.domain.AjaxResult;
|
||||||
|
import com.ruoyi.common.utils.SecurityUtils;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** 登录业务入口。输入仅提取命令字段,不把客户端对象直接映射为数据库实体。 */
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/rental")
|
||||||
|
public class RentalController {
|
||||||
|
private final RentalStore store;
|
||||||
|
private final RentalProvisioning provisioning;
|
||||||
|
private final RentalIdentity identity;
|
||||||
|
private final RentalOrders orders;
|
||||||
|
private final RentalFunds funds;
|
||||||
|
private final RentalReviews reviews;
|
||||||
|
private final RentalTasks tasks;
|
||||||
|
private final RentalChain chain;
|
||||||
|
private final RentalQueries queries;
|
||||||
|
|
||||||
|
@Value("${rental.deposit-address.nile:}")
|
||||||
|
private String nileDeposit;
|
||||||
|
|
||||||
|
@Value("${rental.deposit-address.mainnet:}")
|
||||||
|
private String mainDeposit;
|
||||||
|
|
||||||
|
@org.springframework.beans.factory.annotation.Autowired
|
||||||
|
private RentalReconciliation reconciliation;
|
||||||
|
|
||||||
|
public RentalController(
|
||||||
|
RentalStore store,
|
||||||
|
RentalProvisioning provisioning,
|
||||||
|
RentalIdentity identity,
|
||||||
|
RentalOrders orders,
|
||||||
|
RentalFunds funds,
|
||||||
|
RentalReviews reviews,
|
||||||
|
RentalTasks tasks,
|
||||||
|
RentalChain chain,
|
||||||
|
RentalQueries queries) {
|
||||||
|
this.store = store;
|
||||||
|
this.provisioning = provisioning;
|
||||||
|
this.identity = identity;
|
||||||
|
this.orders = orders;
|
||||||
|
this.funds = funds;
|
||||||
|
this.reviews = reviews;
|
||||||
|
this.tasks = tasks;
|
||||||
|
this.chain = chain;
|
||||||
|
this.queries = queries;
|
||||||
|
}
|
||||||
|
|
||||||
|
private long user() {
|
||||||
|
Long user = SecurityUtils.getUserId();
|
||||||
|
require(user != null, "请先登录");
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/mine/{resource}")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:portal:view')")
|
||||||
|
public AjaxResult mine(
|
||||||
|
@PathVariable String resource, @RequestParam(defaultValue = "1") int page) {
|
||||||
|
return AjaxResult.success(queries.list(resource, user(), page));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/manage/{resource}")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:manage:list')")
|
||||||
|
public AjaxResult manage(
|
||||||
|
@PathVariable String resource, @RequestParam(defaultValue = "1") int page) {
|
||||||
|
return AjaxResult.success(queries.list(resource, null, page));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/register/{resource}")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:portal:register')")
|
||||||
|
public AjaxResult register(
|
||||||
|
@PathVariable String resource, @RequestBody Map<String, Object> body) {
|
||||||
|
return AjaxResult.success(provisioning.create(resource, body, user()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/credential/issue")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:credential:issue')")
|
||||||
|
public AjaxResult issue(@RequestBody Map<String, Object> body) {
|
||||||
|
return AjaxResult.success(
|
||||||
|
identity.issue(input(body, "owner_type", 8), number(body, "owner_id"), user()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/credential/{id}/revoke")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:credential:issue')")
|
||||||
|
public AjaxResult revoke(@PathVariable long id) {
|
||||||
|
identity.revoke(id, user());
|
||||||
|
return AjaxResult.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/wallet/{id}/challenge")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:wallet:bind')")
|
||||||
|
public AjaxResult challenge(@PathVariable long id) {
|
||||||
|
return AjaxResult.success(provisioning.challenge(id, user()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/wallet/{id}/prove")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:wallet:bind')")
|
||||||
|
public AjaxResult prove(@PathVariable long id, @RequestBody Map<String, Object> body) {
|
||||||
|
provisioning.prove(id, input(body, "nonce", 64), input(body, "signature", 256), user());
|
||||||
|
return AjaxResult.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/wallet/{id}/policy")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:wallet:bind')")
|
||||||
|
public AjaxResult policy(@PathVariable long id, @RequestBody Map<String, Object> body) {
|
||||||
|
provisioning.policy(id, body, user());
|
||||||
|
return AjaxResult.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/package")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:package:edit')")
|
||||||
|
public AjaxResult product(@RequestBody Map<String, Object> body) {
|
||||||
|
return AjaxResult.success(provisioning.product(body, user()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/status/{resource}/{id}")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:manage:audit')")
|
||||||
|
public AjaxResult status(
|
||||||
|
@PathVariable String resource,
|
||||||
|
@PathVariable long id,
|
||||||
|
@RequestBody Map<String, Object> body) {
|
||||||
|
provisioning.status(
|
||||||
|
resource, id, input(body, "status", 32), user(), input(body, "reason", 512));
|
||||||
|
return AjaxResult.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/order")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:order:create')")
|
||||||
|
public AjaxResult order(@RequestBody Map<String, Object> body) {
|
||||||
|
Map<String, Object> order = orders.create(number(body, "app_id"), user(), body);
|
||||||
|
return AjaxResult.success(
|
||||||
|
map(
|
||||||
|
"id",
|
||||||
|
order.get("id"),
|
||||||
|
"order_no",
|
||||||
|
order.get("order_no"),
|
||||||
|
"status",
|
||||||
|
order.get("status")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/order/{id}/cancel")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:order:create')")
|
||||||
|
public AjaxResult cancel(@PathVariable long id) {
|
||||||
|
orders.cancel(id, user());
|
||||||
|
return AjaxResult.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/account/open")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:portal:register')")
|
||||||
|
public AjaxResult account(@RequestBody Map<String, Object> body) {
|
||||||
|
return AjaxResult.success(funds.account(user(), input(body, "network", 16)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/account/{id}/topup")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:account:topup')")
|
||||||
|
public AjaxResult topup(@PathVariable long id, @RequestBody Map<String, Object> body) {
|
||||||
|
Map<String, Object> account = store.get("account", id, false);
|
||||||
|
String network = text(account, "network");
|
||||||
|
String deposit = "NILE".equals(network) ? nileDeposit : mainDeposit;
|
||||||
|
require(!deposit.isEmpty(), "尚未配置该网络租赁充值收款地址");
|
||||||
|
java.math.BigDecimal amount = money(body.get("amount"));
|
||||||
|
require(amount.signum() > 0, "充值金额必须大于0");
|
||||||
|
Map<String, Object> proof =
|
||||||
|
chain.transfer(
|
||||||
|
network,
|
||||||
|
input(body, "tx_id", 64),
|
||||||
|
(int) number(body, "log_index"),
|
||||||
|
deposit,
|
||||||
|
amount);
|
||||||
|
String reason = input(body, "reason", 512);
|
||||||
|
long actor = user();
|
||||||
|
tasks.tx(
|
||||||
|
() -> {
|
||||||
|
funds.post(
|
||||||
|
id,
|
||||||
|
"TOPUP:" + text(proof, "reference"),
|
||||||
|
"TOPUP",
|
||||||
|
amount,
|
||||||
|
ZERO,
|
||||||
|
ZERO,
|
||||||
|
ZERO,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
actor,
|
||||||
|
text(proof, "reference"),
|
||||||
|
reason);
|
||||||
|
store.event("ACCOUNT", id, "TOPUP", actor, reason);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
return AjaxResult.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/order/{id}/refund")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:refund:create')")
|
||||||
|
public AjaxResult refund(@PathVariable long id, @RequestBody Map<String, Object> body) {
|
||||||
|
return AjaxResult.success(reviews.refund(id, body, user()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/refund/{id}/review")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:refund:approve')")
|
||||||
|
public AjaxResult reviewRefund(@PathVariable long id, @RequestBody Map<String, Object> body) {
|
||||||
|
require(body.get("approve") instanceof Boolean, "必须明确审批结果");
|
||||||
|
reviews.approveRefund(id, Boolean.TRUE.equals(body.get("approve")), user());
|
||||||
|
return AjaxResult.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/settlement")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:settlement:create')")
|
||||||
|
public AjaxResult settlement(@RequestBody Map<String, Object> body) {
|
||||||
|
require(body.get("order_ids") instanceof List, "缺少来源订单");
|
||||||
|
List<Long> ids = new ArrayList<>();
|
||||||
|
for (Object value : (List<?>) body.get("order_ids")) {
|
||||||
|
ids.add(Long.valueOf(value.toString()));
|
||||||
|
}
|
||||||
|
return AjaxResult.success(reviews.settlement(ids, user()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/settlement/{id}/{action}")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:settlement:approve')")
|
||||||
|
public AjaxResult settlementAction(
|
||||||
|
@PathVariable long id,
|
||||||
|
@PathVariable String action,
|
||||||
|
@RequestBody Map<String, Object> body) {
|
||||||
|
String reason = input(body, "reason", 512);
|
||||||
|
long actor = user();
|
||||||
|
if ("confirm".equals(action)) {
|
||||||
|
Map<String, Object> row = store.get("settlement", id, false),
|
||||||
|
account = store.get("account", number(row, "account_id"), false);
|
||||||
|
Map<String, Object> authorization;
|
||||||
|
try {
|
||||||
|
authorization =
|
||||||
|
new com.fasterxml.jackson.databind.ObjectMapper()
|
||||||
|
.readValue(text(row, "payment_evidence"), Map.class);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new IllegalArgumentException("缺少原付款授权收款地址");
|
||||||
|
}
|
||||||
|
Map<String, Object> proof =
|
||||||
|
chain.transfer(
|
||||||
|
text(account, "network"),
|
||||||
|
input(body, "tx_id", 64),
|
||||||
|
(int) number(body, "log_index"),
|
||||||
|
text(authorization, "receiver_address"),
|
||||||
|
amount(row, "amount"));
|
||||||
|
reviews.paid(id, text(proof, "reference"), orders.encode(proof), actor);
|
||||||
|
return AjaxResult.success();
|
||||||
|
}
|
||||||
|
return AjaxResult.success(
|
||||||
|
tasks.tx(
|
||||||
|
() -> {
|
||||||
|
Map<String, Object> row = reviews.transition(id, action, actor, reason);
|
||||||
|
if ("pay".equals(action) && row.get("payment_evidence") == null) {
|
||||||
|
String receiver = input(body, "receiver_address", 64);
|
||||||
|
RentalOrders.address(receiver);
|
||||||
|
store.update(
|
||||||
|
"settlement",
|
||||||
|
id,
|
||||||
|
map(
|
||||||
|
"payment_evidence",
|
||||||
|
orders.encode(
|
||||||
|
map(
|
||||||
|
"receiver_address",
|
||||||
|
receiver,
|
||||||
|
"payout_no",
|
||||||
|
text(row, "payout_no")))));
|
||||||
|
row = store.get("settlement", id, false);
|
||||||
|
}
|
||||||
|
return row;
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/wallet/{id}/refresh")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:manage:audit')")
|
||||||
|
public AjaxResult refresh(@PathVariable long id) {
|
||||||
|
tasks.refresh(id);
|
||||||
|
return AjaxResult.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/task/{id}/verify")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:manage:audit')")
|
||||||
|
public AjaxResult verify(@PathVariable long id) {
|
||||||
|
tasks.verify(id);
|
||||||
|
return AjaxResult.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/task/{id}/attach")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:manage:audit')")
|
||||||
|
public AjaxResult attach(@PathVariable long id, @RequestBody Map<String, Object> body) {
|
||||||
|
tasks.attach(id, input(body, "tx_id", 64), user(), input(body, "reason", 512));
|
||||||
|
return AjaxResult.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/order/{id}/resolve")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:manage:audit')")
|
||||||
|
public AjaxResult resolve(@PathVariable long id, @RequestBody Map<String, Object> body) {
|
||||||
|
tasks.resolveRecovered(id, user(), input(body, "reason", 512));
|
||||||
|
return AjaxResult.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/webhook/{id}/retry")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:manage:audit')")
|
||||||
|
public AjaxResult retryWebhook(@PathVariable long id, @RequestBody Map<String, Object> body) {
|
||||||
|
String reason = input(body, "reason", 512);
|
||||||
|
long actor = user();
|
||||||
|
tasks.tx(
|
||||||
|
() -> {
|
||||||
|
Map<String, Object> row = store.get("webhook", id, true);
|
||||||
|
require("DEAD".equals(text(row, "status")), "只允许人工重新投递已终止的事件");
|
||||||
|
store.event(
|
||||||
|
"ORDER",
|
||||||
|
number(row, "order_id"),
|
||||||
|
"RETRY_WEBHOOK",
|
||||||
|
actor,
|
||||||
|
reason + ";原重试次数=" + text(row, "attempt_count"));
|
||||||
|
store.update(
|
||||||
|
"webhook",
|
||||||
|
id,
|
||||||
|
map(
|
||||||
|
"status",
|
||||||
|
"PENDING",
|
||||||
|
"attempt_count",
|
||||||
|
0,
|
||||||
|
"next_attempt_at",
|
||||||
|
now(),
|
||||||
|
"lock_owner",
|
||||||
|
null,
|
||||||
|
"lock_until",
|
||||||
|
null));
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
return AjaxResult.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/reconcile")
|
||||||
|
@PreAuthorize("@ss.hasPermi('rent:manage:audit')")
|
||||||
|
public AjaxResult reconcile(@RequestParam(defaultValue = "0") long afterId) {
|
||||||
|
require(afterId >= 0, "核对游标不能为负");
|
||||||
|
return AjaxResult.success(
|
||||||
|
map(
|
||||||
|
"accounts",
|
||||||
|
reconciliation.check(afterId),
|
||||||
|
"reservations",
|
||||||
|
reconciliation.reservations()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import static com.ruoyi.system.rental.RentalValues.*;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.util.Base64;
|
||||||
|
|
||||||
|
import javax.crypto.Cipher;
|
||||||
|
import javax.crypto.Mac;
|
||||||
|
import javax.crypto.spec.GCMParameterSpec;
|
||||||
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
|
|
||||||
|
/** HMAC四域隔离和Secret信封加密。主密钥仅通过外部配置注入,缺失时拒绝签发。 */
|
||||||
|
@Component
|
||||||
|
public class RentalCrypto {
|
||||||
|
@Value("${rental.master-key:}")
|
||||||
|
private String masterKey;
|
||||||
|
|
||||||
|
private static final SecureRandom RANDOM = new SecureRandom();
|
||||||
|
|
||||||
|
public static String sha256(String body) {
|
||||||
|
try {
|
||||||
|
return hex(
|
||||||
|
MessageDigest.getInstance("SHA-256")
|
||||||
|
.digest(body.getBytes(StandardCharsets.UTF_8)));
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new IllegalStateException("摘要计算失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String sign(
|
||||||
|
String secret,
|
||||||
|
String scope,
|
||||||
|
String key,
|
||||||
|
long timestamp,
|
||||||
|
String nonce,
|
||||||
|
String method,
|
||||||
|
String path,
|
||||||
|
String body) {
|
||||||
|
for (String value : new String[] {scope, key, nonce, method, path}) {
|
||||||
|
require(value != null && !value.contains("\n") && !value.contains("\r"), "签名字段非法");
|
||||||
|
}
|
||||||
|
String plain =
|
||||||
|
String.join(
|
||||||
|
"\n",
|
||||||
|
"RENT_HMAC_SHA256_V1",
|
||||||
|
scope,
|
||||||
|
key,
|
||||||
|
Long.toString(timestamp),
|
||||||
|
nonce,
|
||||||
|
method,
|
||||||
|
path,
|
||||||
|
sha256(body));
|
||||||
|
try {
|
||||||
|
Mac mac = Mac.getInstance("HmacSHA256");
|
||||||
|
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
|
||||||
|
return hex(mac.doFinal(plain.getBytes(StandardCharsets.UTF_8)));
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new IllegalStateException("签名计算失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean equal(String expected, String actual) {
|
||||||
|
return actual != null
|
||||||
|
&& MessageDigest.isEqual(
|
||||||
|
expected.getBytes(StandardCharsets.US_ASCII),
|
||||||
|
actual.getBytes(StandardCharsets.US_ASCII));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String random() {
|
||||||
|
byte[] bytes = new byte[32];
|
||||||
|
RANDOM.nextBytes(bytes);
|
||||||
|
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String encrypt(String secret) {
|
||||||
|
return crypt(secret, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String decrypt(String value) {
|
||||||
|
return crypt(value, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String crypt(String value, boolean encrypt) {
|
||||||
|
try {
|
||||||
|
byte[] key = Base64.getDecoder().decode(masterKey);
|
||||||
|
require(key.length == 32, "租赁主密钥必须是Base64编码的32字节密钥");
|
||||||
|
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||||
|
if (encrypt) {
|
||||||
|
byte[] iv = new byte[12];
|
||||||
|
RANDOM.nextBytes(iv);
|
||||||
|
cipher.init(
|
||||||
|
Cipher.ENCRYPT_MODE,
|
||||||
|
new SecretKeySpec(key, "AES"),
|
||||||
|
new GCMParameterSpec(128, iv));
|
||||||
|
return Base64.getEncoder().encodeToString(iv)
|
||||||
|
+ "."
|
||||||
|
+ Base64.getEncoder()
|
||||||
|
.encodeToString(
|
||||||
|
cipher.doFinal(value.getBytes(StandardCharsets.UTF_8)));
|
||||||
|
}
|
||||||
|
String[] parts = value.split("\\.");
|
||||||
|
require(parts.length == 2, "凭证格式错误");
|
||||||
|
cipher.init(
|
||||||
|
Cipher.DECRYPT_MODE,
|
||||||
|
new SecretKeySpec(key, "AES"),
|
||||||
|
new GCMParameterSpec(128, Base64.getDecoder().decode(parts[0])));
|
||||||
|
return new String(
|
||||||
|
cipher.doFinal(Base64.getDecoder().decode(parts[1])), StandardCharsets.UTF_8);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new IllegalStateException("租赁凭证加解密失败,请检查外部主密钥配置");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String hex(byte[] bytes) {
|
||||||
|
StringBuilder result = new StringBuilder(bytes.length * 2);
|
||||||
|
for (byte value : bytes) {
|
||||||
|
result.append(String.format("%02x", value & 255));
|
||||||
|
}
|
||||||
|
return result.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import com.ruoyi.common.core.domain.AjaxResult;
|
||||||
|
|
||||||
|
import org.springframework.dao.DataAccessException;
|
||||||
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
|
|
||||||
|
/** 租赁错误不包含SQL、Secret、认证原文或底层RPC响应。 */
|
||||||
|
@RestControllerAdvice(basePackageClasses = RentalController.class)
|
||||||
|
@org.springframework.core.annotation.Order(org.springframework.core.Ordered.HIGHEST_PRECEDENCE)
|
||||||
|
public class RentalErrors {
|
||||||
|
@ExceptionHandler(IllegalArgumentException.class)
|
||||||
|
public AjaxResult invalid(IllegalArgumentException exception) {
|
||||||
|
return AjaxResult.error(400, exception.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(IllegalStateException.class)
|
||||||
|
public AjaxResult state(IllegalStateException exception) {
|
||||||
|
return AjaxResult.error(409, exception.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(DataAccessException.class)
|
||||||
|
public AjaxResult database(DataAccessException exception) {
|
||||||
|
return AjaxResult.error(409, "租赁记录冲突或数据库结构未就绪,请核对状态后重试");
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(org.springframework.security.access.AccessDeniedException.class)
|
||||||
|
public AjaxResult denied(org.springframework.security.access.AccessDeniedException exception) {
|
||||||
|
return AjaxResult.error(403, "缺少租赁操作权限");
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(Exception.class)
|
||||||
|
public AjaxResult unexpected(Exception exception) {
|
||||||
|
return AjaxResult.error(500, "租赁操作暂未完成,请保留业务编号并检查配置或运行状态");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import static com.ruoyi.system.rental.RentalValues.*;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/** 资金统一入口。所有余额变化与不可变流水同事务;不提供任意金额覆盖接口。 调用方先锁业务主记录,再按账户ID升序加锁,避免商户同时也是供应商时反向锁死。 */
|
||||||
|
@Service
|
||||||
|
public class RentalFunds {
|
||||||
|
private final RentalStore store;
|
||||||
|
|
||||||
|
public RentalFunds(RentalStore store) {
|
||||||
|
this.store = store;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public Map<String, Object> account(long user, String network) {
|
||||||
|
network(network);
|
||||||
|
store.execute(
|
||||||
|
"INSERT INTO"
|
||||||
|
+ " rent_account(user_id,network,available_amount,frozen_amount,supplier_pending_amount,status,version,created_at,updated_at)"
|
||||||
|
+ " VALUES(?,?,0,0,0,'ACTIVE',0,?,?) ON DUPLICATE KEY UPDATE id=id",
|
||||||
|
user,
|
||||||
|
network,
|
||||||
|
now(),
|
||||||
|
now());
|
||||||
|
return store.one("SELECT * FROM rent_account WHERE user_id=? AND network=?", user, network);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void lock(long first, long second) {
|
||||||
|
store.get("account", Math.min(first, second), true);
|
||||||
|
if (first != second) {
|
||||||
|
store.get("account", Math.max(first, second), true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 全局business_key先去重,并校验同键的账户、事件与金额,不吞掉不同参数的重放。 */
|
||||||
|
public void post(
|
||||||
|
long account,
|
||||||
|
String key,
|
||||||
|
String type,
|
||||||
|
BigDecimal available,
|
||||||
|
BigDecimal frozen,
|
||||||
|
BigDecimal pending,
|
||||||
|
BigDecimal fee,
|
||||||
|
Long order,
|
||||||
|
Long settlement,
|
||||||
|
Long refund,
|
||||||
|
long actor,
|
||||||
|
String evidence,
|
||||||
|
String reason) {
|
||||||
|
Map<String, Object> row = store.get("account", account, true);
|
||||||
|
Map<String, Object> old = store.one("SELECT * FROM rent_ledger WHERE business_key=?", key);
|
||||||
|
if (old != null) {
|
||||||
|
require(
|
||||||
|
number(old, "account_id") == account
|
||||||
|
&& type.equals(text(old, "event_type"))
|
||||||
|
&& amount(old, "delta_available").compareTo(available) == 0
|
||||||
|
&& amount(old, "delta_frozen").compareTo(frozen) == 0
|
||||||
|
&& amount(old, "delta_supplier_pending").compareTo(pending) == 0
|
||||||
|
&& amount(old, "delta_platform_fee").compareTo(fee) == 0,
|
||||||
|
"记账键已被不同业务占用");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
BigDecimal a = amount(row, "available_amount").add(available);
|
||||||
|
BigDecimal f = amount(row, "frozen_amount").add(frozen);
|
||||||
|
BigDecimal p = amount(row, "supplier_pending_amount").add(pending);
|
||||||
|
require(a.signum() >= 0 && f.signum() >= 0 && p.signum() >= 0, "余额不足或资金状态冲突");
|
||||||
|
store.update(
|
||||||
|
"account",
|
||||||
|
account,
|
||||||
|
map("available_amount", a, "frozen_amount", f, "supplier_pending_amount", p));
|
||||||
|
Long reversalOf = null;
|
||||||
|
if ("REVERSAL".equals(type) && order != null) {
|
||||||
|
Map<String, Object> original =
|
||||||
|
store.one(
|
||||||
|
"SELECT id FROM rent_ledger WHERE business_key=?",
|
||||||
|
(key.endsWith(":FEE") ? "FEE:" : "EARN:") + order);
|
||||||
|
require(original != null, "冲正缺少原记账来源");
|
||||||
|
reversalOf = number(original, "id");
|
||||||
|
}
|
||||||
|
store.insert(
|
||||||
|
"ledger",
|
||||||
|
map(
|
||||||
|
"account_id",
|
||||||
|
account,
|
||||||
|
"business_key",
|
||||||
|
key,
|
||||||
|
"event_type",
|
||||||
|
type,
|
||||||
|
"delta_available",
|
||||||
|
available,
|
||||||
|
"delta_frozen",
|
||||||
|
frozen,
|
||||||
|
"delta_supplier_pending",
|
||||||
|
pending,
|
||||||
|
"delta_platform_fee",
|
||||||
|
fee,
|
||||||
|
"after_available",
|
||||||
|
a,
|
||||||
|
"after_frozen",
|
||||||
|
f,
|
||||||
|
"after_supplier_pending",
|
||||||
|
p,
|
||||||
|
"order_id",
|
||||||
|
order,
|
||||||
|
"settlement_id",
|
||||||
|
settlement,
|
||||||
|
"refund_id",
|
||||||
|
refund,
|
||||||
|
"reversal_of_id",
|
||||||
|
reversalOf,
|
||||||
|
"operator_user_id",
|
||||||
|
actor,
|
||||||
|
"evidence_ref",
|
||||||
|
evidence,
|
||||||
|
"reason",
|
||||||
|
reason));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void hold(Map<String, Object> order) {
|
||||||
|
long id = number(order, "id");
|
||||||
|
BigDecimal price = amount(order, "sale_amount");
|
||||||
|
post(
|
||||||
|
number(order, "payer_account_id"),
|
||||||
|
"HOLD:" + id,
|
||||||
|
"HOLD",
|
||||||
|
price.negate(),
|
||||||
|
price,
|
||||||
|
ZERO,
|
||||||
|
ZERO,
|
||||||
|
id,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
0,
|
||||||
|
null,
|
||||||
|
"租赁订单冻结");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void release(Map<String, Object> order) {
|
||||||
|
require("HELD".equals(text(order, "fund_status")), "订单不处于冻结状态");
|
||||||
|
long id = number(order, "id");
|
||||||
|
BigDecimal price = amount(order, "sale_amount");
|
||||||
|
post(
|
||||||
|
number(order, "payer_account_id"),
|
||||||
|
"RELEASE:" + id,
|
||||||
|
"RELEASE",
|
||||||
|
price,
|
||||||
|
price.negate(),
|
||||||
|
ZERO,
|
||||||
|
ZERO,
|
||||||
|
id,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
0,
|
||||||
|
null,
|
||||||
|
"明确未执行,释放冻结");
|
||||||
|
store.update("order", id, map("fund_status", "RELEASED"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void charge(Map<String, Object> order) {
|
||||||
|
require("HELD".equals(text(order, "fund_status")), "订单资金不可重复扣款");
|
||||||
|
long id = number(order, "id");
|
||||||
|
long payer = number(order, "payer_account_id");
|
||||||
|
long supplier = number(order, "supplier_account_id");
|
||||||
|
lock(payer, supplier);
|
||||||
|
post(
|
||||||
|
payer,
|
||||||
|
"CHARGE:" + id,
|
||||||
|
"CHARGE",
|
||||||
|
ZERO,
|
||||||
|
amount(order, "sale_amount").negate(),
|
||||||
|
ZERO,
|
||||||
|
ZERO,
|
||||||
|
id,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
0,
|
||||||
|
null,
|
||||||
|
"独立链上核验通过,确认扣款");
|
||||||
|
post(
|
||||||
|
supplier,
|
||||||
|
"EARN:" + id,
|
||||||
|
"SUPPLIER_EARN",
|
||||||
|
ZERO,
|
||||||
|
ZERO,
|
||||||
|
amount(order, "supplier_amount"),
|
||||||
|
ZERO,
|
||||||
|
id,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
0,
|
||||||
|
null,
|
||||||
|
"供应商履约毛收入");
|
||||||
|
BigDecimal fee = amount(order, "supplier_fee_amount");
|
||||||
|
post(
|
||||||
|
supplier,
|
||||||
|
"FEE:" + id,
|
||||||
|
"SUPPLIER_FEE",
|
||||||
|
ZERO,
|
||||||
|
ZERO,
|
||||||
|
fee.negate(),
|
||||||
|
fee,
|
||||||
|
id,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
0,
|
||||||
|
null,
|
||||||
|
"按订单锁定费率扣取手续费");
|
||||||
|
store.update("order", id, map("fund_status", "CHARGED"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import static com.ruoyi.system.rental.RentalValues.*;
|
||||||
|
|
||||||
|
import okhttp3.*;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
/** 回调专用HTTP客户端:HTTPS、解析结果逐一检查、实际连接复用该DNS结果、拒绝重定向。 */
|
||||||
|
public final class RentalHttp {
|
||||||
|
private RentalHttp() {}
|
||||||
|
|
||||||
|
public static void checkUrl(String url) {
|
||||||
|
URI uri = URI.create(url);
|
||||||
|
require(
|
||||||
|
"https".equalsIgnoreCase(uri.getScheme())
|
||||||
|
&& uri.getHost() != null
|
||||||
|
&& uri.getUserInfo() == null
|
||||||
|
&& uri.getFragment() == null
|
||||||
|
&& uri.getQuery() == null
|
||||||
|
&& (uri.getPort() == -1 || uri.getPort() == 443)
|
||||||
|
&& url.length() <= 512,
|
||||||
|
"回调仅允许标准HTTPS地址");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean publicAddress(InetAddress address) {
|
||||||
|
byte[] bytes = address.getAddress();
|
||||||
|
if (address.isAnyLocalAddress()
|
||||||
|
|| address.isLoopbackAddress()
|
||||||
|
|| address.isLinkLocalAddress()
|
||||||
|
|| address.isSiteLocalAddress()
|
||||||
|
|| address.isMulticastAddress()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (bytes.length == 16) {
|
||||||
|
return (bytes[0] & 0xe0) == 0x20;
|
||||||
|
}
|
||||||
|
int a = bytes[0] & 255;
|
||||||
|
int b = bytes[1] & 255;
|
||||||
|
return a != 0
|
||||||
|
&& a != 10
|
||||||
|
&& a != 127
|
||||||
|
&& a < 224
|
||||||
|
&& !(a == 100 && b >= 64 && b <= 127)
|
||||||
|
&& !(a == 169 && b == 254)
|
||||||
|
&& !(a == 172 && b >= 16 && b <= 31)
|
||||||
|
&& !(a == 192 && b == 168)
|
||||||
|
&& !(a == 198 && (b == 18 || b == 19))
|
||||||
|
&& !(a == 192 && b == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static OkHttpClient callbackClient() {
|
||||||
|
return new OkHttpClient.Builder()
|
||||||
|
.connectTimeout(5, TimeUnit.SECONDS)
|
||||||
|
.readTimeout(5, TimeUnit.SECONDS)
|
||||||
|
.callTimeout(10, TimeUnit.SECONDS)
|
||||||
|
.followRedirects(false)
|
||||||
|
.followSslRedirects(false)
|
||||||
|
.retryOnConnectionFailure(false)
|
||||||
|
.dns(
|
||||||
|
host -> {
|
||||||
|
InetAddress[] addresses = InetAddress.getAllByName(host);
|
||||||
|
for (InetAddress address : addresses) {
|
||||||
|
if (!publicAddress(address)) {
|
||||||
|
throw new java.net.UnknownHostException("回调目标非公网地址");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Arrays.asList(addresses);
|
||||||
|
})
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String body(Response response) throws IOException {
|
||||||
|
require(response.isSuccessful() && response.body() != null, "RPC响应失败");
|
||||||
|
java.io.InputStream stream = response.body().byteStream();
|
||||||
|
java.io.ByteArrayOutputStream output = new java.io.ByteArrayOutputStream();
|
||||||
|
byte[] buffer = new byte[4096];
|
||||||
|
int count;
|
||||||
|
while ((count = stream.read(buffer)) != -1) {
|
||||||
|
require(output.size() + count <= 1024 * 1024, "RPC响应超过限制");
|
||||||
|
output.write(buffer, 0, count);
|
||||||
|
}
|
||||||
|
return new String(output.toByteArray(), java.nio.charset.StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import static com.ruoyi.system.rental.RentalValues.*;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** 外部APP和本地NODE共用凭证认证,登录用户归属仍由sys_user及RBAC决定。 */
|
||||||
|
@Service
|
||||||
|
public class RentalIdentity {
|
||||||
|
private final RentalStore store;
|
||||||
|
private final RentalCrypto crypto;
|
||||||
|
|
||||||
|
@Value("${rental.master-key-version:v1}")
|
||||||
|
private String masterVersion;
|
||||||
|
|
||||||
|
public RentalIdentity(RentalStore store, RentalCrypto crypto) {
|
||||||
|
this.store = store;
|
||||||
|
this.crypto = crypto;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> credential(String key) {
|
||||||
|
Map<String, Object> row = store.one("SELECT * FROM rent_credential WHERE api_key=?", key);
|
||||||
|
require(
|
||||||
|
row != null
|
||||||
|
&& "ACTIVE".equals(text(row, "status"))
|
||||||
|
&& (row.get("expires_at") == null
|
||||||
|
|| time(row.get("expires_at")).isAfter(Instant.now())),
|
||||||
|
"租赁凭证无效");
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String secret(Map<String, Object> credential) {
|
||||||
|
return crypto.decrypt(text(credential, "api_secret"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public Map<String, Object> authenticate(
|
||||||
|
String key,
|
||||||
|
String ownerType,
|
||||||
|
String scope,
|
||||||
|
long timestamp,
|
||||||
|
String nonce,
|
||||||
|
String method,
|
||||||
|
String path,
|
||||||
|
String body,
|
||||||
|
String signature) {
|
||||||
|
require(
|
||||||
|
key != null
|
||||||
|
&& key.length() <= 64
|
||||||
|
&& nonce != null
|
||||||
|
&& nonce.matches("[A-Za-z0-9_-]{16,64}")
|
||||||
|
&& timestamp > System.currentTimeMillis() - 60000
|
||||||
|
&& timestamp < System.currentTimeMillis() + 60000,
|
||||||
|
"认证时间或随机数无效");
|
||||||
|
Map<String, Object> row = credential(key);
|
||||||
|
require(
|
||||||
|
ownerType.equals(text(row, "owner_type"))
|
||||||
|
&& RentalCrypto.equal(
|
||||||
|
RentalCrypto.sign(
|
||||||
|
secret(row),
|
||||||
|
scope,
|
||||||
|
key,
|
||||||
|
timestamp,
|
||||||
|
nonce,
|
||||||
|
method,
|
||||||
|
path,
|
||||||
|
body),
|
||||||
|
signature),
|
||||||
|
"租赁签名无效");
|
||||||
|
store.insert(
|
||||||
|
"nonce",
|
||||||
|
map("api_key", key, "scope", scope, "nonce", nonce, "expires_at", after(180)));
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 轮换保留历史Secret,仅明确在途任务可以使用VERIFY_ONLY,不能签发新任务。 */
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public Map<String, Object> issue(String type, long owner, long actor) {
|
||||||
|
require("APP".equals(type) || "NODE".equals(type), "凭证主体非法");
|
||||||
|
Map<String, Object> row = store.get(type.toLowerCase(Locale.ROOT), owner, true);
|
||||||
|
require(number(row, "user_id") == actor, "无主体权限");
|
||||||
|
String secret = RentalCrypto.random();
|
||||||
|
String encrypted = crypto.encrypt(secret);
|
||||||
|
String key = id("RK");
|
||||||
|
store.execute(
|
||||||
|
"UPDATE rent_credential SET status='VERIFY_ONLY',version=version+1,updated_at=?"
|
||||||
|
+ " WHERE owner_type=? AND owner_id=? AND status='ACTIVE'",
|
||||||
|
now(),
|
||||||
|
type,
|
||||||
|
owner);
|
||||||
|
long id =
|
||||||
|
store.insert(
|
||||||
|
"credential",
|
||||||
|
map(
|
||||||
|
"owner_type",
|
||||||
|
type,
|
||||||
|
"owner_id",
|
||||||
|
owner,
|
||||||
|
"api_key",
|
||||||
|
key,
|
||||||
|
"api_secret",
|
||||||
|
encrypted,
|
||||||
|
"master_key_version",
|
||||||
|
masterVersion,
|
||||||
|
"status",
|
||||||
|
"ACTIVE"));
|
||||||
|
store.event(type, owner, "ROTATE_CREDENTIAL", actor, "新Secret仅通过本次TLS响应展示,旧凭证仅核对在途");
|
||||||
|
return map("id", id, "api_key", key, "api_secret", secret);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void revoke(long id, long actor) {
|
||||||
|
Map<String, Object> credential = store.get("credential", id, true);
|
||||||
|
Map<String, Object> owner =
|
||||||
|
store.get(
|
||||||
|
text(credential, "owner_type").toLowerCase(Locale.ROOT),
|
||||||
|
number(credential, "owner_id"),
|
||||||
|
false);
|
||||||
|
require(number(owner, "user_id") == actor, "无主体权限");
|
||||||
|
store.update("credential", id, map("status", "REVOKED", "revoked_at", now()));
|
||||||
|
store.event(
|
||||||
|
"APP".equals(text(credential, "owner_type")) ? "APP" : "NODE",
|
||||||
|
number(credential, "owner_id"),
|
||||||
|
"REVOKE_CREDENTIAL",
|
||||||
|
actor,
|
||||||
|
"主动吊销凭证");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import static com.ruoyi.system.rental.RentalValues.require;
|
||||||
|
|
||||||
|
/** Jackson2.10没有流深度限制,解析前先检查结构深度;字符串内括号不计入。 */
|
||||||
|
public final class RentalJson {
|
||||||
|
private RentalJson() {}
|
||||||
|
|
||||||
|
public static void bounded(String value) {
|
||||||
|
require(value != null && value.length() <= 65536, "JSON消息超限");
|
||||||
|
int depth = 0;
|
||||||
|
boolean quoted = false;
|
||||||
|
boolean escaped = false;
|
||||||
|
for (int i = 0; i < value.length(); i++) {
|
||||||
|
char character = value.charAt(i);
|
||||||
|
if (quoted) {
|
||||||
|
if (escaped) {
|
||||||
|
escaped = false;
|
||||||
|
} else if (character == '\\') {
|
||||||
|
escaped = true;
|
||||||
|
} else if (character == '"') {
|
||||||
|
quoted = false;
|
||||||
|
}
|
||||||
|
} else if (character == '"') {
|
||||||
|
quoted = true;
|
||||||
|
} else if (character == '{' || character == '[') {
|
||||||
|
require(++depth <= 32, "JSON嵌套超过32层");
|
||||||
|
} else if (character == '}' || character == ']') {
|
||||||
|
require(--depth >= 0, "JSON结构无效");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
require(depth == 0 && !quoted, "JSON结构不完整");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.web.servlet.HandlerInterceptor;
|
||||||
|
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||||
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||||
|
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
|
||||||
|
/** 禁用生成器直接操作16张业务表的旧入口,包括余额覆盖、流水删除和Secret导出。 旧菜单组件仍可保留,页面统一转向/rental业务接口;不是依赖隐藏按钮防越权。 */
|
||||||
|
@Configuration
|
||||||
|
public class RentalLegacyGuard implements WebMvcConfigurer {
|
||||||
|
@Override
|
||||||
|
public void addInterceptors(InterceptorRegistry registry) {
|
||||||
|
registry.addInterceptor(
|
||||||
|
new HandlerInterceptor() {
|
||||||
|
@Override
|
||||||
|
public boolean preHandle(
|
||||||
|
HttpServletRequest request,
|
||||||
|
HttpServletResponse response,
|
||||||
|
Object handler)
|
||||||
|
throws Exception {
|
||||||
|
String path =
|
||||||
|
request.getRequestURI()
|
||||||
|
.substring(request.getContextPath().length());
|
||||||
|
if (path.matches(
|
||||||
|
"/system/rent(App|Credential|Nonce|Node|Wallet|Package|Account|Order|Task|Transaction|Ledger|Settlement|SettlementItem|Refund|Webhook|Event)(/.*)?")) {
|
||||||
|
response.setStatus(409);
|
||||||
|
response.setContentType("application/json;charset=UTF-8");
|
||||||
|
response.getWriter()
|
||||||
|
.write("{\"code\":409,\"msg\":\"请使用租赁业务接口,禁止直接修改或导出底层业务记录\"}");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import static com.ruoyi.system.rental.RentalValues.*;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.tron.trident.core.ApiWrapper;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/** 下单、冻结、取消与业务回调入队;外部接口与登录接口复用同一套事务规则。 */
|
||||||
|
@Service
|
||||||
|
public class RentalOrders {
|
||||||
|
private final RentalStore store;
|
||||||
|
private final RentalFunds funds;
|
||||||
|
private final ObjectMapper json;
|
||||||
|
|
||||||
|
public RentalOrders(RentalStore store, RentalFunds funds, ObjectMapper json) {
|
||||||
|
this.store = store;
|
||||||
|
this.funds = funds;
|
||||||
|
this.json = json;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void address(String address) {
|
||||||
|
try {
|
||||||
|
require(
|
||||||
|
address.startsWith("T") && ApiWrapper.parseAddress(address).size() == 21,
|
||||||
|
"地址不合法");
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new IllegalArgumentException("TRON地址校验失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public Map<String, Object> create(long appId, long user, Map<String, Object> request) {
|
||||||
|
// 锁应用行使同应用幂等竞争顺序化;不能仅依靠先查后插。
|
||||||
|
Map<String, Object> app = store.get("app", appId, true);
|
||||||
|
require(
|
||||||
|
number(app, "user_id") == user && "ACTIVE".equals(text(app, "status")),
|
||||||
|
"应用无权限或已禁用");
|
||||||
|
String merchant = input(request, "merchant_order_no", 64);
|
||||||
|
String receiver = input(request, "receiver_address", 64);
|
||||||
|
address(receiver);
|
||||||
|
long packageId = number(request, "package_id");
|
||||||
|
String notify = text(request, "notify_url").trim();
|
||||||
|
if (notify.isEmpty()) {
|
||||||
|
notify = text(app, "notify_url");
|
||||||
|
}
|
||||||
|
if (!notify.isEmpty()) {
|
||||||
|
RentalHttp.checkUrl(notify);
|
||||||
|
}
|
||||||
|
String hash =
|
||||||
|
RentalCrypto.sha256(
|
||||||
|
encode(
|
||||||
|
map(
|
||||||
|
"package_id",
|
||||||
|
packageId,
|
||||||
|
"receiver_address",
|
||||||
|
receiver,
|
||||||
|
"notify_url",
|
||||||
|
notify)));
|
||||||
|
Map<String, Object> existing =
|
||||||
|
store.one(
|
||||||
|
"SELECT * FROM rent_order WHERE app_id=? AND merchant_order_no=?",
|
||||||
|
appId,
|
||||||
|
merchant);
|
||||||
|
if (existing != null) {
|
||||||
|
require(hash.equals(text(existing, "request_hash")), "同一商户订单号参数不一致");
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
Map<String, Object> product = store.get("package", packageId, true);
|
||||||
|
validatePackage(product);
|
||||||
|
require("ACTIVE".equals(text(product, "status")), "套餐未上架");
|
||||||
|
if (request.containsKey("resource_type")) {
|
||||||
|
require(
|
||||||
|
text(product, "resource_type").equals(text(request, "resource_type")),
|
||||||
|
"资源类型与套餐不符");
|
||||||
|
}
|
||||||
|
Map<String, Object> account = funds.account(user, network(text(product, "network")));
|
||||||
|
account = store.get("account", number(account, "id"), true);
|
||||||
|
require("ACTIVE".equals(text(account, "status")), "租赁账户已冻结");
|
||||||
|
BigDecimal gross = amount(product, "supplier_amount");
|
||||||
|
BigDecimal fee =
|
||||||
|
gross.multiply(new BigDecimal(text(product, "supplier_fee_percent")))
|
||||||
|
.movePointLeft(2)
|
||||||
|
.setScale(6, RoundingMode.HALF_UP);
|
||||||
|
Map<String, Object> order =
|
||||||
|
map(
|
||||||
|
"order_no",
|
||||||
|
id("RO"),
|
||||||
|
"app_id",
|
||||||
|
appId,
|
||||||
|
"merchant_order_no",
|
||||||
|
merchant,
|
||||||
|
"request_hash",
|
||||||
|
hash,
|
||||||
|
"package_id",
|
||||||
|
packageId,
|
||||||
|
"network",
|
||||||
|
text(product, "network"),
|
||||||
|
"receiver_address",
|
||||||
|
receiver,
|
||||||
|
"resource_type",
|
||||||
|
text(product, "resource_type"),
|
||||||
|
"resource_quantity",
|
||||||
|
number(product, "resource_quantity"),
|
||||||
|
"redundancy_percent",
|
||||||
|
product.get("redundancy_percent"),
|
||||||
|
"target_resource_quantity",
|
||||||
|
target(
|
||||||
|
number(product, "resource_quantity"),
|
||||||
|
new BigDecimal(text(product, "redundancy_percent"))),
|
||||||
|
"duration_seconds",
|
||||||
|
number(product, "duration_seconds"),
|
||||||
|
"sale_amount",
|
||||||
|
amount(product, "sale_amount"),
|
||||||
|
"supplier_amount",
|
||||||
|
gross,
|
||||||
|
"supplier_fee_percent",
|
||||||
|
product.get("supplier_fee_percent"),
|
||||||
|
"supplier_fee_amount",
|
||||||
|
fee,
|
||||||
|
"supplier_net_amount",
|
||||||
|
gross.subtract(fee),
|
||||||
|
"package_snapshot",
|
||||||
|
encode(product),
|
||||||
|
"status",
|
||||||
|
"WAITING",
|
||||||
|
"payer_account_id",
|
||||||
|
number(account, "id"),
|
||||||
|
"fund_status",
|
||||||
|
"HELD",
|
||||||
|
"dispatch_deadline",
|
||||||
|
after(300),
|
||||||
|
"reclaim_status",
|
||||||
|
"NOT_STARTED",
|
||||||
|
"notify_url",
|
||||||
|
notify.isEmpty() ? null : notify);
|
||||||
|
long id = store.insert("order", order);
|
||||||
|
order.put("id", id);
|
||||||
|
funds.hold(order);
|
||||||
|
store.event("ORDER", id, "CREATE", user, "创建订单并冻结内部USDT");
|
||||||
|
return store.get("order", id, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void validatePackage(Map<String, Object> row) {
|
||||||
|
network(text(row, "network"));
|
||||||
|
resource(text(row, "resource_type"));
|
||||||
|
target(number(row, "resource_quantity"), new BigDecimal(text(row, "redundancy_percent")));
|
||||||
|
BigDecimal sale = amount(row, "sale_amount");
|
||||||
|
BigDecimal gross = amount(row, "supplier_amount");
|
||||||
|
BigDecimal percent = new BigDecimal(text(row, "supplier_fee_percent"));
|
||||||
|
BigDecimal fee = gross.multiply(percent).movePointLeft(2).setScale(6, RoundingMode.HALF_UP);
|
||||||
|
require(
|
||||||
|
sale.signum() > 0
|
||||||
|
&& gross.signum() > 0
|
||||||
|
&& gross.compareTo(sale) <= 0
|
||||||
|
&& percent.signum() > 0
|
||||||
|
&& percent.compareTo(new BigDecimal("100")) < 0
|
||||||
|
&& fee.signum() > 0
|
||||||
|
&& fee.compareTo(gross) < 0,
|
||||||
|
"套餐售价或供应商费率无效");
|
||||||
|
require(
|
||||||
|
number(row, "duration_seconds") > 0
|
||||||
|
&& number(row, "fee_limit_sun") > 0
|
||||||
|
&& number(row, "delegate_lock") == 0,
|
||||||
|
"首版仅支持非锁定委托,租期和本地费用预算必须为正");
|
||||||
|
require(row.get("rules") != null && !text(row, "rules").isEmpty(), "必须配置套餐规则");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void cancel(long orderId, long user) {
|
||||||
|
Map<String, Object> order = store.get("order", orderId, true);
|
||||||
|
Map<String, Object> app = store.get("app", number(order, "app_id"), false);
|
||||||
|
require(number(app, "user_id") == user, "无订单权限");
|
||||||
|
if ("CANCELLED".equals(text(order, "status"))) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
require(
|
||||||
|
"WAITING".equals(text(order, "status"))
|
||||||
|
&& store.one("SELECT id FROM rent_task WHERE order_id=? LIMIT 1", orderId)
|
||||||
|
== null,
|
||||||
|
"已创建执行任务,不可取消或重派");
|
||||||
|
funds.release(order);
|
||||||
|
store.update("order", orderId, map("status", "CANCELLED"));
|
||||||
|
webhook(order, "CANCELLED", "ORDER:" + orderId + ":CANCELLED");
|
||||||
|
store.event("ORDER", orderId, "CANCEL", user, "未派单取消");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void webhook(Map<String, Object> order, String type, String key) {
|
||||||
|
long orderId = number(order, "id");
|
||||||
|
if (store.one("SELECT id FROM rent_webhook WHERE event_key=?", key) != null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Map<String, Object> last =
|
||||||
|
store.one(
|
||||||
|
"SELECT COALESCE(MAX(order_event_sequence),0) AS seq FROM rent_webhook"
|
||||||
|
+ " WHERE order_id=?",
|
||||||
|
orderId);
|
||||||
|
long seq = number(last, "seq") + 1;
|
||||||
|
String event = id("WH");
|
||||||
|
store.insert(
|
||||||
|
"webhook",
|
||||||
|
map(
|
||||||
|
"event_no",
|
||||||
|
event,
|
||||||
|
"order_id",
|
||||||
|
orderId,
|
||||||
|
"event_type",
|
||||||
|
type,
|
||||||
|
"event_key",
|
||||||
|
key,
|
||||||
|
"order_event_sequence",
|
||||||
|
seq,
|
||||||
|
"payload",
|
||||||
|
encode(
|
||||||
|
map(
|
||||||
|
"event_no",
|
||||||
|
event,
|
||||||
|
"event_type",
|
||||||
|
type,
|
||||||
|
"order_event_sequence",
|
||||||
|
seq,
|
||||||
|
"order_no",
|
||||||
|
text(order, "order_no"),
|
||||||
|
"merchant_order_no",
|
||||||
|
text(order, "merchant_order_no"),
|
||||||
|
"network",
|
||||||
|
text(order, "network"),
|
||||||
|
"resource_type",
|
||||||
|
text(order, "resource_type"),
|
||||||
|
"resource_quantity",
|
||||||
|
number(order, "resource_quantity"),
|
||||||
|
"amount",
|
||||||
|
text(order, "sale_amount"),
|
||||||
|
"refunded_amount",
|
||||||
|
text(order, "refunded_amount"))),
|
||||||
|
"status",
|
||||||
|
"PENDING",
|
||||||
|
"next_attempt_at",
|
||||||
|
now()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public String encode(Object value) {
|
||||||
|
try {
|
||||||
|
return json.writeValueAsString(value);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new IllegalArgumentException("业务数据序列化失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import static com.ruoyi.system.rental.RentalValues.*;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.tron.common.crypto.ECKey;
|
||||||
|
import org.tron.trident.crypto.Hash;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** 应用、节点、公开钱包和不可变套餐版本的生命周期。绝不接收TRON私钥。 */
|
||||||
|
@Service
|
||||||
|
public class RentalProvisioning {
|
||||||
|
private final RentalStore store;
|
||||||
|
private final RentalOrders orders;
|
||||||
|
|
||||||
|
@Value("${rental.domain:localhost}")
|
||||||
|
private String domain;
|
||||||
|
|
||||||
|
public RentalProvisioning(RentalStore store, RentalOrders orders) {
|
||||||
|
this.store = store;
|
||||||
|
this.orders = orders;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public long create(String type, Map<String, Object> request, long actor) {
|
||||||
|
Map<String, Object> row;
|
||||||
|
if ("app".equals(type)) {
|
||||||
|
String url = text(request, "notify_url");
|
||||||
|
if (!url.isEmpty()) {
|
||||||
|
RentalHttp.checkUrl(url);
|
||||||
|
}
|
||||||
|
row =
|
||||||
|
map(
|
||||||
|
"user_id",
|
||||||
|
actor,
|
||||||
|
"name",
|
||||||
|
input(request, "name", 100),
|
||||||
|
"status",
|
||||||
|
"ACTIVE",
|
||||||
|
"notify_url",
|
||||||
|
url.isEmpty() ? null : url);
|
||||||
|
} else if ("node".equals(type)) {
|
||||||
|
row =
|
||||||
|
map(
|
||||||
|
"user_id",
|
||||||
|
actor,
|
||||||
|
"node_no",
|
||||||
|
id("NODE"),
|
||||||
|
"name",
|
||||||
|
input(request, "name", 100),
|
||||||
|
"agent_version",
|
||||||
|
"1.0.0",
|
||||||
|
"status",
|
||||||
|
"PENDING",
|
||||||
|
"created_by",
|
||||||
|
actor);
|
||||||
|
} else if ("wallet".equals(type)) {
|
||||||
|
long nodeId = number(request, "node_id");
|
||||||
|
Map<String, Object> node = store.get("node", nodeId, true);
|
||||||
|
require(
|
||||||
|
number(node, "user_id") == actor && !"REVOKED".equals(text(node, "status")),
|
||||||
|
"无节点权限");
|
||||||
|
String address = input(request, "address", 64);
|
||||||
|
RentalOrders.address(address);
|
||||||
|
row =
|
||||||
|
map(
|
||||||
|
"node_id",
|
||||||
|
nodeId,
|
||||||
|
"network",
|
||||||
|
network(input(request, "network", 16)),
|
||||||
|
"address",
|
||||||
|
address,
|
||||||
|
"status",
|
||||||
|
"PENDING");
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("未知创建类型");
|
||||||
|
}
|
||||||
|
long id = store.insert(type, row);
|
||||||
|
store.event(type.toUpperCase(Locale.ROOT), id, "CREATE", actor, "租赁业务注册");
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public long product(Map<String, Object> request, long actor) {
|
||||||
|
Map<String, Object> row = new LinkedHashMap<>();
|
||||||
|
for (String key :
|
||||||
|
Arrays.asList(
|
||||||
|
"package_code",
|
||||||
|
"revision",
|
||||||
|
"name",
|
||||||
|
"network",
|
||||||
|
"resource_type",
|
||||||
|
"resource_quantity",
|
||||||
|
"redundancy_percent",
|
||||||
|
"duration_seconds",
|
||||||
|
"sale_amount",
|
||||||
|
"supplier_amount",
|
||||||
|
"supplier_fee_percent",
|
||||||
|
"fee_limit_sun",
|
||||||
|
"rules")) {
|
||||||
|
require(request.containsKey(key), "缺少套餐字段:" + key);
|
||||||
|
row.put(key, request.get(key));
|
||||||
|
}
|
||||||
|
input(row, "package_code", 32);
|
||||||
|
input(row, "name", 100);
|
||||||
|
require(number(row, "revision") > 0, "版本必须为正整数");
|
||||||
|
if (!(row.get("rules") instanceof String)) {
|
||||||
|
row.put("rules", orders.encode(row.get("rules")));
|
||||||
|
}
|
||||||
|
row.put("delegate_lock", 0);
|
||||||
|
row.put("status", "DISABLED");
|
||||||
|
RentalOrders.validatePackage(row);
|
||||||
|
Map<String, Object> previous =
|
||||||
|
store.one(
|
||||||
|
"SELECT * FROM rent_package WHERE package_code=? ORDER BY revision DESC"
|
||||||
|
+ " LIMIT 1 FOR UPDATE",
|
||||||
|
row.get("package_code"));
|
||||||
|
if (previous != null) {
|
||||||
|
require(
|
||||||
|
text(previous, "resource_type").equals(text(row, "resource_type"))
|
||||||
|
&& number(row, "revision") > number(previous, "revision"),
|
||||||
|
"同套餐资源类型不可变且版本必须递增");
|
||||||
|
}
|
||||||
|
long id = store.insert("package", row);
|
||||||
|
store.event("PACKAGE", id, "CREATE_VERSION", actor, "新增不可变价格版本");
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> ownedWallet(long id, long actor, boolean lock) {
|
||||||
|
Map<String, Object> wallet = store.get("wallet", id, lock);
|
||||||
|
Map<String, Object> node = store.get("node", number(wallet, "node_id"), false);
|
||||||
|
require(number(node, "user_id") == actor, "无钱包权限");
|
||||||
|
return wallet;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public Map<String, Object> challenge(long id, long actor) {
|
||||||
|
Map<String, Object> wallet = ownedWallet(id, actor, true);
|
||||||
|
String nonce = RentalCrypto.random();
|
||||||
|
String message =
|
||||||
|
"TRON RENTAL WALLET OWNERSHIP V1\nDomain: "
|
||||||
|
+ domain
|
||||||
|
+ "\nPurpose: bind rental wallet only; not a transaction"
|
||||||
|
+ "\nUser: "
|
||||||
|
+ actor
|
||||||
|
+ "\nWallet: "
|
||||||
|
+ id
|
||||||
|
+ "\nNetwork: "
|
||||||
|
+ text(wallet, "network")
|
||||||
|
+ "\nAddress: "
|
||||||
|
+ text(wallet, "address")
|
||||||
|
+ "\nNonce: "
|
||||||
|
+ nonce
|
||||||
|
+ "\nIssued: "
|
||||||
|
+ now()
|
||||||
|
+ "Z\nExpires: "
|
||||||
|
+ after(300)
|
||||||
|
+ "Z";
|
||||||
|
store.update(
|
||||||
|
"wallet",
|
||||||
|
id,
|
||||||
|
map(
|
||||||
|
"ownership_method",
|
||||||
|
"TRONLINK_SIGN_MESSAGE_V2",
|
||||||
|
"ownership_challenge",
|
||||||
|
nonce,
|
||||||
|
"ownership_message",
|
||||||
|
message,
|
||||||
|
"challenge_issued_at",
|
||||||
|
now(),
|
||||||
|
"challenge_expires_at",
|
||||||
|
after(300),
|
||||||
|
"challenge_consumed_at",
|
||||||
|
null));
|
||||||
|
return map("message", message, "nonce", nonce);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void prove(long id, String nonce, String signature, long actor) {
|
||||||
|
Map<String, Object> wallet = ownedWallet(id, actor, true);
|
||||||
|
require(
|
||||||
|
nonce.equals(text(wallet, "ownership_challenge"))
|
||||||
|
&& wallet.get("challenge_consumed_at") == null
|
||||||
|
&& wallet.get("challenge_expires_at") != null
|
||||||
|
&& time(wallet.get("challenge_expires_at"))
|
||||||
|
.isAfter(java.time.Instant.now()),
|
||||||
|
"挑战已过期或已消费");
|
||||||
|
require(signature.matches("(0x)?[0-9a-fA-F]{130}"), "TronLink消息签名格式无效");
|
||||||
|
try {
|
||||||
|
byte[] message = text(wallet, "ownership_message").getBytes(StandardCharsets.UTF_8);
|
||||||
|
byte[] prefix =
|
||||||
|
("\u0019TRON Signed Message:\n" + message.length)
|
||||||
|
.getBytes(StandardCharsets.UTF_8);
|
||||||
|
byte[] plain = new byte[prefix.length + message.length];
|
||||||
|
System.arraycopy(prefix, 0, plain, 0, prefix.length);
|
||||||
|
System.arraycopy(message, 0, plain, prefix.length, message.length);
|
||||||
|
byte[] sig =
|
||||||
|
org.bouncycastle.util.encoders.Hex.decode(signature.replaceFirst("^0x", ""));
|
||||||
|
int v = sig[64] & 255;
|
||||||
|
if (v < 27) {
|
||||||
|
v += 27;
|
||||||
|
}
|
||||||
|
byte[] compact = new byte[65];
|
||||||
|
compact[0] = (byte) v;
|
||||||
|
System.arraycopy(sig, 0, compact, 1, 64);
|
||||||
|
byte[] address =
|
||||||
|
ECKey.signatureToAddress(
|
||||||
|
Hash.sha3(plain),
|
||||||
|
java.util.Base64.getEncoder().encodeToString(compact));
|
||||||
|
String recovered = org.tron.trident.utils.Base58Check.bytesToBase58(address);
|
||||||
|
require(text(wallet, "address").equals(recovered), "恢复地址与钱包不符");
|
||||||
|
store.update(
|
||||||
|
"wallet",
|
||||||
|
id,
|
||||||
|
map(
|
||||||
|
"ownership_signature",
|
||||||
|
signature,
|
||||||
|
"ownership_verified_address",
|
||||||
|
recovered,
|
||||||
|
"ownership_verified_at",
|
||||||
|
now(),
|
||||||
|
"challenge_consumed_at",
|
||||||
|
now(),
|
||||||
|
"ownership_evidence",
|
||||||
|
orders.encode(
|
||||||
|
map(
|
||||||
|
"message_hash",
|
||||||
|
RentalCrypto.sha256(text(wallet, "ownership_message")),
|
||||||
|
"recovered",
|
||||||
|
recovered))));
|
||||||
|
} catch (IllegalArgumentException ex) {
|
||||||
|
throw ex;
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new IllegalArgumentException("TronLink签名验证失败");
|
||||||
|
}
|
||||||
|
store.event("WALLET", id, "OWNERSHIP_VERIFIED", actor, "一次性离线消息验证成功,尚需审核与链上权限检查");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void status(String type, long id, String status, long actor, String reason) {
|
||||||
|
Map<String, Object> row = store.get(type, id, true);
|
||||||
|
Map<String, Object> changes = map("status", status);
|
||||||
|
if ("node".equals(type)) {
|
||||||
|
require(Arrays.asList("ACTIVE", "PAUSED", "REVOKED").contains(status), "节点状态非法");
|
||||||
|
if ("ACTIVE".equals(status)) {
|
||||||
|
require(number(row, "created_by") != actor, "节点不能自审");
|
||||||
|
changes.put("approved_by", actor);
|
||||||
|
changes.put("approved_at", now());
|
||||||
|
}
|
||||||
|
} else if ("wallet".equals(type)) {
|
||||||
|
require(Arrays.asList("ACTIVE", "PAUSED").contains(status), "钱包状态非法");
|
||||||
|
require(
|
||||||
|
!"ACTIVE".equals(status) || row.get("ownership_verified_at") != null,
|
||||||
|
"钱包尚未完成TronLink验证");
|
||||||
|
} else if ("package".equals(type)) {
|
||||||
|
require(Arrays.asList("ACTIVE", "DISABLED").contains(status), "套餐状态非法");
|
||||||
|
RentalOrders.validatePackage(row);
|
||||||
|
} else if ("app".equals(type) || "account".equals(type)) {
|
||||||
|
require(
|
||||||
|
("app".equals(type)
|
||||||
|
? Arrays.asList("ACTIVE", "DISABLED")
|
||||||
|
: Arrays.asList("ACTIVE", "FROZEN"))
|
||||||
|
.contains(status),
|
||||||
|
"业务状态非法");
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("该资源不支持直接修改状态");
|
||||||
|
}
|
||||||
|
store.update(type, id, changes);
|
||||||
|
store.event(type.toUpperCase(Locale.ROOT), id, "STATUS", actor, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void policy(long id, Map<String, Object> request, long actor) {
|
||||||
|
ownedWallet(id, actor, true);
|
||||||
|
Map<String, Object> changes = new LinkedHashMap<>();
|
||||||
|
for (String type : Arrays.asList("energy", "bandwidth")) {
|
||||||
|
long enabled = number(request, type + "_enabled"),
|
||||||
|
retain = number(request, type + "_retain_sun");
|
||||||
|
require((enabled == 0 || enabled == 1) && retain >= 0, "钱包出租开关或留存本金无效");
|
||||||
|
changes.put(type + "_enabled", enabled);
|
||||||
|
changes.put(type + "_retain_sun", retain);
|
||||||
|
}
|
||||||
|
store.update("wallet", id, changes);
|
||||||
|
store.event("WALLET", id, "POLICY", actor, "供应商修改平台侧出租约束;不能替代本地广播授权");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import static com.ruoyi.system.rental.RentalValues.*;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** 查询层显式沿关联关系确定用户归属,绝不对没有user_id的表直接拼用户过滤。 */
|
||||||
|
@Service
|
||||||
|
public class RentalQueries {
|
||||||
|
private final RentalStore store;
|
||||||
|
|
||||||
|
public RentalQueries(RentalStore store) {
|
||||||
|
this.store = store;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Map<String, Object>> list(String type, Long user, int page) {
|
||||||
|
String table = store.table(type);
|
||||||
|
String where = "1=1";
|
||||||
|
List<Object> args = new ArrayList<>();
|
||||||
|
if (user != null) {
|
||||||
|
switch (type) {
|
||||||
|
case "app":
|
||||||
|
case "node":
|
||||||
|
case "account":
|
||||||
|
where = "r.user_id=?";
|
||||||
|
break;
|
||||||
|
case "package":
|
||||||
|
where = "r.status='ACTIVE'";
|
||||||
|
break;
|
||||||
|
case "wallet":
|
||||||
|
where =
|
||||||
|
"EXISTS(SELECT 1 FROM rent_node n WHERE n.id=r.node_id AND"
|
||||||
|
+ " n.user_id=?)";
|
||||||
|
break;
|
||||||
|
case "order":
|
||||||
|
where =
|
||||||
|
"EXISTS(SELECT 1 FROM rent_app a WHERE a.id=r.app_id AND a.user_id=?)"
|
||||||
|
+ " OR r.supplier_user_id=?";
|
||||||
|
break;
|
||||||
|
case "task":
|
||||||
|
where =
|
||||||
|
"EXISTS(SELECT 1 FROM rent_node n WHERE n.id=r.node_id AND"
|
||||||
|
+ " n.user_id=?)";
|
||||||
|
break;
|
||||||
|
case "ledger":
|
||||||
|
case "settlement":
|
||||||
|
where =
|
||||||
|
"EXISTS(SELECT 1 FROM rent_account a WHERE a.id=r.account_id AND"
|
||||||
|
+ " a.user_id=?)";
|
||||||
|
break;
|
||||||
|
case "refund":
|
||||||
|
where =
|
||||||
|
"EXISTS(SELECT 1 FROM rent_order o JOIN rent_app a ON a.id=o.app_id"
|
||||||
|
+ " WHERE o.id=r.order_id AND a.user_id=?)";
|
||||||
|
break;
|
||||||
|
case "credential":
|
||||||
|
where =
|
||||||
|
"(r.owner_type='APP' AND EXISTS(SELECT 1 FROM rent_app a WHERE"
|
||||||
|
+ " a.id=r.owner_id AND a.user_id=?)) OR (r.owner_type='NODE' AND"
|
||||||
|
+ " EXISTS(SELECT 1 FROM rent_node n WHERE n.id=r.owner_id AND"
|
||||||
|
+ " n.user_id=?))";
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new IllegalArgumentException("该资源仅限运营查询");
|
||||||
|
}
|
||||||
|
if (!"package".equals(type)) {
|
||||||
|
args.add(user);
|
||||||
|
}
|
||||||
|
if ("order".equals(type) || "credential".equals(type)) {
|
||||||
|
args.add(user);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
require(page > 0 && page <= 10000, "页码不合法");
|
||||||
|
args.add((page - 1) * 50);
|
||||||
|
List<Map<String, Object>> rows =
|
||||||
|
store.rows(
|
||||||
|
"SELECT r.* FROM "
|
||||||
|
+ table
|
||||||
|
+ " r WHERE ("
|
||||||
|
+ where
|
||||||
|
+ ") ORDER BY r.id DESC LIMIT 50 OFFSET ?",
|
||||||
|
args.toArray());
|
||||||
|
for (Map<String, Object> row : rows) {
|
||||||
|
row.remove("api_secret");
|
||||||
|
row.remove("ownership_signature");
|
||||||
|
row.remove("ownership_challenge");
|
||||||
|
row.remove("ownership_message");
|
||||||
|
row.remove("signature");
|
||||||
|
row.remove("nonce");
|
||||||
|
if (user != null && "order".equals(type)) {
|
||||||
|
for (String field :
|
||||||
|
Arrays.asList(
|
||||||
|
"package_snapshot",
|
||||||
|
"supplier_amount",
|
||||||
|
"supplier_fee_percent",
|
||||||
|
"supplier_fee_amount",
|
||||||
|
"supplier_net_amount")) {
|
||||||
|
row.remove(field);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import static com.ruoyi.system.rental.RentalValues.*;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Isolation;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** 账账核对只报告差异,不自动改余额或释放未知本金;同一可重复读快照避免正常并发误报。 */
|
||||||
|
@Service
|
||||||
|
public class RentalReconciliation {
|
||||||
|
private final RentalStore store;
|
||||||
|
|
||||||
|
public RentalReconciliation(RentalStore store) {
|
||||||
|
this.store = store;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
|
||||||
|
public Map<String, Object> check(long afterId) {
|
||||||
|
List<Map<String, Object>> accounts =
|
||||||
|
store.rows("SELECT * FROM rent_account WHERE id>? ORDER BY id LIMIT 100", afterId);
|
||||||
|
List<Map<String, Object>> differences = new ArrayList<>();
|
||||||
|
long last = afterId;
|
||||||
|
for (Map<String, Object> account : accounts) {
|
||||||
|
last = number(account, "id");
|
||||||
|
Map<String, Object> sum =
|
||||||
|
store.one(
|
||||||
|
"SELECT COALESCE(SUM(delta_available),0) AS"
|
||||||
|
+ " available_amount,COALESCE(SUM(delta_frozen),0) AS"
|
||||||
|
+ " frozen_amount,COALESCE(SUM(delta_supplier_pending),0) AS"
|
||||||
|
+ " supplier_pending_amount FROM rent_ledger WHERE account_id=?",
|
||||||
|
last);
|
||||||
|
for (String column :
|
||||||
|
Arrays.asList("available_amount", "frozen_amount", "supplier_pending_amount")) {
|
||||||
|
if (amount(account, column).compareTo(amount(sum, column)) != 0
|
||||||
|
|| amount(account, column).signum() < 0) {
|
||||||
|
differences.add(
|
||||||
|
map(
|
||||||
|
"type",
|
||||||
|
"ACCOUNT_LEDGER",
|
||||||
|
"id",
|
||||||
|
last,
|
||||||
|
"field",
|
||||||
|
column,
|
||||||
|
"balance",
|
||||||
|
account.get(column),
|
||||||
|
"ledger_total",
|
||||||
|
sum.get(column)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return map(
|
||||||
|
"checked",
|
||||||
|
accounts.size(),
|
||||||
|
"next_after_id",
|
||||||
|
last,
|
||||||
|
"has_more",
|
||||||
|
accounts.size() == 100,
|
||||||
|
"differences",
|
||||||
|
differences);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
|
||||||
|
public List<Map<String, Object>> reservations() {
|
||||||
|
return store.rows(
|
||||||
|
"SELECT w.id,w.energy_reserved_sun,w.bandwidth_reserved_sun,COALESCE(SUM(CASE WHEN"
|
||||||
|
+ " t.resource_type='ENERGY' THEN t.delegate_sun ELSE 0 END),0) AS"
|
||||||
|
+ " expected_energy,COALESCE(SUM(CASE WHEN t.resource_type='BANDWIDTH' THEN"
|
||||||
|
+ " t.delegate_sun ELSE 0 END),0) AS expected_bandwidth FROM rent_wallet w LEFT"
|
||||||
|
+ " JOIN rent_task t ON t.wallet_id=w.id AND t.reservation_status='HELD' GROUP"
|
||||||
|
+ " BY w.id,w.energy_reserved_sun,w.bandwidth_reserved_sun HAVING"
|
||||||
|
+ " w.energy_reserved_sun<>expected_energy OR"
|
||||||
|
+ " w.bandwidth_reserved_sun<>expected_bandwidth LIMIT 100");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import org.springframework.core.MethodParameter;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.converter.HttpMessageConverter;
|
||||||
|
import org.springframework.http.server.ServerHttpRequest;
|
||||||
|
import org.springframework.http.server.ServerHttpResponse;
|
||||||
|
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.sql.Timestamp;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** 租赁响应保留BIGINT/USDT精度,DATETIME按UTC输出,避免浏览器Number和全局支付时区影响。 */
|
||||||
|
@ControllerAdvice(basePackageClasses = RentalController.class)
|
||||||
|
public class RentalResponse implements ResponseBodyAdvice<Object> {
|
||||||
|
@Override
|
||||||
|
public boolean supports(
|
||||||
|
MethodParameter method, Class<? extends HttpMessageConverter<?>> converter) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object beforeBodyWrite(
|
||||||
|
Object body,
|
||||||
|
MethodParameter method,
|
||||||
|
MediaType mediaType,
|
||||||
|
Class<? extends HttpMessageConverter<?>> converter,
|
||||||
|
ServerHttpRequest request,
|
||||||
|
ServerHttpResponse response) {
|
||||||
|
// 凭证只展示一次;同时禁止浏览器、代理和中间缓存保存资金及密钥响应。
|
||||||
|
response.getHeaders().set("Cache-Control", "no-store");
|
||||||
|
return convert(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Object convert(Object value) {
|
||||||
|
if (value instanceof Long || value instanceof BigDecimal) {
|
||||||
|
return value.toString();
|
||||||
|
}
|
||||||
|
if (value instanceof Timestamp || value instanceof LocalDateTime) {
|
||||||
|
return RentalValues.time(value).toString();
|
||||||
|
}
|
||||||
|
if (value instanceof Map) {
|
||||||
|
Map<String, Object> result = new LinkedHashMap<>();
|
||||||
|
((Map<?, ?>) value).forEach((key, item) -> result.put(key.toString(), convert(item)));
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
if (value instanceof Collection) {
|
||||||
|
List<Object> result = new ArrayList<>();
|
||||||
|
for (Object item : (Collection<?>) value) {
|
||||||
|
result.add(convert(item));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,319 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import static com.ruoyi.system.rental.RentalValues.*;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** 人工退款及结算审批;审批者与发起者分离,付款未知绝不释放来源。 */
|
||||||
|
@Service
|
||||||
|
public class RentalReviews {
|
||||||
|
private final RentalStore store;
|
||||||
|
private final RentalFunds funds;
|
||||||
|
private final RentalOrders orders;
|
||||||
|
|
||||||
|
public RentalReviews(RentalStore store, RentalFunds funds, RentalOrders orders) {
|
||||||
|
this.store = store;
|
||||||
|
this.funds = funds;
|
||||||
|
this.orders = orders;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public long refund(long orderId, Map<String, Object> request, long actor) {
|
||||||
|
Map<String, Object> order = store.get("order", orderId, true);
|
||||||
|
require("CHARGED".equals(text(order, "fund_status")), "冻结订单只能释放,不能退款");
|
||||||
|
String requestNo = input(request, "request_no", 64);
|
||||||
|
String reason = input(request, "reason", 512);
|
||||||
|
BigDecimal refund = money(request.get("refund_amount"));
|
||||||
|
BigDecimal reverse = money(request.get("supplier_reverse_amount"));
|
||||||
|
BigDecimal fee = money(request.get("platform_fee_reverse_amount"));
|
||||||
|
String target = input(request, "fee_return_to", 16);
|
||||||
|
require(
|
||||||
|
refund.signum() > 0
|
||||||
|
&& reverse.signum() >= 0
|
||||||
|
&& fee.signum() >= 0
|
||||||
|
&& Arrays.asList("NONE", "MERCHANT", "SUPPLIER").contains(target)
|
||||||
|
&& ((fee.signum() == 0 && "NONE".equals(target))
|
||||||
|
|| (fee.signum() > 0 && !"NONE".equals(target)))
|
||||||
|
&& (!"MERCHANT".equals(target) || fee.compareTo(refund) <= 0),
|
||||||
|
"退款或费用承担参数无效");
|
||||||
|
String hash =
|
||||||
|
RentalCrypto.sha256(
|
||||||
|
orders.encode(
|
||||||
|
map(
|
||||||
|
"amount", refund, "reverse", reverse, "fee", fee, "to",
|
||||||
|
target, "reason", reason)));
|
||||||
|
Map<String, Object> existing =
|
||||||
|
store.one(
|
||||||
|
"SELECT * FROM rent_refund WHERE order_id=? AND request_no=?",
|
||||||
|
orderId,
|
||||||
|
requestNo);
|
||||||
|
if (existing != null) {
|
||||||
|
require(hash.equals(text(existing, "request_hash")), "退款幂等参数冲突");
|
||||||
|
return number(existing, "id");
|
||||||
|
}
|
||||||
|
return store.insert(
|
||||||
|
"refund",
|
||||||
|
map(
|
||||||
|
"refund_no",
|
||||||
|
id("RF"),
|
||||||
|
"order_id",
|
||||||
|
orderId,
|
||||||
|
"request_no",
|
||||||
|
requestNo,
|
||||||
|
"request_hash",
|
||||||
|
hash,
|
||||||
|
"refund_amount",
|
||||||
|
refund,
|
||||||
|
"supplier_reverse_amount",
|
||||||
|
reverse,
|
||||||
|
"platform_fee_reverse_amount",
|
||||||
|
fee,
|
||||||
|
"fee_return_to",
|
||||||
|
target,
|
||||||
|
"created_by",
|
||||||
|
actor,
|
||||||
|
"status",
|
||||||
|
"PENDING",
|
||||||
|
"reason",
|
||||||
|
reason));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void approveRefund(long id, boolean approve, long actor) {
|
||||||
|
// 先订单后退款,统一与结算来源的锁顺序;不先持有退款锁等待订单。
|
||||||
|
Map<String, Object> initial = store.get("refund", id, false);
|
||||||
|
long orderId = number(initial, "order_id");
|
||||||
|
Map<String, Object> order = store.get("order", orderId, true);
|
||||||
|
Map<String, Object> refund = store.get("refund", id, true);
|
||||||
|
if ("APPLIED".equals(text(refund, "status")) && approve) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
require(
|
||||||
|
"PENDING".equals(text(refund, "status")) && number(refund, "created_by") != actor,
|
||||||
|
"退款状态或审批人不合法");
|
||||||
|
if (!approve) {
|
||||||
|
store.update("refund", id, map("status", "REJECTED", "approved_by", actor));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
require("CHARGED".equals(text(order, "fund_status")), "订单尚未确认收入");
|
||||||
|
BigDecimal value = amount(refund, "refund_amount");
|
||||||
|
BigDecimal reverse = amount(refund, "supplier_reverse_amount");
|
||||||
|
BigDecimal fee = amount(refund, "platform_fee_reverse_amount");
|
||||||
|
BigDecimal refunded = amount(order, "refunded_amount").add(value);
|
||||||
|
BigDecimal reversed = amount(order, "supplier_reversed_amount").add(reverse);
|
||||||
|
BigDecimal feeReversed = amount(order, "supplier_fee_reversed_amount").add(fee);
|
||||||
|
require(
|
||||||
|
refunded.compareTo(amount(order, "sale_amount")) <= 0
|
||||||
|
&& reversed.compareTo(amount(order, "supplier_net_amount")) <= 0
|
||||||
|
&& feeReversed.compareTo(amount(order, "supplier_fee_amount")) <= 0,
|
||||||
|
"累计退款或冲正超限");
|
||||||
|
BigDecimal returned = "SUPPLIER".equals(text(refund, "fee_return_to")) ? fee : ZERO;
|
||||||
|
if (reverse.signum() > 0 || returned.signum() > 0) {
|
||||||
|
require(
|
||||||
|
store.one(
|
||||||
|
"SELECT id FROM rent_settlement_item WHERE order_id=? AND"
|
||||||
|
+ " active_slot=1",
|
||||||
|
orderId)
|
||||||
|
== null,
|
||||||
|
"订单已被结算占用,不能修改供应商来源;需先明确未付款并拒绝结算");
|
||||||
|
}
|
||||||
|
long payer = number(order, "payer_account_id"),
|
||||||
|
supplier = number(order, "supplier_account_id");
|
||||||
|
funds.lock(payer, supplier);
|
||||||
|
funds.post(
|
||||||
|
payer,
|
||||||
|
"REFUND:" + id,
|
||||||
|
"REFUND",
|
||||||
|
value,
|
||||||
|
ZERO,
|
||||||
|
ZERO,
|
||||||
|
ZERO,
|
||||||
|
orderId,
|
||||||
|
null,
|
||||||
|
id,
|
||||||
|
actor,
|
||||||
|
null,
|
||||||
|
text(refund, "reason"));
|
||||||
|
if (reverse.signum() > 0) {
|
||||||
|
funds.post(
|
||||||
|
supplier,
|
||||||
|
"REVERSAL:" + id + ":NET",
|
||||||
|
"REVERSAL",
|
||||||
|
ZERO,
|
||||||
|
ZERO,
|
||||||
|
reverse.negate(),
|
||||||
|
ZERO,
|
||||||
|
orderId,
|
||||||
|
null,
|
||||||
|
id,
|
||||||
|
actor,
|
||||||
|
null,
|
||||||
|
text(refund, "reason"));
|
||||||
|
}
|
||||||
|
if (fee.signum() > 0) {
|
||||||
|
funds.post(
|
||||||
|
supplier,
|
||||||
|
"REVERSAL:" + id + ":FEE",
|
||||||
|
"REVERSAL",
|
||||||
|
ZERO,
|
||||||
|
ZERO,
|
||||||
|
returned,
|
||||||
|
fee.negate(),
|
||||||
|
orderId,
|
||||||
|
null,
|
||||||
|
id,
|
||||||
|
actor,
|
||||||
|
null,
|
||||||
|
text(refund, "reason"));
|
||||||
|
}
|
||||||
|
store.update(
|
||||||
|
"order",
|
||||||
|
orderId,
|
||||||
|
map(
|
||||||
|
"refunded_amount",
|
||||||
|
refunded,
|
||||||
|
"supplier_reversed_amount",
|
||||||
|
reversed,
|
||||||
|
"supplier_fee_reversed_amount",
|
||||||
|
feeReversed,
|
||||||
|
"supplier_fee_returned_amount",
|
||||||
|
amount(order, "supplier_fee_returned_amount").add(returned)));
|
||||||
|
store.update(
|
||||||
|
"refund", id, map("status", "APPLIED", "approved_by", actor, "applied_at", now()));
|
||||||
|
orders.webhook(
|
||||||
|
store.get("order", orderId, false),
|
||||||
|
"REFUNDED",
|
||||||
|
"REFUND:" + text(refund, "refund_no"));
|
||||||
|
store.event("REFUND", id, "APPLY", actor, text(refund, "reason"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public long settlement(List<Long> orderIds, long actor) {
|
||||||
|
require(orderIds != null && !orderIds.isEmpty() && orderIds.size() <= 100, "选择1至100笔订单");
|
||||||
|
SortedSet<Long> sorted = new TreeSet<>(orderIds);
|
||||||
|
require(sorted.size() == orderIds.size(), "不能重复选择来源");
|
||||||
|
List<Map<String, Object>> sources = new ArrayList<>();
|
||||||
|
Long account = null;
|
||||||
|
BigDecimal total = ZERO;
|
||||||
|
for (long orderId : sorted) {
|
||||||
|
Map<String, Object> order = store.get("order", orderId, true);
|
||||||
|
require("CHARGED".equals(text(order, "fund_status")), "来源订单尚未确认收入");
|
||||||
|
long current = number(order, "supplier_account_id");
|
||||||
|
require(account == null || account == current, "只允许同一供应商同网络的来源");
|
||||||
|
account = current;
|
||||||
|
BigDecimal net =
|
||||||
|
amount(order, "supplier_net_amount")
|
||||||
|
.subtract(amount(order, "supplier_reversed_amount"))
|
||||||
|
.add(amount(order, "supplier_fee_returned_amount"));
|
||||||
|
require(net.signum() > 0, "来源无可结算金额");
|
||||||
|
sources.add(map("order_id", orderId, "amount", net));
|
||||||
|
total = total.add(net);
|
||||||
|
}
|
||||||
|
long id =
|
||||||
|
store.insert(
|
||||||
|
"settlement",
|
||||||
|
map(
|
||||||
|
"settlement_no",
|
||||||
|
id("ST"),
|
||||||
|
"account_id",
|
||||||
|
account,
|
||||||
|
"amount",
|
||||||
|
total,
|
||||||
|
"status",
|
||||||
|
"PENDING",
|
||||||
|
"created_by",
|
||||||
|
actor));
|
||||||
|
for (Map<String, Object> source : sources) {
|
||||||
|
source.put("settlement_id", id);
|
||||||
|
source.put("active_slot", 1);
|
||||||
|
store.insert("settlement_item", source);
|
||||||
|
}
|
||||||
|
store.event("SETTLEMENT", id, "CREATE", actor, "占用订单净应收来源");
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public Map<String, Object> transition(long id, String action, long actor, String reason) {
|
||||||
|
Map<String, Object> row = store.get("settlement", id, true);
|
||||||
|
String state = text(row, "status");
|
||||||
|
if ("approve".equals(action)) {
|
||||||
|
require("PENDING".equals(state) && number(row, "created_by") != actor, "审批须职责分离");
|
||||||
|
store.update(
|
||||||
|
"settlement",
|
||||||
|
id,
|
||||||
|
map("status", "APPROVED", "approved_by", actor, "remark", reason));
|
||||||
|
} else if ("pay".equals(action)) {
|
||||||
|
if ("PAYING".equals(state) || "UNKNOWN".equals(state)) {
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
require("APPROVED".equals(state), "必须先审批再领取付款授权");
|
||||||
|
store.update(
|
||||||
|
"settlement",
|
||||||
|
id,
|
||||||
|
map(
|
||||||
|
"status",
|
||||||
|
"PAYING",
|
||||||
|
"payout_no",
|
||||||
|
RentalValues.id("PAY"),
|
||||||
|
"payment_started_at",
|
||||||
|
now()));
|
||||||
|
} else if ("unknown".equals(action)) {
|
||||||
|
require("PAYING".equals(state), "仅付款中可转待核对");
|
||||||
|
store.update("settlement", id, map("status", "UNKNOWN", "remark", reason));
|
||||||
|
} else if ("reject".equals(action)) {
|
||||||
|
require("PENDING".equals(state) || "APPROVED".equals(state), "付款中或未知不能释放来源");
|
||||||
|
store.update("settlement", id, map("status", "REJECTED", "remark", reason));
|
||||||
|
store.execute(
|
||||||
|
"UPDATE rent_settlement_item SET"
|
||||||
|
+ " active_slot=NULL,version=version+1,updated_at=? WHERE settlement_id=?",
|
||||||
|
now(),
|
||||||
|
id);
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("未知结算操作");
|
||||||
|
}
|
||||||
|
store.event("SETTLEMENT", id, action.toUpperCase(Locale.ROOT), actor, reason);
|
||||||
|
return store.get("settlement", id, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 由链上只读服务独立核对付款后调用;不接受前端的verified=true作为依据。 */
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void paid(long id, String reference, String evidence, long actor) {
|
||||||
|
Map<String, Object> row = store.get("settlement", id, true);
|
||||||
|
if ("PAID".equals(text(row, "status"))) {
|
||||||
|
require(reference.equals(text(row, "payment_reference")), "付款凭据冲突");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
require(Arrays.asList("PAYING", "UNKNOWN").contains(text(row, "status")), "未领取付款授权");
|
||||||
|
funds.post(
|
||||||
|
number(row, "account_id"),
|
||||||
|
"SETTLE:" + id,
|
||||||
|
"SETTLE",
|
||||||
|
ZERO,
|
||||||
|
ZERO,
|
||||||
|
amount(row, "amount").negate(),
|
||||||
|
ZERO,
|
||||||
|
null,
|
||||||
|
id,
|
||||||
|
null,
|
||||||
|
actor,
|
||||||
|
reference,
|
||||||
|
"独立核验人工结算付款");
|
||||||
|
store.update(
|
||||||
|
"settlement",
|
||||||
|
id,
|
||||||
|
map(
|
||||||
|
"status",
|
||||||
|
"PAID",
|
||||||
|
"payment_reference",
|
||||||
|
reference,
|
||||||
|
"payment_evidence",
|
||||||
|
evidence,
|
||||||
|
"paid_at",
|
||||||
|
now()));
|
||||||
|
store.event("SETTLEMENT", id, "PAID", actor, reference);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,376 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import static com.ruoyi.system.rental.RentalValues.*;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.socket.*;
|
||||||
|
import org.springframework.web.socket.handler.TextWebSocketHandler;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 单入口WSS节点网关。数据库session_epoch为fencing token,旧连接关闭不能覆盖新连接。
|
||||||
|
* Socket只负责可靠交付和线索采集,不执行RPC、不把ACK或RESULT当履约成功。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@ConditionalOnProperty(name = "rental.enabled", havingValue = "true")
|
||||||
|
public class RentalSocket extends TextWebSocketHandler {
|
||||||
|
private static final String PATH = "/node/v1/socket";
|
||||||
|
private final RentalStore store;
|
||||||
|
private final RentalIdentity identity;
|
||||||
|
private final RentalTasks tasks;
|
||||||
|
private final ObjectMapper json;
|
||||||
|
private final Map<String, Connection> connections = new ConcurrentHashMap<>();
|
||||||
|
private final String instance = id("INSTANCE");
|
||||||
|
|
||||||
|
public RentalSocket(
|
||||||
|
RentalStore store, RentalIdentity identity, RentalTasks tasks, ObjectMapper json) {
|
||||||
|
this.store = store;
|
||||||
|
this.identity = identity;
|
||||||
|
this.tasks = tasks;
|
||||||
|
this.json = json;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class Connection {
|
||||||
|
WebSocketSession socket;
|
||||||
|
String challenge;
|
||||||
|
String key;
|
||||||
|
String secret;
|
||||||
|
String session;
|
||||||
|
String ping;
|
||||||
|
long node;
|
||||||
|
long epoch;
|
||||||
|
long sent;
|
||||||
|
long received;
|
||||||
|
long pong = System.currentTimeMillis();
|
||||||
|
long opened = System.currentTimeMillis();
|
||||||
|
long window;
|
||||||
|
int count;
|
||||||
|
boolean ready;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
|
||||||
|
if (connections.size() >= 1000) {
|
||||||
|
session.close(CloseStatus.SERVICE_OVERLOAD);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
session.setTextMessageSizeLimit(65536);
|
||||||
|
Connection c = new Connection();
|
||||||
|
c.socket =
|
||||||
|
new org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator(
|
||||||
|
session, 5000, 262144);
|
||||||
|
c.challenge = RentalCrypto.random();
|
||||||
|
connections.put(session.getId(), c);
|
||||||
|
session.sendMessage(
|
||||||
|
new TextMessage(
|
||||||
|
json.writeValueAsString(
|
||||||
|
map("type", "CHALLENGE", "challenge", c.challenge))));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void handleTextMessage(WebSocketSession socket, TextMessage message)
|
||||||
|
throws Exception {
|
||||||
|
Connection c = connections.get(socket.getId());
|
||||||
|
try {
|
||||||
|
require(c != null && message.getPayloadLength() <= 65536, "连接或帧大小无效");
|
||||||
|
long window = System.currentTimeMillis() / 1000;
|
||||||
|
if (c.window != window) {
|
||||||
|
c.window = window;
|
||||||
|
c.count = 0;
|
||||||
|
}
|
||||||
|
require(++c.count <= 30, "节点发送速率超限");
|
||||||
|
RentalJson.bounded(message.getPayload());
|
||||||
|
Map<String, Object> envelope =
|
||||||
|
json.readValue(
|
||||||
|
message.getPayload(), new TypeReference<Map<String, Object>>() {});
|
||||||
|
String body = input(envelope, "body", 60000);
|
||||||
|
RentalJson.bounded(body);
|
||||||
|
Map<String, Object> frame =
|
||||||
|
json.readValue(body, new TypeReference<Map<String, Object>>() {});
|
||||||
|
String type = input(frame, "type", 24);
|
||||||
|
String key = input(envelope, "api_key", 64);
|
||||||
|
require(
|
||||||
|
c.node != 0
|
||||||
|
|| ("AUTH".equals(type)
|
||||||
|
&& System.currentTimeMillis() - c.opened <= 5000),
|
||||||
|
"未认证连接");
|
||||||
|
Map<String, Object> credential =
|
||||||
|
identity.authenticate(
|
||||||
|
key,
|
||||||
|
"NODE",
|
||||||
|
"NODE",
|
||||||
|
number(envelope, "timestamp"),
|
||||||
|
input(envelope, "nonce", 64),
|
||||||
|
"FRAME",
|
||||||
|
PATH,
|
||||||
|
body,
|
||||||
|
input(envelope, "signature", 64));
|
||||||
|
if (c.node == 0) {
|
||||||
|
require(c.challenge.equals(text(frame, "challenge")), "认证挑战不匹配");
|
||||||
|
long nodeId = number(credential, "owner_id");
|
||||||
|
tasks.tx(
|
||||||
|
() -> {
|
||||||
|
Map<String, Object> node = store.get("node", nodeId, true);
|
||||||
|
require(
|
||||||
|
Arrays.asList("ACTIVE", "PAUSED").contains(text(node, "status"))
|
||||||
|
&& text(node, "node_no").equals(text(frame, "node_no")),
|
||||||
|
"节点未审核或已吊销");
|
||||||
|
c.node = nodeId;
|
||||||
|
c.epoch = Math.addExact(number(node, "session_epoch"), 1);
|
||||||
|
c.session = id("SESSION");
|
||||||
|
c.key = key;
|
||||||
|
c.secret = identity.secret(credential);
|
||||||
|
store.update(
|
||||||
|
"node",
|
||||||
|
nodeId,
|
||||||
|
map(
|
||||||
|
"session_id",
|
||||||
|
c.session,
|
||||||
|
"session_epoch",
|
||||||
|
c.epoch,
|
||||||
|
"server_instance_id",
|
||||||
|
instance,
|
||||||
|
"connection_status",
|
||||||
|
"SYNCING",
|
||||||
|
"connected_at",
|
||||||
|
now(),
|
||||||
|
"heartbeat_at",
|
||||||
|
now(),
|
||||||
|
"heartbeat_expires_at",
|
||||||
|
after(45),
|
||||||
|
"last_client_sequence",
|
||||||
|
0));
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
for (Connection other : connections.values()) {
|
||||||
|
if (other != c && other.node == c.node) {
|
||||||
|
other.socket.close(CloseStatus.POLICY_VIOLATION);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
send(c, "AUTH_OK", map("challenge", c.challenge, "heartbeat_seconds", 15));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
require(
|
||||||
|
key.equals(c.key)
|
||||||
|
&& "CLIENT".equals(text(frame, "direction"))
|
||||||
|
&& c.session.equals(text(frame, "session_id"))
|
||||||
|
&& number(frame, "session_epoch") == c.epoch
|
||||||
|
&& number(frame, "sequence") == c.received + 1,
|
||||||
|
"过期会话或帧序号错误");
|
||||||
|
require(
|
||||||
|
store.execute(
|
||||||
|
"UPDATE rent_node SET"
|
||||||
|
+ " last_client_sequence=?,version=version+1,updated_at=?"
|
||||||
|
+ " WHERE id=? AND session_epoch=? AND"
|
||||||
|
+ " last_client_sequence=? AND status<>'REVOKED'",
|
||||||
|
c.received + 1,
|
||||||
|
now(),
|
||||||
|
c.node,
|
||||||
|
c.epoch,
|
||||||
|
c.received)
|
||||||
|
== 1,
|
||||||
|
"会话已被替换");
|
||||||
|
c.received++;
|
||||||
|
Object payloadValue = frame.get("payload");
|
||||||
|
require(payloadValue instanceof Map, "缺少消息内容");
|
||||||
|
Map<String, Object> payload = (Map<String, Object>) payloadValue;
|
||||||
|
if ("PING".equals(type)) {
|
||||||
|
send(c, "PONG", map("ping_id", text(frame, "message_id")));
|
||||||
|
} else if ("PONG".equals(type)) {
|
||||||
|
require(c.ping != null && c.ping.equals(text(payload, "ping_id")), "PONG不匹配");
|
||||||
|
c.ping = null;
|
||||||
|
c.pong = System.currentTimeMillis();
|
||||||
|
store.execute(
|
||||||
|
"UPDATE rent_node SET"
|
||||||
|
+ " heartbeat_at=?,heartbeat_expires_at=?,version=version+1,updated_at=?"
|
||||||
|
+ " WHERE id=? AND session_epoch=?",
|
||||||
|
now(),
|
||||||
|
after(45),
|
||||||
|
now(),
|
||||||
|
c.node,
|
||||||
|
c.epoch);
|
||||||
|
} else if ("SYNC_STATE".equals(type)) {
|
||||||
|
Object events = payload.get("events");
|
||||||
|
if (events instanceof List) {
|
||||||
|
require(((List<?>) events).size() <= 100, "单次恢复事件超限");
|
||||||
|
for (Object event : (List<?>) events) {
|
||||||
|
tasks.report(c.node, (Map<String, Object>) event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
send(
|
||||||
|
c,
|
||||||
|
"SYNC_ACK",
|
||||||
|
map("events", events == null ? Collections.emptyList() : events));
|
||||||
|
c.ready = !Boolean.TRUE.equals(payload.get("more"));
|
||||||
|
if (c.ready) {
|
||||||
|
store.execute(
|
||||||
|
"UPDATE rent_node SET"
|
||||||
|
+ " connection_status='ONLINE',version=version+1,updated_at=? WHERE"
|
||||||
|
+ " id=? AND session_epoch=?",
|
||||||
|
now(),
|
||||||
|
c.node,
|
||||||
|
c.epoch);
|
||||||
|
}
|
||||||
|
} else if ("TASK_EVENT".equals(type) && c.ready) {
|
||||||
|
tasks.report(c.node, payload);
|
||||||
|
send(c, "RESULT_ACK", map("event_id", text(payload, "event_id")));
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("消息不允许或尚未同步");
|
||||||
|
}
|
||||||
|
} catch (Exception ex) {
|
||||||
|
// 不回传认证材料、Secret、SQL或原始异常,防止日志与网络泄密。
|
||||||
|
socket.close(CloseStatus.POLICY_VIOLATION);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String send(Connection c, String type, Map<String, Object> payload) throws Exception {
|
||||||
|
synchronized (c) {
|
||||||
|
require(c.socket.isOpen(), "节点连接已关闭");
|
||||||
|
String message = id("MSG");
|
||||||
|
String body =
|
||||||
|
json.writeValueAsString(
|
||||||
|
map(
|
||||||
|
"type",
|
||||||
|
type,
|
||||||
|
"direction",
|
||||||
|
"SERVER",
|
||||||
|
"session_id",
|
||||||
|
c.session,
|
||||||
|
"session_epoch",
|
||||||
|
Long.toString(c.epoch),
|
||||||
|
"sequence",
|
||||||
|
Long.toString(++c.sent),
|
||||||
|
"message_id",
|
||||||
|
message,
|
||||||
|
"payload",
|
||||||
|
payload));
|
||||||
|
long timestamp = System.currentTimeMillis();
|
||||||
|
String nonce = RentalCrypto.random();
|
||||||
|
if ("PING".equals(type)) {
|
||||||
|
c.ping = message;
|
||||||
|
}
|
||||||
|
c.socket.sendMessage(
|
||||||
|
new TextMessage(
|
||||||
|
json.writeValueAsString(
|
||||||
|
map(
|
||||||
|
"api_key",
|
||||||
|
c.key,
|
||||||
|
"timestamp",
|
||||||
|
timestamp,
|
||||||
|
"nonce",
|
||||||
|
nonce,
|
||||||
|
"body",
|
||||||
|
body,
|
||||||
|
"signature",
|
||||||
|
RentalCrypto.sign(
|
||||||
|
c.secret, "NODE", c.key, timestamp, nonce,
|
||||||
|
"FRAME", PATH, body)))));
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 由有界后台调度调用,同一逻辑任务始终使用相同delivery_message_id和冻结intent。 */
|
||||||
|
public void tick() {
|
||||||
|
for (Connection c : connections.values()) {
|
||||||
|
try {
|
||||||
|
if (c.node == 0) {
|
||||||
|
if (System.currentTimeMillis() - c.opened > 5000) {
|
||||||
|
c.socket.close(CloseStatus.POLICY_VIOLATION);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (System.currentTimeMillis() - c.pong > 45000) {
|
||||||
|
c.socket.close(CloseStatus.SESSION_NOT_RELIABLE);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Map<String, Object> node = store.get("node", c.node, false);
|
||||||
|
if (number(node, "session_epoch") != c.epoch
|
||||||
|
|| "REVOKED".equals(text(node, "status"))) {
|
||||||
|
c.socket.close(CloseStatus.POLICY_VIOLATION);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c.ping == null) {
|
||||||
|
send(c, "PING", map());
|
||||||
|
}
|
||||||
|
if (!c.ready) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (Map<String, Object> task :
|
||||||
|
store.rows(
|
||||||
|
"SELECT * FROM rent_task WHERE node_id=? AND status IN"
|
||||||
|
+ " ('PENDING','ACCEPTED','UNKNOWN','BROADCASTED') AND"
|
||||||
|
+ " (last_sent_at IS NULL OR last_sent_at<?) ORDER BY id LIMIT"
|
||||||
|
+ " 10",
|
||||||
|
c.node,
|
||||||
|
after(-15))) {
|
||||||
|
Map<String, Object> credential =
|
||||||
|
store.get("credential", number(task, "credential_id"), false);
|
||||||
|
if ("REVOKED".equals(text(credential, "status"))) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// PAUSED仍核对历史原任务,但不推送尚未接受的首次任务去执行。
|
||||||
|
if (!"ACTIVE".equals(text(node, "status"))
|
||||||
|
&& "PENDING".equals(text(task, "status"))) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
send(
|
||||||
|
c,
|
||||||
|
"TASK_PUSH",
|
||||||
|
map(
|
||||||
|
"task_no",
|
||||||
|
text(task, "task_no"),
|
||||||
|
"delivery_message_id",
|
||||||
|
text(task, "delivery_message_id"),
|
||||||
|
"api_key",
|
||||||
|
text(credential, "api_key"),
|
||||||
|
"intent",
|
||||||
|
json.writeValueAsString(
|
||||||
|
new TreeMap<>(
|
||||||
|
json.readValue(
|
||||||
|
text(task, "intent"), Map.class))),
|
||||||
|
"signature",
|
||||||
|
text(task, "signature"),
|
||||||
|
"timestamp",
|
||||||
|
time(task.get("signed_at")).toEpochMilli(),
|
||||||
|
"nonce",
|
||||||
|
text(task, "nonce")));
|
||||||
|
store.execute(
|
||||||
|
"UPDATE rent_task SET"
|
||||||
|
+ " delivery_count=delivery_count+1,last_sent_at=?,delivery_session_epoch=?,version=version+1,updated_at=?"
|
||||||
|
+ " WHERE id=?",
|
||||||
|
now(),
|
||||||
|
c.epoch,
|
||||||
|
now(),
|
||||||
|
task.get("id"));
|
||||||
|
}
|
||||||
|
} catch (Exception ex) {
|
||||||
|
try {
|
||||||
|
c.socket.close(CloseStatus.SERVER_ERROR);
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
/* 关闭后由epoch保护离线更新。 */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterConnectionClosed(WebSocketSession socket, CloseStatus status) {
|
||||||
|
Connection c = connections.remove(socket.getId());
|
||||||
|
if (c != null && c.node != 0) {
|
||||||
|
store.execute(
|
||||||
|
"UPDATE rent_node SET"
|
||||||
|
+ " connection_status='OFFLINE',disconnected_at=?,version=version+1,updated_at=?"
|
||||||
|
+ " WHERE id=? AND session_epoch=?",
|
||||||
|
now(),
|
||||||
|
now(),
|
||||||
|
c.node,
|
||||||
|
c.epoch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||||
|
import org.springframework.scheduling.annotation.SchedulingConfigurer;
|
||||||
|
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
|
||||||
|
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
|
||||||
|
import org.springframework.web.socket.config.annotation.*;
|
||||||
|
|
||||||
|
/** 启用开关默认关闭;正式环境由HTTPS反向代理提供WSS,节点协议另有HMAC认证。 */
|
||||||
|
@Configuration
|
||||||
|
@EnableWebSocket
|
||||||
|
@EnableScheduling
|
||||||
|
@ConditionalOnProperty(name = "rental.enabled", havingValue = "true")
|
||||||
|
public class RentalSocketConfig implements WebSocketConfigurer, SchedulingConfigurer {
|
||||||
|
private final RentalSocket socket;
|
||||||
|
|
||||||
|
public RentalSocketConfig(RentalSocket socket) {
|
||||||
|
this.socket = socket;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
|
||||||
|
registry.addHandler(socket, "/node/v1/socket");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public ThreadPoolTaskScheduler rentalTaskScheduler() {
|
||||||
|
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
|
||||||
|
scheduler.setPoolSize(6);
|
||||||
|
scheduler.setThreadNamePrefix("rental-worker-");
|
||||||
|
scheduler.setWaitForTasksToCompleteOnShutdown(true);
|
||||||
|
scheduler.setAwaitTerminationSeconds(30);
|
||||||
|
return scheduler;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void configureTasks(ScheduledTaskRegistrar registrar) {
|
||||||
|
registrar.setTaskScheduler(rentalTaskScheduler());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import static com.ruoyi.system.rental.RentalValues.*;
|
||||||
|
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.jdbc.support.GeneratedKeyHolder;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.Statement;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** 租赁事务仓储。动态标识符只接受内部白名单,业务值全部使用占位符。 行锁由调用方事务持有;RPC必须在事务外执行,避免占用数据库连接等待链上响应。 */
|
||||||
|
@Repository
|
||||||
|
public class RentalStore {
|
||||||
|
public static final Set<String> TABLES =
|
||||||
|
Collections.unmodifiableSet(
|
||||||
|
new HashSet<>(
|
||||||
|
Arrays.asList(
|
||||||
|
"app",
|
||||||
|
"credential",
|
||||||
|
"nonce",
|
||||||
|
"node",
|
||||||
|
"wallet",
|
||||||
|
"package",
|
||||||
|
"account",
|
||||||
|
"order",
|
||||||
|
"task",
|
||||||
|
"transaction",
|
||||||
|
"ledger",
|
||||||
|
"settlement",
|
||||||
|
"settlement_item",
|
||||||
|
"refund",
|
||||||
|
"webhook",
|
||||||
|
"event")));
|
||||||
|
private final JdbcTemplate jdbc;
|
||||||
|
|
||||||
|
public RentalStore(JdbcTemplate jdbc) {
|
||||||
|
this.jdbc = jdbc;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String table(String name) {
|
||||||
|
require(TABLES.contains(name), "未知租赁资源");
|
||||||
|
return "`rent_" + name + "`";
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Map<String, Object>> rows(String sql, Object... args) {
|
||||||
|
return jdbc.queryForList(sql, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> one(String sql, Object... args) {
|
||||||
|
List<Map<String, Object>> rows = rows(sql, args);
|
||||||
|
return rows.isEmpty() ? null : rows.get(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> get(String table, long id, boolean lock) {
|
||||||
|
Map<String, Object> row =
|
||||||
|
one(
|
||||||
|
"SELECT * FROM "
|
||||||
|
+ table(table)
|
||||||
|
+ " WHERE id=?"
|
||||||
|
+ (lock ? " FOR UPDATE" : ""),
|
||||||
|
id);
|
||||||
|
require(row != null, "记录不存在");
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int execute(String sql, Object... args) {
|
||||||
|
return jdbc.update(sql, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
public long insert(String table, Map<String, Object> data) {
|
||||||
|
Map<String, Object> values = new LinkedHashMap<>(data);
|
||||||
|
values.put("created_at", now());
|
||||||
|
values.put("updated_at", now());
|
||||||
|
values.put("version", 0L);
|
||||||
|
List<String> columns = new ArrayList<>(values.keySet());
|
||||||
|
columns.forEach(this::column);
|
||||||
|
String sql =
|
||||||
|
"INSERT INTO "
|
||||||
|
+ table(table)
|
||||||
|
+ " (`"
|
||||||
|
+ String.join("`,`", columns)
|
||||||
|
+ "`) VALUES ("
|
||||||
|
+ String.join(",", Collections.nCopies(columns.size(), "?"))
|
||||||
|
+ ")";
|
||||||
|
GeneratedKeyHolder holder = new GeneratedKeyHolder();
|
||||||
|
jdbc.update(
|
||||||
|
connection -> {
|
||||||
|
PreparedStatement ps =
|
||||||
|
connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
|
||||||
|
int index = 1;
|
||||||
|
for (Object value : values.values()) {
|
||||||
|
ps.setObject(index++, value);
|
||||||
|
}
|
||||||
|
return ps;
|
||||||
|
},
|
||||||
|
holder);
|
||||||
|
return Objects.requireNonNull(holder.getKey()).longValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void update(String table, long id, Map<String, Object> data) {
|
||||||
|
List<Object> args = new ArrayList<>();
|
||||||
|
List<String> setters = new ArrayList<>();
|
||||||
|
data.forEach(
|
||||||
|
(key, value) -> {
|
||||||
|
column(key);
|
||||||
|
setters.add("`" + key + "`=?");
|
||||||
|
args.add(value);
|
||||||
|
});
|
||||||
|
setters.add("version=version+1");
|
||||||
|
setters.add("updated_at=?");
|
||||||
|
args.add(now());
|
||||||
|
args.add(id);
|
||||||
|
require(
|
||||||
|
execute(
|
||||||
|
"UPDATE "
|
||||||
|
+ table(table)
|
||||||
|
+ " SET "
|
||||||
|
+ String.join(",", setters)
|
||||||
|
+ " WHERE id=?",
|
||||||
|
args.toArray())
|
||||||
|
== 1,
|
||||||
|
"记录更新失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void column(String value) {
|
||||||
|
require(value.matches("[a-z][a-z0-9_]*"), "非法列名");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void event(String type, long id, String action, long actor, String reason) {
|
||||||
|
insert(
|
||||||
|
"event",
|
||||||
|
map(
|
||||||
|
"event_no",
|
||||||
|
id("EV"),
|
||||||
|
"object_type",
|
||||||
|
type,
|
||||||
|
"object_id",
|
||||||
|
id,
|
||||||
|
"action",
|
||||||
|
action,
|
||||||
|
"actor_user_id",
|
||||||
|
actor,
|
||||||
|
"reason",
|
||||||
|
reason));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,862 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import static com.ruoyi.system.rental.RentalValues.*;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.support.TransactionTemplate;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
/** 持久任务状态机。数据库事务仅修改事实,所有RPC在事务外完成。 UNKNOWN保留三个占位和冻结资金;租约、断线、超时均不是未执行证据。 */
|
||||||
|
@Service
|
||||||
|
public class RentalTasks {
|
||||||
|
private final RentalStore store;
|
||||||
|
private final RentalChain chain;
|
||||||
|
private final RentalIdentity identity;
|
||||||
|
private final RentalOrders orders;
|
||||||
|
private final RentalFunds funds;
|
||||||
|
private final TransactionTemplate transaction;
|
||||||
|
|
||||||
|
public RentalTasks(
|
||||||
|
RentalStore store,
|
||||||
|
RentalChain chain,
|
||||||
|
RentalIdentity identity,
|
||||||
|
RentalOrders orders,
|
||||||
|
RentalFunds funds,
|
||||||
|
org.springframework.transaction.PlatformTransactionManager manager) {
|
||||||
|
this.store = store;
|
||||||
|
this.chain = chain;
|
||||||
|
this.identity = identity;
|
||||||
|
this.orders = orders;
|
||||||
|
this.funds = funds;
|
||||||
|
this.transaction = new TransactionTemplate(manager);
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> T tx(Supplier<T> action) {
|
||||||
|
return transaction.execute(status -> action.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void refresh(long id) {
|
||||||
|
Map<String, Object> previous = store.get("wallet", id, false);
|
||||||
|
Map<String, Object> snapshot =
|
||||||
|
chain.snapshot(text(previous, "network"), text(previous, "address"));
|
||||||
|
tx(
|
||||||
|
() -> {
|
||||||
|
Map<String, Object> current = store.get("wallet", id, true);
|
||||||
|
require(
|
||||||
|
number(previous, "version") == number(current, "version")
|
||||||
|
&& number(snapshot, "snapshot_block_height")
|
||||||
|
>= number(current, "snapshot_min_block_height")
|
||||||
|
&& (current.get("snapshot_block_height") == null
|
||||||
|
|| number(snapshot, "snapshot_block_height")
|
||||||
|
>= number(current, "snapshot_block_height")),
|
||||||
|
"快照已过时,丢弃并重新查询");
|
||||||
|
store.update("wallet", id, snapshot);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public void dispatch(long orderId) {
|
||||||
|
Map<String, Object> initial = store.get("order", orderId, false);
|
||||||
|
if (!"WAITING".equals(text(initial, "status"))) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!time(initial.get("dispatch_deadline")).isAfter(Instant.now())) {
|
||||||
|
tx(
|
||||||
|
() -> {
|
||||||
|
Map<String, Object> row = store.get("order", orderId, true);
|
||||||
|
if ("WAITING".equals(text(row, "status"))) {
|
||||||
|
require(
|
||||||
|
store.one(
|
||||||
|
"SELECT id FROM rent_task WHERE order_id=? AND"
|
||||||
|
+ " active_slot=1",
|
||||||
|
orderId)
|
||||||
|
== null,
|
||||||
|
"在途任务不可超时释放");
|
||||||
|
funds.release(row);
|
||||||
|
store.update("order", orderId, map("status", "CANCELLED"));
|
||||||
|
orders.webhook(row, "CANCELLED", "ORDER:" + orderId + ":CANCELLED");
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
List<Map<String, Object>> candidates =
|
||||||
|
store.rows(
|
||||||
|
"SELECT w.* FROM rent_wallet w JOIN rent_node n ON n.id=w.node_id WHERE"
|
||||||
|
+ " w.status='ACTIVE' AND w.ownership_verified_at IS NOT NULL AND"
|
||||||
|
+ " w.network=? AND w.snapshot_expires_at>? AND n.status='ACTIVE' AND"
|
||||||
|
+ " n.connection_status='ONLINE' AND n.heartbeat_expires_at>? ORDER BY"
|
||||||
|
+ " w.id LIMIT 20",
|
||||||
|
text(initial, "network"),
|
||||||
|
now(),
|
||||||
|
now());
|
||||||
|
for (Map<String, Object> candidate : candidates) {
|
||||||
|
String type = text(initial, "resource_type"), owner = text(candidate, "address");
|
||||||
|
if (owner.equals(text(initial, "receiver_address"))) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (chain.relation(
|
||||||
|
text(initial, "network"),
|
||||||
|
owner,
|
||||||
|
text(initial, "receiver_address"),
|
||||||
|
type)
|
||||||
|
!= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Boolean assigned =
|
||||||
|
tx(
|
||||||
|
() -> {
|
||||||
|
Map<String, Object> order = store.get("order", orderId, true);
|
||||||
|
if (!"WAITING".equals(text(order, "status"))
|
||||||
|
|| !time(order.get("dispatch_deadline"))
|
||||||
|
.isAfter(Instant.now())) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Map<String, Object> wallet =
|
||||||
|
store.get("wallet", number(candidate, "id"), true);
|
||||||
|
if (number(wallet, "version") != number(candidate, "version")) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Map<String, Object> node =
|
||||||
|
store.get("node", number(wallet, "node_id"), true);
|
||||||
|
String prefix = resource(type).toLowerCase(Locale.ROOT);
|
||||||
|
if (!"ACTIVE".equals(text(node, "status"))
|
||||||
|
|| !"ONLINE".equals(text(node, "connection_status"))
|
||||||
|
|| node.get("heartbeat_expires_at") == null
|
||||||
|
|| !time(node.get("heartbeat_expires_at"))
|
||||||
|
.isAfter(Instant.now())
|
||||||
|
|| number(wallet, prefix + "_enabled") != 1
|
||||||
|
|| wallet.get("snapshot_expires_at") == null
|
||||||
|
|| !time(wallet.get("snapshot_expires_at"))
|
||||||
|
.isAfter(Instant.now())
|
||||||
|
|| number(wallet, "snapshot_block_height")
|
||||||
|
< number(wallet, "snapshot_min_block_height")) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (store.one(
|
||||||
|
"SELECT id FROM rent_task WHERE wallet_id=?"
|
||||||
|
+ " AND resource_type=? AND"
|
||||||
|
+ " wallet_execution_slot=1",
|
||||||
|
wallet.get("id"),
|
||||||
|
type)
|
||||||
|
!= null
|
||||||
|
|| store.one(
|
||||||
|
"SELECT id FROM rent_order WHERE"
|
||||||
|
+ " wallet_id=? AND receiver_address=?"
|
||||||
|
+ " AND resource_type=? AND"
|
||||||
|
+ " relation_slot=1",
|
||||||
|
wallet.get("id"),
|
||||||
|
order.get("receiver_address"),
|
||||||
|
type)
|
||||||
|
!= null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
long limit = number(wallet, "total_" + prefix + "_limit"),
|
||||||
|
weight = number(wallet, "total_" + prefix + "_weight");
|
||||||
|
long sun =
|
||||||
|
principal(
|
||||||
|
number(order, "target_resource_quantity"),
|
||||||
|
limit,
|
||||||
|
weight);
|
||||||
|
long available =
|
||||||
|
Math.subtractExact(
|
||||||
|
Math.subtractExact(
|
||||||
|
number(wallet, prefix + "_delegatable_sun"),
|
||||||
|
number(wallet, prefix + "_reserved_sun")),
|
||||||
|
number(wallet, prefix + "_retain_sun"));
|
||||||
|
if (sun > available) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Map<String, Object> supplier =
|
||||||
|
funds.account(
|
||||||
|
number(node, "user_id"), text(order, "network"));
|
||||||
|
require("ACTIVE".equals(text(supplier, "status")), "供应商资金账户冻结");
|
||||||
|
store.update(
|
||||||
|
"wallet",
|
||||||
|
number(wallet, "id"),
|
||||||
|
map(
|
||||||
|
prefix + "_reserved_sun",
|
||||||
|
Math.addExact(
|
||||||
|
number(wallet, prefix + "_reserved_sun"),
|
||||||
|
sun)));
|
||||||
|
store.update(
|
||||||
|
"order",
|
||||||
|
orderId,
|
||||||
|
map(
|
||||||
|
"status",
|
||||||
|
"EXECUTING",
|
||||||
|
"wallet_id",
|
||||||
|
wallet.get("id"),
|
||||||
|
"supplier_user_id",
|
||||||
|
node.get("user_id"),
|
||||||
|
"supplier_account_id",
|
||||||
|
supplier.get("id"),
|
||||||
|
"relation_slot",
|
||||||
|
1));
|
||||||
|
createTask(order, wallet, "DELEGATE", sun, limit, weight, null);
|
||||||
|
store.event(
|
||||||
|
"ORDER", orderId, "DISPATCH", 0, "预留对应资源SUN并取得地址对和执行占位");
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
if (Boolean.TRUE.equals(assigned)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createTask(
|
||||||
|
Map<String, Object> order,
|
||||||
|
Map<String, Object> wallet,
|
||||||
|
String type,
|
||||||
|
long sun,
|
||||||
|
long limit,
|
||||||
|
long weight,
|
||||||
|
Map<String, Object> source) {
|
||||||
|
long nodeId = number(wallet, "node_id"), orderId = number(order, "id");
|
||||||
|
Map<String, Object> credential =
|
||||||
|
store.one(
|
||||||
|
"SELECT * FROM rent_credential WHERE owner_type='NODE' AND owner_id=? AND"
|
||||||
|
+ " status='ACTIVE' AND (expires_at IS NULL OR expires_at>?) ORDER BY"
|
||||||
|
+ " id DESC LIMIT 1",
|
||||||
|
nodeId,
|
||||||
|
now());
|
||||||
|
require(credential != null, "节点缺少有效凭证");
|
||||||
|
Map<String, Object> last =
|
||||||
|
store.one(
|
||||||
|
"SELECT COALESCE(MAX(attempt_no),0) AS attempt FROM rent_task WHERE"
|
||||||
|
+ " order_id=? AND task_type=?",
|
||||||
|
orderId,
|
||||||
|
type);
|
||||||
|
long attempt = number(last, "attempt") + 1;
|
||||||
|
String taskNo = id("RT"), nonce = RentalCrypto.random();
|
||||||
|
long signed = System.currentTimeMillis();
|
||||||
|
java.time.LocalDateTime deadline =
|
||||||
|
"DELEGATE".equals(type)
|
||||||
|
? java.time.LocalDateTime.ofInstant(
|
||||||
|
time(order.get("dispatch_deadline")), java.time.ZoneOffset.UTC)
|
||||||
|
: after(300);
|
||||||
|
Map<String, Object> product;
|
||||||
|
try {
|
||||||
|
product =
|
||||||
|
new com.fasterxml.jackson.databind.ObjectMapper()
|
||||||
|
.readValue(text(order, "package_snapshot"), Map.class);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new IllegalArgumentException("订单规则快照损坏");
|
||||||
|
}
|
||||||
|
long fee = number(product, "fee_limit_sun");
|
||||||
|
Map<String, Object> intent =
|
||||||
|
map(
|
||||||
|
"protocol",
|
||||||
|
"RENT_TASK_V2",
|
||||||
|
"task_no",
|
||||||
|
taskNo,
|
||||||
|
"node_id",
|
||||||
|
Long.toString(nodeId),
|
||||||
|
"network",
|
||||||
|
text(order, "network"),
|
||||||
|
"task_type",
|
||||||
|
type,
|
||||||
|
"resource_type",
|
||||||
|
text(order, "resource_type"),
|
||||||
|
"resource_quantity",
|
||||||
|
text(order, "resource_quantity"),
|
||||||
|
"target_resource_quantity",
|
||||||
|
text(order, "target_resource_quantity"),
|
||||||
|
"owner",
|
||||||
|
text(wallet, "address"),
|
||||||
|
"receiver",
|
||||||
|
text(order, "receiver_address"),
|
||||||
|
"delegate_sun",
|
||||||
|
Long.toString(sun),
|
||||||
|
"total_limit",
|
||||||
|
Long.toString(limit),
|
||||||
|
"total_weight",
|
||||||
|
Long.toString(weight),
|
||||||
|
"baseline_sun",
|
||||||
|
"DELEGATE".equals(type) ? "0" : Long.toString(sun),
|
||||||
|
"conversion_block_height",
|
||||||
|
text(wallet, "snapshot_block_height"),
|
||||||
|
"delegate_lock",
|
||||||
|
false,
|
||||||
|
"fee_limit_sun",
|
||||||
|
Long.toString(fee),
|
||||||
|
"deadline",
|
||||||
|
Long.toString(deadline.toInstant(java.time.ZoneOffset.UTC).toEpochMilli()),
|
||||||
|
"source_tx_id",
|
||||||
|
source == null ? "" : text(source, "tx_id"));
|
||||||
|
// MySQL JSON会规范化键顺序/空格;签名使用排序后的紧凑JSON,投递时按同样规则重建。
|
||||||
|
String body = orders.encode(new TreeMap<>(intent)), key = text(credential, "api_key");
|
||||||
|
store.insert(
|
||||||
|
"task",
|
||||||
|
map(
|
||||||
|
"task_no",
|
||||||
|
taskNo,
|
||||||
|
"order_id",
|
||||||
|
orderId,
|
||||||
|
"wallet_id",
|
||||||
|
wallet.get("id"),
|
||||||
|
"node_id",
|
||||||
|
nodeId,
|
||||||
|
"network",
|
||||||
|
text(order, "network"),
|
||||||
|
"source_transaction_id",
|
||||||
|
source == null ? null : source.get("id"),
|
||||||
|
"task_type",
|
||||||
|
type,
|
||||||
|
"resource_type",
|
||||||
|
text(order, "resource_type"),
|
||||||
|
"resource_quantity",
|
||||||
|
order.get("resource_quantity"),
|
||||||
|
"target_resource_quantity",
|
||||||
|
order.get("target_resource_quantity"),
|
||||||
|
"conversion_total_limit",
|
||||||
|
limit,
|
||||||
|
"conversion_total_weight",
|
||||||
|
weight,
|
||||||
|
"conversion_block_height",
|
||||||
|
wallet.get("snapshot_block_height"),
|
||||||
|
"conversion_at",
|
||||||
|
now(),
|
||||||
|
"estimated_resource_quantity",
|
||||||
|
quantity(sun, limit, weight),
|
||||||
|
"attempt_no",
|
||||||
|
attempt,
|
||||||
|
"active_slot",
|
||||||
|
1,
|
||||||
|
"wallet_execution_slot",
|
||||||
|
1,
|
||||||
|
"delegate_sun",
|
||||||
|
sun,
|
||||||
|
"fee_limit_sun",
|
||||||
|
fee,
|
||||||
|
"credential_id",
|
||||||
|
credential.get("id"),
|
||||||
|
"nonce",
|
||||||
|
nonce,
|
||||||
|
"signed_at",
|
||||||
|
now(),
|
||||||
|
"deadline",
|
||||||
|
deadline,
|
||||||
|
"intent",
|
||||||
|
body,
|
||||||
|
"signature",
|
||||||
|
RentalCrypto.sign(
|
||||||
|
identity.secret(credential),
|
||||||
|
"TASK",
|
||||||
|
key,
|
||||||
|
signed,
|
||||||
|
nonce,
|
||||||
|
"PUSH",
|
||||||
|
"/node/v1/task",
|
||||||
|
body),
|
||||||
|
"status",
|
||||||
|
"PENDING",
|
||||||
|
"reservation_status",
|
||||||
|
"DELEGATE".equals(type) ? "HELD" : "NONE",
|
||||||
|
"delivery_message_id",
|
||||||
|
id("MSG"),
|
||||||
|
"next_check_at",
|
||||||
|
now()));
|
||||||
|
// signed_at参与HMAC必须与毫秒值完全一致,不能用第二次now()。
|
||||||
|
store.execute(
|
||||||
|
"UPDATE rent_task SET signed_at=? WHERE task_no=?",
|
||||||
|
java.time.LocalDateTime.ofInstant(
|
||||||
|
Instant.ofEpochMilli(signed), java.time.ZoneOffset.UTC),
|
||||||
|
taskNo);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void reclaim(long orderId) {
|
||||||
|
tx(
|
||||||
|
() -> {
|
||||||
|
Map<String, Object> order = store.get("order", orderId, true);
|
||||||
|
if (!Arrays.asList("WAITING", "MANUAL_REVIEW")
|
||||||
|
.contains(text(order, "reclaim_status"))
|
||||||
|
|| order.get("next_reclaim_at") == null
|
||||||
|
|| time(order.get("next_reclaim_at")).isAfter(Instant.now())) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Map<String, Object> source =
|
||||||
|
store.one(
|
||||||
|
"SELECT x.* FROM rent_transaction x JOIN rent_task t ON"
|
||||||
|
+ " t.id=x.task_id WHERE t.order_id=? AND"
|
||||||
|
+ " t.task_type='DELEGATE' AND x.status='CONFIRMED' ORDER"
|
||||||
|
+ " BY x.id LIMIT 1",
|
||||||
|
orderId);
|
||||||
|
require(source != null, "缺少原确认委托");
|
||||||
|
Map<String, Object> wallet =
|
||||||
|
store.get("wallet", number(order, "wallet_id"), true);
|
||||||
|
if (store.one(
|
||||||
|
"SELECT id FROM rent_task WHERE wallet_id=? AND resource_type=?"
|
||||||
|
+ " AND wallet_execution_slot=1",
|
||||||
|
wallet.get("id"),
|
||||||
|
order.get("resource_type"))
|
||||||
|
!= null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (store.one(
|
||||||
|
"SELECT id FROM rent_task WHERE order_id=? AND"
|
||||||
|
+ " task_type='RECLAIM' AND active_slot=1",
|
||||||
|
orderId)
|
||||||
|
!= null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Map<String, Object> original =
|
||||||
|
store.get("task", number(source, "task_id"), false);
|
||||||
|
createTask(
|
||||||
|
order,
|
||||||
|
wallet,
|
||||||
|
"RECLAIM",
|
||||||
|
number(source, "amount_sun"),
|
||||||
|
number(original, "conversion_total_limit"),
|
||||||
|
number(original, "conversion_total_weight"),
|
||||||
|
source);
|
||||||
|
store.update(
|
||||||
|
"order",
|
||||||
|
orderId,
|
||||||
|
map("reclaim_status", "RUNNING", "next_reclaim_at", after(30)));
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 来自当前认证会话的事件先持久去重;节点自报成功只记录线索,不扣款。 */
|
||||||
|
public void report(long nodeId, Map<String, Object> report) {
|
||||||
|
String taskNo = input(report, "task_no", 64);
|
||||||
|
String eventId = input(report, "event_id", 40);
|
||||||
|
String kind = input(report, "state", 24);
|
||||||
|
require(eventId.matches("[A-Za-z0-9_-]+"), "事件编号非法");
|
||||||
|
Map<String, Object> initial =
|
||||||
|
store.one("SELECT * FROM rent_task WHERE task_no=? AND node_id=?", taskNo, nodeId);
|
||||||
|
require(initial != null, "任务不属于节点");
|
||||||
|
tx(
|
||||||
|
() -> {
|
||||||
|
Map<String, Object> order =
|
||||||
|
store.get("order", number(initial, "order_id"), true);
|
||||||
|
Map<String, Object> wallet =
|
||||||
|
store.get("wallet", number(initial, "wallet_id"), true);
|
||||||
|
Map<String, Object> task = store.get("task", number(initial, "id"), true);
|
||||||
|
String event = "NODE:" + nodeId + ":" + eventId;
|
||||||
|
if (store.one("SELECT id FROM rent_event WHERE event_no=?", event) != null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
long taskId = number(task, "id");
|
||||||
|
if ("ACK".equals(kind)) {
|
||||||
|
store.update("task", taskId, map("delivery_acked_at", now()));
|
||||||
|
} else if ("ACCEPTED".equals(kind) && "PENDING".equals(text(task, "status"))) {
|
||||||
|
store.update(
|
||||||
|
"task", taskId, map("status", "ACCEPTED", "accepted_at", now()));
|
||||||
|
} else if ("REJECTED".equals(kind)) {
|
||||||
|
require(
|
||||||
|
store.one("SELECT id FROM rent_transaction WHERE task_id=?", taskId)
|
||||||
|
== null
|
||||||
|
&& Arrays.asList("PENDING", "ACCEPTED", "UNKNOWN")
|
||||||
|
.contains(text(task, "status")),
|
||||||
|
"已存在广播线索,不能按未执行释放");
|
||||||
|
fail(task, order, wallet, "REJECTED");
|
||||||
|
} else if (Arrays.asList("BUILT", "BROADCASTED", "UNKNOWN", "RESULT")
|
||||||
|
.contains(kind)) {
|
||||||
|
require(
|
||||||
|
!Arrays.asList("REJECTED", "FAILED").contains(text(task, "status")),
|
||||||
|
"明确终结任务不可重新报告执行,应隔离核对");
|
||||||
|
String txId = text(report, "tx_id");
|
||||||
|
if (!txId.isEmpty()) {
|
||||||
|
require(txId.matches("[0-9a-fA-F]{64}"), "交易哈希无效");
|
||||||
|
Map<String, Object> existing =
|
||||||
|
store.one(
|
||||||
|
"SELECT * FROM rent_transaction WHERE task_id=?",
|
||||||
|
taskId);
|
||||||
|
if (existing != null) {
|
||||||
|
require(
|
||||||
|
txId.equalsIgnoreCase(text(existing, "tx_id")),
|
||||||
|
"一任务只能有一笔原交易");
|
||||||
|
} else {
|
||||||
|
store.insert(
|
||||||
|
"transaction",
|
||||||
|
map(
|
||||||
|
"task_id",
|
||||||
|
taskId,
|
||||||
|
"network",
|
||||||
|
text(task, "network"),
|
||||||
|
"tx_id",
|
||||||
|
txId.toLowerCase(Locale.ROOT),
|
||||||
|
"owner_address",
|
||||||
|
text(wallet, "address"),
|
||||||
|
"receiver_address",
|
||||||
|
text(order, "receiver_address"),
|
||||||
|
"transaction_type",
|
||||||
|
text(task, "task_type"),
|
||||||
|
"resource_type",
|
||||||
|
text(task, "resource_type"),
|
||||||
|
"amount_sun",
|
||||||
|
task.get("delegate_sun"),
|
||||||
|
"baseline_sun",
|
||||||
|
"DELEGATE".equals(text(task, "task_type"))
|
||||||
|
? 0
|
||||||
|
: task.get("delegate_sun"),
|
||||||
|
"status",
|
||||||
|
"REPORTED",
|
||||||
|
"next_check_at",
|
||||||
|
now()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!"VERIFIED".equals(text(task, "status"))) {
|
||||||
|
store.update(
|
||||||
|
"task",
|
||||||
|
taskId,
|
||||||
|
map(
|
||||||
|
"status",
|
||||||
|
"UNKNOWN".equals(kind) ? "UNKNOWN" : "BROADCASTED",
|
||||||
|
"next_check_at",
|
||||||
|
now()));
|
||||||
|
if ("DELEGATE".equals(text(task, "task_type"))) {
|
||||||
|
store.update(
|
||||||
|
"order", number(order, "id"), map("status", "VERIFYING"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (!Arrays.asList("VERIFIED", "FAILED", "REJECTED")
|
||||||
|
.contains(text(task, "status"))) {
|
||||||
|
throw new IllegalArgumentException("未知节点事件");
|
||||||
|
}
|
||||||
|
store.insert(
|
||||||
|
"event",
|
||||||
|
map(
|
||||||
|
"event_no",
|
||||||
|
event,
|
||||||
|
"object_type",
|
||||||
|
"TASK",
|
||||||
|
"object_id",
|
||||||
|
taskId,
|
||||||
|
"action",
|
||||||
|
kind,
|
||||||
|
"actor_user_id",
|
||||||
|
0,
|
||||||
|
"node_id",
|
||||||
|
nodeId,
|
||||||
|
"reason",
|
||||||
|
"已认证节点事件,成功仍须独立链上核验"));
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public void verify(long taskId) {
|
||||||
|
Map<String, Object> task = store.get("task", taskId, false);
|
||||||
|
Map<String, Object> record =
|
||||||
|
store.one("SELECT * FROM rent_transaction WHERE task_id=?", taskId);
|
||||||
|
if (record == null
|
||||||
|
|| "CONFIRMED".equals(text(record, "status"))
|
||||||
|
|| "FAILED".equals(text(record, "status"))) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Map<String, Object> proof =
|
||||||
|
chain.verify(
|
||||||
|
task,
|
||||||
|
text(record, "tx_id"),
|
||||||
|
text(record, "owner_address"),
|
||||||
|
text(record, "receiver_address"));
|
||||||
|
tx(
|
||||||
|
() -> {
|
||||||
|
Map<String, Object> order = store.get("order", number(task, "order_id"), true);
|
||||||
|
Map<String, Object> wallet =
|
||||||
|
store.get("wallet", number(task, "wallet_id"), true);
|
||||||
|
Map<String, Object> current = store.get("task", taskId, true);
|
||||||
|
Map<String, Object> currentTx =
|
||||||
|
store.get("transaction", number(record, "id"), true);
|
||||||
|
if ("CONFIRMED".equals(text(currentTx, "status"))
|
||||||
|
|| "FAILED".equals(text(currentTx, "status"))) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if ("FAILED".equals(text(proof, "status"))) {
|
||||||
|
store.update("transaction", number(record, "id"), map("status", "FAILED"));
|
||||||
|
fail(current, order, wallet, "FAILED");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Map<String, Object> fields = new LinkedHashMap<>(proof);
|
||||||
|
fields.remove("delivery_proven");
|
||||||
|
fields.put("evidence", orders.encode(proof));
|
||||||
|
fields.put("confirmed_at", now());
|
||||||
|
store.update("transaction", number(record, "id"), fields);
|
||||||
|
boolean delegate = "DELEGATE".equals(text(current, "task_type"));
|
||||||
|
String prefix = text(current, "resource_type").toLowerCase(Locale.ROOT);
|
||||||
|
Map<String, Object> barrier =
|
||||||
|
map(
|
||||||
|
"snapshot_min_block_height",
|
||||||
|
Math.max(
|
||||||
|
number(wallet, "snapshot_min_block_height"),
|
||||||
|
number(proof, "block_height")),
|
||||||
|
"snapshot_expires_at",
|
||||||
|
null);
|
||||||
|
if (delegate && "HELD".equals(text(current, "reservation_status"))) {
|
||||||
|
long remaining =
|
||||||
|
Math.subtractExact(
|
||||||
|
number(wallet, prefix + "_reserved_sun"),
|
||||||
|
number(current, "delegate_sun"));
|
||||||
|
require(remaining >= 0, "预留账实不一致");
|
||||||
|
barrier.put(prefix + "_reserved_sun", remaining);
|
||||||
|
}
|
||||||
|
store.update("wallet", number(wallet, "id"), barrier);
|
||||||
|
store.update(
|
||||||
|
"task",
|
||||||
|
taskId,
|
||||||
|
map(
|
||||||
|
"status",
|
||||||
|
"VERIFIED",
|
||||||
|
"wallet_execution_slot",
|
||||||
|
null,
|
||||||
|
"reservation_status",
|
||||||
|
delegate ? "COMMITTED" : "NONE"));
|
||||||
|
long orderId = number(order, "id");
|
||||||
|
if (delegate) {
|
||||||
|
Instant start = time(proof.get("block_time")),
|
||||||
|
expires = start.plusSeconds(number(order, "duration_seconds"));
|
||||||
|
boolean delivered =
|
||||||
|
Boolean.TRUE.equals(proof.get("delivery_proven"))
|
||||||
|
&& number(proof, "verified_resource_quantity")
|
||||||
|
>= number(order, "target_resource_quantity")
|
||||||
|
&& expires.isAfter(Instant.now());
|
||||||
|
if (delivered) {
|
||||||
|
funds.charge(order);
|
||||||
|
}
|
||||||
|
store.update(
|
||||||
|
"order",
|
||||||
|
orderId,
|
||||||
|
map(
|
||||||
|
"status",
|
||||||
|
delivered ? "SUCCESS" : "MANUAL_REVIEW",
|
||||||
|
"service_started_at",
|
||||||
|
proof.get("block_time"),
|
||||||
|
"service_expires_at",
|
||||||
|
java.time.LocalDateTime.ofInstant(
|
||||||
|
expires, java.time.ZoneOffset.UTC),
|
||||||
|
"reclaim_status",
|
||||||
|
"WAITING",
|
||||||
|
"next_reclaim_at",
|
||||||
|
java.time.LocalDateTime.ofInstant(
|
||||||
|
expires, java.time.ZoneOffset.UTC),
|
||||||
|
"error_code",
|
||||||
|
delivered ? null : "DELIVERY_EVIDENCE_REVIEW"));
|
||||||
|
if (delivered) {
|
||||||
|
orders.webhook(order, "SUCCESS", "ORDER:" + orderId + ":SUCCESS");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
store.update(
|
||||||
|
"order",
|
||||||
|
orderId,
|
||||||
|
map("reclaim_status", "RECOVERING", "next_reclaim_at", after(15)));
|
||||||
|
}
|
||||||
|
store.event("TASK", taskId, "CHAIN_CONFIRMED", 0, "独立核验并同事务提升快照屏障,禁止旧快照重新出租");
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fail(
|
||||||
|
Map<String, Object> task,
|
||||||
|
Map<String, Object> order,
|
||||||
|
Map<String, Object> wallet,
|
||||||
|
String state) {
|
||||||
|
boolean delegate = "DELEGATE".equals(text(task, "task_type"));
|
||||||
|
long taskId = number(task, "id"), orderId = number(order, "id");
|
||||||
|
if (delegate && "HELD".equals(text(task, "reservation_status"))) {
|
||||||
|
String column = text(task, "resource_type").toLowerCase(Locale.ROOT) + "_reserved_sun";
|
||||||
|
long remaining =
|
||||||
|
Math.subtractExact(number(wallet, column), number(task, "delegate_sun"));
|
||||||
|
require(remaining >= 0, "资源预留冲突");
|
||||||
|
store.update("wallet", number(wallet, "id"), map(column, remaining));
|
||||||
|
}
|
||||||
|
store.update(
|
||||||
|
"task",
|
||||||
|
taskId,
|
||||||
|
map(
|
||||||
|
"status",
|
||||||
|
state,
|
||||||
|
"active_slot",
|
||||||
|
null,
|
||||||
|
"wallet_execution_slot",
|
||||||
|
null,
|
||||||
|
"reservation_status",
|
||||||
|
delegate ? "RELEASED" : "NONE"));
|
||||||
|
if (delegate) {
|
||||||
|
boolean retry =
|
||||||
|
number(task, "attempt_no") < 4
|
||||||
|
&& time(order.get("dispatch_deadline")).isAfter(Instant.now());
|
||||||
|
if (!retry) {
|
||||||
|
funds.release(order);
|
||||||
|
orders.webhook(order, "FAILED", "ORDER:" + orderId + ":FAILED");
|
||||||
|
}
|
||||||
|
store.update(
|
||||||
|
"order",
|
||||||
|
orderId,
|
||||||
|
map(
|
||||||
|
"status",
|
||||||
|
retry ? "WAITING" : "FAILED",
|
||||||
|
"relation_slot",
|
||||||
|
null,
|
||||||
|
"wallet_id",
|
||||||
|
null));
|
||||||
|
} else {
|
||||||
|
store.update(
|
||||||
|
"order",
|
||||||
|
orderId,
|
||||||
|
map("reclaim_status", "WAITING", "next_reclaim_at", after(60)));
|
||||||
|
}
|
||||||
|
store.event("TASK", taskId, "SAFE_FAILURE", 0, "明确拒绝未构建或链上确认失败;未知不走本分支");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void recoverResource(long orderId) {
|
||||||
|
Map<String, Object> order = store.get("order", orderId, false);
|
||||||
|
if (!"RECOVERING".equals(text(order, "reclaim_status"))) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Map<String, Object> wallet = store.get("wallet", number(order, "wallet_id"), false);
|
||||||
|
Map<String, Object> snapshot =
|
||||||
|
chain.snapshot(text(wallet, "network"), text(wallet, "address"));
|
||||||
|
if (chain.relation(
|
||||||
|
text(wallet, "network"),
|
||||||
|
text(wallet, "address"),
|
||||||
|
text(order, "receiver_address"),
|
||||||
|
text(order, "resource_type"))
|
||||||
|
!= 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 可委托本金>0不代表本单资源已恢复。保守要求原本金可再次委托,减去本地占用和留存。
|
||||||
|
Map<String, Object> source =
|
||||||
|
store.one(
|
||||||
|
"SELECT x.* FROM rent_transaction x JOIN rent_task t ON t.id=x.task_id"
|
||||||
|
+ " WHERE t.order_id=? AND t.task_type='DELEGATE' AND"
|
||||||
|
+ " x.status='CONFIRMED'",
|
||||||
|
orderId);
|
||||||
|
String prefix = text(order, "resource_type").toLowerCase(Locale.ROOT);
|
||||||
|
if (number(snapshot, prefix + "_delegatable_sun")
|
||||||
|
- number(wallet, prefix + "_retain_sun")
|
||||||
|
- number(wallet, prefix + "_reserved_sun")
|
||||||
|
< number(source, "amount_sun")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
tx(
|
||||||
|
() -> {
|
||||||
|
Map<String, Object> current = store.get("order", orderId, true);
|
||||||
|
Map<String, Object> latest = store.get("wallet", number(wallet, "id"), true);
|
||||||
|
if (!"RECOVERING".equals(text(current, "reclaim_status"))) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
require(
|
||||||
|
number(latest, "version") == number(wallet, "version")
|
||||||
|
&& number(snapshot, "snapshot_block_height")
|
||||||
|
>= number(latest, "snapshot_min_block_height"),
|
||||||
|
"资源恢复快照已过时");
|
||||||
|
store.update("wallet", number(wallet, "id"), snapshot);
|
||||||
|
store.update(
|
||||||
|
"order",
|
||||||
|
orderId,
|
||||||
|
map(
|
||||||
|
"reclaim_status",
|
||||||
|
"DONE",
|
||||||
|
"relation_slot",
|
||||||
|
null,
|
||||||
|
"next_reclaim_at",
|
||||||
|
null));
|
||||||
|
orders.webhook(current, "RECLAIMED", "ORDER:" + orderId + ":RECLAIMED");
|
||||||
|
store.event("ORDER", orderId, "RECLAIMED", 0, "原本金已撤销且可委托资源恢复");
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 无txId的未知任务只能补充独立核实的原交易,不能直接标失败或重新派单。 */
|
||||||
|
public void attach(long taskId, String txId, long actor, String reason) {
|
||||||
|
Map<String, Object> task = store.get("task", taskId, false);
|
||||||
|
require(
|
||||||
|
task.get("active_slot") != null
|
||||||
|
&& !Arrays.asList("REJECTED", "FAILED").contains(text(task, "status")),
|
||||||
|
"只能补充原在途任务的交易证据");
|
||||||
|
Map<String, Object> wallet = store.get("wallet", number(task, "wallet_id"), false);
|
||||||
|
Map<String, Object> order = store.get("order", number(task, "order_id"), false);
|
||||||
|
chain.verify(task, txId, text(wallet, "address"), text(order, "receiver_address"));
|
||||||
|
report(
|
||||||
|
number(task, "node_id"),
|
||||||
|
map(
|
||||||
|
"task_no",
|
||||||
|
text(task, "task_no"),
|
||||||
|
"event_id",
|
||||||
|
RentalValues.id("ADMIN"),
|
||||||
|
"state",
|
||||||
|
"BUILT",
|
||||||
|
"tx_id",
|
||||||
|
txId));
|
||||||
|
tx(
|
||||||
|
() -> {
|
||||||
|
store.event("TASK", taskId, "ATTACH_ORIGINAL_TX", actor, reason);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
verify(taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 异常委托完成原本金回收后,人工可终结未确认收入的HELD订单,不能释放未知在途。 */
|
||||||
|
public void resolveRecovered(long orderId, long actor, String reason) {
|
||||||
|
tx(
|
||||||
|
() -> {
|
||||||
|
Map<String, Object> order = store.get("order", orderId, true);
|
||||||
|
require(
|
||||||
|
"MANUAL_REVIEW".equals(text(order, "status"))
|
||||||
|
&& "DONE".equals(text(order, "reclaim_status"))
|
||||||
|
&& "HELD".equals(text(order, "fund_status")),
|
||||||
|
"仅本金及资源已确认回收的人工核对冻结单可解冻");
|
||||||
|
funds.release(order);
|
||||||
|
store.update("order", orderId, map("status", "FAILED", "remark", reason));
|
||||||
|
orders.webhook(order, "FAILED", "ORDER:" + orderId + ":FAILED");
|
||||||
|
store.event("ORDER", orderId, "RESOLVE_AFTER_RECLAIM", actor, reason);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 在租期间监测外部提前撤销/追加。发现差异只隔离,不擅自撤销他人本金或自动退款。 */
|
||||||
|
public void monitor(long orderId) {
|
||||||
|
Map<String, Object> order = store.get("order", orderId, false);
|
||||||
|
if (!"SUCCESS".equals(text(order, "status"))
|
||||||
|
|| !"WAITING".equals(text(order, "reclaim_status"))) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Map<String, Object> wallet = store.get("wallet", number(order, "wallet_id"), false);
|
||||||
|
Map<String, Object> source =
|
||||||
|
store.one(
|
||||||
|
"SELECT x.* FROM rent_transaction x JOIN rent_task t ON t.id=x.task_id"
|
||||||
|
+ " WHERE t.order_id=? AND t.task_type='DELEGATE' AND"
|
||||||
|
+ " x.status='CONFIRMED'",
|
||||||
|
orderId);
|
||||||
|
require(source != null, "缺少原始委托证据");
|
||||||
|
long current =
|
||||||
|
chain.relation(
|
||||||
|
text(order, "network"),
|
||||||
|
text(wallet, "address"),
|
||||||
|
text(order, "receiver_address"),
|
||||||
|
text(order, "resource_type"));
|
||||||
|
if (current != number(source, "amount_sun")) {
|
||||||
|
tx(
|
||||||
|
() -> {
|
||||||
|
Map<String, Object> latest = store.get("order", orderId, true);
|
||||||
|
if ("SUCCESS".equals(text(latest, "status"))
|
||||||
|
&& "WAITING".equals(text(latest, "reclaim_status"))) {
|
||||||
|
store.update(
|
||||||
|
"order",
|
||||||
|
orderId,
|
||||||
|
map(
|
||||||
|
"status",
|
||||||
|
"MANUAL_REVIEW",
|
||||||
|
"reclaim_status",
|
||||||
|
"MANUAL_REVIEW",
|
||||||
|
"error_code",
|
||||||
|
"DELEGATION_CHANGED",
|
||||||
|
"next_reclaim_at",
|
||||||
|
after(60)));
|
||||||
|
store.event(
|
||||||
|
"ORDER",
|
||||||
|
orderId,
|
||||||
|
"DELEGATION_CHANGED",
|
||||||
|
0,
|
||||||
|
"原地址对委托关系已发生外部变化,隔离并等待人工处理");
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
import java.sql.Timestamp;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneOffset;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/** 租赁专用精度和输入规则。SUN、资源量使用精确整数,USDT最多六位小数。 */
|
||||||
|
public final class RentalValues {
|
||||||
|
public static final BigDecimal ZERO = new BigDecimal("0.000000");
|
||||||
|
|
||||||
|
private RentalValues() {}
|
||||||
|
|
||||||
|
public static Map<String, Object> map(Object... pairs) {
|
||||||
|
Map<String, Object> result = new LinkedHashMap<>();
|
||||||
|
for (int i = 0; i < pairs.length; i += 2) {
|
||||||
|
result.put((String) pairs[i], pairs[i + 1]);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void require(boolean condition, String message) {
|
||||||
|
if (!condition) {
|
||||||
|
throw new IllegalArgumentException(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String text(Map<String, Object> row, String key) {
|
||||||
|
Object value = row.get(key);
|
||||||
|
return value == null ? "" : value.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String input(Map<String, Object> row, String key, int max) {
|
||||||
|
String value = text(row, key).trim();
|
||||||
|
require(
|
||||||
|
!value.isEmpty()
|
||||||
|
&& value.length() <= max
|
||||||
|
&& !value.contains("\n")
|
||||||
|
&& !value.contains("\r"),
|
||||||
|
"参数不合法:" + key);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static long number(Map<String, Object> row, String key) {
|
||||||
|
require(
|
||||||
|
!(row.get(key) instanceof Double) && !(row.get(key) instanceof Float),
|
||||||
|
"整数请使用精确整数或字符串:" + key);
|
||||||
|
return new BigDecimal(text(row, key)).longValueExact();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BigDecimal money(Object value) {
|
||||||
|
require(
|
||||||
|
value != null && !(value instanceof Double) && !(value instanceof Float),
|
||||||
|
"USDT请使用最多6位小数的十进制字符串");
|
||||||
|
return new BigDecimal(value.toString()).setScale(6, RoundingMode.UNNECESSARY);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BigDecimal amount(Map<String, Object> row, String key) {
|
||||||
|
return money(row.get(key));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static LocalDateTime now() {
|
||||||
|
return LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static LocalDateTime after(long seconds) {
|
||||||
|
return now().plusSeconds(seconds);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Instant time(Object value) {
|
||||||
|
if (value instanceof Timestamp) {
|
||||||
|
return ((Timestamp) value).toLocalDateTime().toInstant(ZoneOffset.UTC);
|
||||||
|
}
|
||||||
|
return ((LocalDateTime) value).toInstant(ZoneOffset.UTC);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String id(String prefix) {
|
||||||
|
return prefix + UUID.randomUUID().toString().replace("-", "");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String network(String value) {
|
||||||
|
require("NILE".equals(value) || "MAINNET".equals(value), "仅支持NILE或MAINNET");
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String resource(String value) {
|
||||||
|
require("ENERGY".equals(value) || "BANDWIDTH".equals(value), "资源类型不合法");
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 用BigDecimal防止中间乘积溢出;所有落库整数都做精确范围检查。 */
|
||||||
|
public static long target(long quantity, BigDecimal percent) {
|
||||||
|
require(quantity > 0 && percent.signum() > 0, "资源数量和冗余必须大于0");
|
||||||
|
return BigDecimal.valueOf(quantity)
|
||||||
|
.multiply(BigDecimal.ONE.add(percent.movePointLeft(2)))
|
||||||
|
.setScale(0, RoundingMode.CEILING)
|
||||||
|
.max(BigDecimal.valueOf(Math.addExact(quantity, 1)))
|
||||||
|
.longValueExact();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static long principal(long target, long limit, long weight) {
|
||||||
|
require(target > 0 && limit > 0 && weight > 0, "链上换算参数无效");
|
||||||
|
return BigDecimal.valueOf(target)
|
||||||
|
.multiply(BigDecimal.valueOf(weight))
|
||||||
|
.divide(BigDecimal.valueOf(limit), 0, RoundingMode.CEILING)
|
||||||
|
.movePointRight(6)
|
||||||
|
.longValueExact();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static long quantity(long sun, long limit, long weight) {
|
||||||
|
require(sun > 0 && limit > 0 && weight > 0, "链上资源参数无效");
|
||||||
|
return BigDecimal.valueOf(sun)
|
||||||
|
.multiply(BigDecimal.valueOf(limit))
|
||||||
|
.divide(BigDecimal.valueOf(weight).movePointRight(6), 0, RoundingMode.FLOOR)
|
||||||
|
.longValueExact();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,294 @@
|
|||||||
|
package com.ruoyi.system.rental;
|
||||||
|
|
||||||
|
import static com.ruoyi.system.rental.RentalValues.*;
|
||||||
|
|
||||||
|
import okhttp3.*;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
/** 有界分批扫描持久事实,失败按记录隔离;关闭广播或节点离线仍继续核对原交易。 */
|
||||||
|
@Component
|
||||||
|
@ConditionalOnProperty(name = "rental.enabled", havingValue = "true")
|
||||||
|
public class RentalWorkers {
|
||||||
|
private static final Logger LOG = LoggerFactory.getLogger(RentalWorkers.class);
|
||||||
|
private final RentalStore store;
|
||||||
|
private final RentalTasks tasks;
|
||||||
|
private final RentalSocket socket;
|
||||||
|
private final RentalIdentity identity;
|
||||||
|
private final OkHttpClient callbacks = RentalHttp.callbackClient();
|
||||||
|
private long walletCursor;
|
||||||
|
private long monitoringCursor;
|
||||||
|
private long dispatchCursor;
|
||||||
|
|
||||||
|
@org.springframework.beans.factory.annotation.Autowired
|
||||||
|
private RentalReconciliation reconciliation;
|
||||||
|
|
||||||
|
@Scheduled(cron = "0 0 2 * * ?", zone = "UTC")
|
||||||
|
public void reconciliation() {
|
||||||
|
long after = 0;
|
||||||
|
while (true) {
|
||||||
|
Map<String, Object> result = reconciliation.check(after);
|
||||||
|
if (!((List<?>) result.get("differences")).isEmpty()) {
|
||||||
|
LOG.error("租赁账户与不可变流水存在差异,请通过受保护的核对接口检查,afterId={}", after);
|
||||||
|
}
|
||||||
|
if (!Boolean.TRUE.equals(result.get("has_more"))) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
after = number(result, "next_after_id");
|
||||||
|
}
|
||||||
|
if (!reconciliation.reservations().isEmpty()) {
|
||||||
|
LOG.error("租赁SUN预留与任务占用存在差异,禁止人工直接覆盖,请核对原任务");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public RentalWorkers(
|
||||||
|
RentalStore store, RentalTasks tasks, RentalSocket socket, RentalIdentity identity) {
|
||||||
|
this.store = store;
|
||||||
|
this.tasks = tasks;
|
||||||
|
this.socket = socket;
|
||||||
|
this.identity = identity;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Scheduled(fixedDelay = 15000)
|
||||||
|
public void heartbeat() {
|
||||||
|
socket.tick();
|
||||||
|
store.execute(
|
||||||
|
"UPDATE rent_node SET connection_status='OFFLINE',version=version+1,updated_at=?"
|
||||||
|
+ " WHERE connection_status<>'OFFLINE' AND heartbeat_expires_at<?",
|
||||||
|
now(),
|
||||||
|
now());
|
||||||
|
// 认证仅允许前后60秒,nonce保留180秒后分批清理仍不会重新接受过期请求。
|
||||||
|
store.execute("DELETE FROM rent_nonce WHERE expires_at<? LIMIT 1000", now());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Scheduled(fixedDelay = 5000)
|
||||||
|
public void dispatch() {
|
||||||
|
// 主键轮转,资源不足的早期订单不能永久阻塞其他网络或资源类型的订单。
|
||||||
|
List<Map<String, Object>> waiting =
|
||||||
|
store.rows(
|
||||||
|
"SELECT id FROM rent_order WHERE status='WAITING' AND id>? ORDER BY id"
|
||||||
|
+ " LIMIT 20",
|
||||||
|
dispatchCursor);
|
||||||
|
if (waiting.isEmpty()) {
|
||||||
|
dispatchCursor = 0;
|
||||||
|
}
|
||||||
|
for (Map<String, Object> row : waiting) {
|
||||||
|
dispatchCursor = number(row, "id");
|
||||||
|
try {
|
||||||
|
tasks.dispatch(dispatchCursor);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
LOG.warn("租赁订单调度待重试,orderId={}", dispatchCursor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
each(
|
||||||
|
"SELECT id FROM rent_order WHERE reclaim_status IN ('WAITING','MANUAL_REVIEW') AND"
|
||||||
|
+ " next_reclaim_at<=UTC_TIMESTAMP(3) ORDER BY next_reclaim_at LIMIT 20",
|
||||||
|
tasks::reclaim);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Scheduled(fixedDelay = 10000)
|
||||||
|
public void verify() {
|
||||||
|
each(
|
||||||
|
"SELECT id FROM rent_task WHERE status IN"
|
||||||
|
+ " ('PENDING','ACCEPTED','BROADCASTED','UNKNOWN') AND (next_check_at IS NULL"
|
||||||
|
+ " OR next_check_at<=UTC_TIMESTAMP(3)) ORDER BY next_check_at LIMIT 20",
|
||||||
|
id -> {
|
||||||
|
try {
|
||||||
|
tasks.verify(id);
|
||||||
|
store.execute(
|
||||||
|
"UPDATE rent_task SET"
|
||||||
|
+ " status='UNKNOWN',version=version+1,updated_at=? WHERE id=?"
|
||||||
|
+ " AND status IN ('PENDING','ACCEPTED') AND deadline<?",
|
||||||
|
now(),
|
||||||
|
id,
|
||||||
|
now());
|
||||||
|
} finally {
|
||||||
|
store.execute(
|
||||||
|
"UPDATE rent_task SET next_check_at=? WHERE id=?", after(30), id);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
each(
|
||||||
|
"SELECT id FROM rent_order WHERE reclaim_status='RECOVERING' AND"
|
||||||
|
+ " next_reclaim_at<=UTC_TIMESTAMP(3) ORDER BY next_reclaim_at LIMIT 20",
|
||||||
|
id -> {
|
||||||
|
try {
|
||||||
|
tasks.recoverResource(id);
|
||||||
|
} finally {
|
||||||
|
// 即使RPC失败也推进重试时间,避免故障记录占满每批扫描窗口。
|
||||||
|
store.execute(
|
||||||
|
"UPDATE rent_order SET next_reclaim_at=? WHERE id=? AND"
|
||||||
|
+ " reclaim_status='RECOVERING'",
|
||||||
|
after(30),
|
||||||
|
id);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Scheduled(fixedDelay = 15000)
|
||||||
|
public void snapshots() {
|
||||||
|
// 按主键轮转,不能让最早20个故障RPC钱包永久阻塞后续供应钱包。
|
||||||
|
List<Map<String, Object>> rows =
|
||||||
|
store.rows(
|
||||||
|
"SELECT id FROM rent_wallet WHERE id>? AND status='ACTIVE' AND"
|
||||||
|
+ " (snapshot_expires_at IS NULL OR snapshot_expires_at<=?) ORDER BY id"
|
||||||
|
+ " LIMIT 20",
|
||||||
|
walletCursor,
|
||||||
|
now());
|
||||||
|
if (rows.isEmpty()) {
|
||||||
|
walletCursor = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (Map<String, Object> row : rows) {
|
||||||
|
walletCursor = number(row, "id");
|
||||||
|
try {
|
||||||
|
tasks.refresh(walletCursor);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
LOG.warn("租赁钱包快照暂不可用,walletId={}", walletCursor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void each(String sql, Consumer<Long> action) {
|
||||||
|
for (Map<String, Object> row : store.rows(sql)) {
|
||||||
|
long id = number(row, "id");
|
||||||
|
try {
|
||||||
|
action.accept(id);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
LOG.warn("租赁后台核对暂未完成,recordId={},下轮继续;敏感异常不记录", id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Scheduled(fixedDelay = 30000)
|
||||||
|
public void monitor() {
|
||||||
|
List<Map<String, Object>> rows =
|
||||||
|
store.rows(
|
||||||
|
"SELECT id FROM rent_order WHERE id>? AND status='SUCCESS' AND"
|
||||||
|
+ " reclaim_status='WAITING' AND service_expires_at>? ORDER BY id LIMIT"
|
||||||
|
+ " 20",
|
||||||
|
monitoringCursor,
|
||||||
|
now());
|
||||||
|
if (rows.isEmpty()) {
|
||||||
|
monitoringCursor = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (Map<String, Object> row : rows) {
|
||||||
|
monitoringCursor = number(row, "id");
|
||||||
|
try {
|
||||||
|
tasks.monitor(monitoringCursor);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
LOG.warn("租赁在租委托监测待重试,orderId={}", monitoringCursor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Scheduled(fixedDelay = 5000)
|
||||||
|
public void webhooks() {
|
||||||
|
for (Map<String, Object> candidate :
|
||||||
|
store.rows(
|
||||||
|
"SELECT id FROM rent_webhook WHERE status IN ('PENDING','SENDING') AND"
|
||||||
|
+ " (next_attempt_at IS NULL OR next_attempt_at<=?) AND (lock_until IS"
|
||||||
|
+ " NULL OR lock_until<?) ORDER BY id LIMIT 20",
|
||||||
|
now(),
|
||||||
|
now())) {
|
||||||
|
long id = number(candidate, "id");
|
||||||
|
String lease = RentalValues.id("LEASE");
|
||||||
|
Map<String, Object> row =
|
||||||
|
tasks.tx(
|
||||||
|
() -> {
|
||||||
|
Map<String, Object> current = store.get("webhook", id, true);
|
||||||
|
if (!Arrays.asList("PENDING", "SENDING")
|
||||||
|
.contains(text(current, "status"))
|
||||||
|
|| (current.get("lock_until") != null
|
||||||
|
&& time(current.get("lock_until"))
|
||||||
|
.isAfter(java.time.Instant.now()))) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
store.update(
|
||||||
|
"webhook",
|
||||||
|
id,
|
||||||
|
map(
|
||||||
|
"status",
|
||||||
|
"SENDING",
|
||||||
|
"lock_owner",
|
||||||
|
lease,
|
||||||
|
"lock_until",
|
||||||
|
after(30),
|
||||||
|
"attempt_count",
|
||||||
|
number(current, "attempt_count") + 1));
|
||||||
|
return store.get("webhook", id, false);
|
||||||
|
});
|
||||||
|
if (row == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
boolean acked = false;
|
||||||
|
try {
|
||||||
|
Map<String, Object> order = store.get("order", number(row, "order_id"), false);
|
||||||
|
String url = text(order, "notify_url");
|
||||||
|
if (url.isEmpty()) {
|
||||||
|
acked = true;
|
||||||
|
} else {
|
||||||
|
RentalHttp.checkUrl(url);
|
||||||
|
Map<String, Object> credential =
|
||||||
|
store.one(
|
||||||
|
"SELECT * FROM rent_credential WHERE owner_type='APP' AND"
|
||||||
|
+ " owner_id=? AND status='ACTIVE' AND (expires_at IS NULL"
|
||||||
|
+ " OR expires_at>?) ORDER BY id DESC LIMIT 1",
|
||||||
|
order.get("app_id"),
|
||||||
|
now());
|
||||||
|
require(credential != null, "无有效回调凭证");
|
||||||
|
String key = text(credential, "api_key");
|
||||||
|
String nonce = RentalCrypto.random();
|
||||||
|
String body = text(row, "payload");
|
||||||
|
long timestamp = System.currentTimeMillis();
|
||||||
|
HttpUrl parsed = HttpUrl.parse(url);
|
||||||
|
require(parsed != null && parsed.query() == null, "回调URL不允许查询串");
|
||||||
|
Request request =
|
||||||
|
new Request.Builder()
|
||||||
|
.url(url)
|
||||||
|
.header("X-Rent-Key", key)
|
||||||
|
.header("X-Rent-Timestamp", Long.toString(timestamp))
|
||||||
|
.header("X-Rent-Nonce", nonce)
|
||||||
|
.header(
|
||||||
|
"X-Rent-Signature",
|
||||||
|
RentalCrypto.sign(
|
||||||
|
identity.secret(credential),
|
||||||
|
"WEBHOOK",
|
||||||
|
key,
|
||||||
|
timestamp,
|
||||||
|
nonce,
|
||||||
|
"POST",
|
||||||
|
parsed.encodedPath(),
|
||||||
|
body))
|
||||||
|
.post(
|
||||||
|
RequestBody.create(
|
||||||
|
MediaType.parse("application/json"), body))
|
||||||
|
.build();
|
||||||
|
try (Response response = callbacks.newCall(request).execute()) {
|
||||||
|
acked = response.code() == 200 && "ok".equals(RentalHttp.body(response));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception ex) {
|
||||||
|
/* 不记录URL、签名或响应原文,保留同一事件下次重试。 */
|
||||||
|
}
|
||||||
|
int attempt = (int) number(row, "attempt_count");
|
||||||
|
store.execute(
|
||||||
|
"UPDATE rent_webhook SET"
|
||||||
|
+ " status=?,next_attempt_at=?,lock_owner=NULL,lock_until=NULL,last_error=?,version=version+1,updated_at=?"
|
||||||
|
+ " WHERE id=? AND lock_owner=?",
|
||||||
|
acked ? "ACKED" : attempt >= 10 ? "DEAD" : "PENDING",
|
||||||
|
after(Math.min(3600, 1L << Math.min(attempt, 11))),
|
||||||
|
acked ? null : "回调未确认,请核对凭证、目标网络和响应",
|
||||||
|
now(),
|
||||||
|
id,
|
||||||
|
lease);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -44,4 +44,11 @@ public class TronServiceProvider {
|
|||||||
if (networkType == NETWORK_MAINNET) return mainnetService;
|
if (networkType == NETWORK_MAINNET) return mainnetService;
|
||||||
throw new CustomException("TRON 全局网络类型非法:" + networkType);
|
throw new CustomException("TRON 全局网络类型非法:" + networkType);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 租赁订单按自身锁定网络查询,不能被全局支付网络切换影响。仅返回服务,不执行广播。 */
|
||||||
|
public ITronService getServiceForNetwork(String network) {
|
||||||
|
if ("NILE".equals(network)) { return nileService; }
|
||||||
|
if ("MAINNET".equals(network)) { return mainnetService; }
|
||||||
|
throw new IllegalArgumentException("TRON网络类型非法");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,90 @@
|
|||||||
|
-- 租赁V2.2菜单与细粒度按钮权限,可重复执行;不自动授予现有角色。
|
||||||
|
-- 执行后请通过若依角色管理分别分配商户、供应商、运营及独立财务审批角色。
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '资源租赁',0,90,'rental','Layout',1,0,'M','0','0','','money','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE parent_id=0 AND path='rental');
|
||||||
|
SET @rent_parent=(SELECT menu_id FROM sys_menu WHERE parent_id=0 AND path='rental' LIMIT 1);
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '租赁工作台',@rent_parent,0,'portal','rental/index',1,0,'C','0','0','rent:portal:view','dashboard','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE perms='rent:portal:view');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '商户应用',@rent_parent,1,'admin-app','system/rentApp/index',1,0,'C','0','0','rent:manage:list','list','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE parent_id=@rent_parent AND path='admin-app');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '供应节点',@rent_parent,2,'admin-node','system/rentNode/index',1,0,'C','0','0','rent:manage:list','list','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE parent_id=@rent_parent AND path='admin-node');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '供应钱包',@rent_parent,3,'admin-wallet','system/rentWallet/index',1,0,'C','0','0','rent:manage:list','list','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE parent_id=@rent_parent AND path='admin-wallet');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '租赁套餐',@rent_parent,4,'admin-package','system/rentPackage/index',1,0,'C','0','0','rent:manage:list','list','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE parent_id=@rent_parent AND path='admin-package');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '资金账户',@rent_parent,5,'admin-account','system/rentAccount/index',1,0,'C','0','0','rent:manage:list','list','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE parent_id=@rent_parent AND path='admin-account');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '租赁订单',@rent_parent,6,'admin-order','system/rentOrder/index',1,0,'C','0','0','rent:manage:list','list','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE parent_id=@rent_parent AND path='admin-order');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '执行任务',@rent_parent,7,'admin-task','system/rentTask/index',1,0,'C','0','0','rent:manage:list','list','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE parent_id=@rent_parent AND path='admin-task');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '链上交易',@rent_parent,8,'admin-transaction','system/rentTransaction/index',1,0,'C','0','0','rent:manage:list','list','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE parent_id=@rent_parent AND path='admin-transaction');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '资金流水',@rent_parent,9,'admin-ledger','system/rentLedger/index',1,0,'C','0','0','rent:manage:list','list','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE parent_id=@rent_parent AND path='admin-ledger');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '供应商结算',@rent_parent,10,'admin-settlement','system/rentSettlement/index',1,0,'C','0','0','rent:manage:list','list','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE parent_id=@rent_parent AND path='admin-settlement');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '结算来源',@rent_parent,11,'admin-settlement-item','system/rentSettlementItem/index',1,0,'C','0','0','rent:manage:list','list','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE parent_id=@rent_parent AND path='admin-settlement-item');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '退款审批',@rent_parent,12,'admin-refund','system/rentRefund/index',1,0,'C','0','0','rent:manage:list','list','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE parent_id=@rent_parent AND path='admin-refund');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '凭证元数据',@rent_parent,13,'admin-credential','system/rentCredential/index',1,0,'C','0','0','rent:manage:list','list','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE parent_id=@rent_parent AND path='admin-credential');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '防重放记录',@rent_parent,14,'admin-nonce','system/rentNonce/index',1,0,'C','0','0','rent:manage:list','list','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE parent_id=@rent_parent AND path='admin-nonce');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '商户回调',@rent_parent,15,'admin-webhook','system/rentWebhook/index',1,0,'C','0','0','rent:manage:list','list','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE parent_id=@rent_parent AND path='admin-webhook');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '审计事件',@rent_parent,16,'admin-event','system/rentEvent/index',1,0,'C','0','0','rent:manage:list','list','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE parent_id=@rent_parent AND path='admin-event');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '开通应用节点及账户',@rent_parent,99,'#','',1,0,'F','0','0','rent:portal:register','#','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE perms='rent:portal:register');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '本人凭证签发及吊销',@rent_parent,99,'#','',1,0,'F','0','0','rent:credential:issue','#','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE perms='rent:credential:issue');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '本人钱包验证及策略',@rent_parent,99,'#','',1,0,'F','0','0','rent:wallet:bind','#','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE perms='rent:wallet:bind');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '新增套餐版本',@rent_parent,99,'#','',1,0,'F','0','0','rent:package:edit','#','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE perms='rent:package:edit');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '审核及链上核对',@rent_parent,99,'#','',1,0,'F','0','0','rent:manage:audit','#','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE perms='rent:manage:audit');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '本人下单及取消',@rent_parent,99,'#','',1,0,'F','0','0','rent:order:create','#','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE perms='rent:order:create');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '充值审核',@rent_parent,99,'#','',1,0,'F','0','0','rent:account:topup','#','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE perms='rent:account:topup');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '退款申请',@rent_parent,99,'#','',1,0,'F','0','0','rent:refund:create','#','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE perms='rent:refund:create');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '退款审批',@rent_parent,99,'#','',1,0,'F','0','0','rent:refund:approve','#','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE perms='rent:refund:approve');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '结算申请',@rent_parent,99,'#','',1,0,'F','0','0','rent:settlement:create','#','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE perms='rent:settlement:create');
|
||||||
|
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
|
||||||
|
SELECT '结算审批及付款核验',@rent_parent,99,'#','',1,0,'F','0','0','rent:settlement:approve','#','admin',NOW()
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE perms='rent:settlement:approve');
|
||||||
Reference in new issue
Block a user