diff --git a/.planning/rental-v22-review/findings.md b/.planning/rental-v22-review/findings.md index 0b45de0..0b2565e 100644 --- a/.planning/rental-v22-review/findings.md +++ b/.planning/rental-v22-review/findings.md @@ -37,3 +37,10 @@ - sql/rent_init.sql - docs/rental/schema-design.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;未对现有数据库或链上资产执行操作。 diff --git a/.planning/rental-v22-review/progress.md b/.planning/rental-v22-review/progress.md index a14cadb..95e40a3 100644 --- a/.planning/rental-v22-review/progress.md +++ b/.planning/rental-v22-review/progress.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 历史查询。 @@ -31,3 +44,11 @@ - 首轮机械删除误判注解中的{id}边界,已修正脚本并清理两类残片;静态检查确认每个无userId模块仅8个后台端点,有userId模块保留7个用户端点,所有端点均有权限注解。 - 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。 + +## 三端业务实现完成(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联调仍属部署验收边界,历史证明服务为外部依赖。 diff --git a/.planning/rental-v22-review/task_plan.md b/.planning/rental-v22-review/task_plan.md index 81452df..4095683 100644 --- a/.planning/rental-v22-review/task_plan.md +++ b/.planning/rental-v22-review/task_plan.md @@ -6,11 +6,26 @@ ## Next Step -已完成生成代码清理及JDK8编译验证,交付40个相关Java文件的修改。 +三端实现及本地验证完成;实际数据库迁移、公网WSS及NILE端到端验收按部署说明执行。 ## Current Phase -全部完成(含生成代码清理) +Phase 7:验证和部署文档 + +### Phase 5: 业务后端与可靠任务 + +- **Status:** complete +- 实现应用/节点认证、钱包授权、资金事务、订单、调度、独立核验、回收、退款、结算与回调。 + +### Phase 6: 本地 Agent 与 Vue + +- **Status:** complete +- 本地持久化原签名交易、默认禁广播、WSS 恢复;前端补齐 API、业务操作及权限。 + +### Phase 7: 验证和部署文档 + +- **Status:** complete +- JDK8 编译、资金/并发/恢复测试、前端构建及 Agent 测试;记录未获得外部环境的验证边界。 ### Phase 1: 设计审查 diff --git a/README.md b/README.md index a6025fb..f04ca33 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ ## 平台简介 +能量与带宽租赁模块:三端配置、业务API、Agent安装及验收边界见[租赁实现说明](docs/rental/implementation.md);初始化结构见[租赁SQL](sql/rent_init.sql),菜单权限见[租赁菜单SQL](sql/rent_menu.sql)。默认不启动租赁调度与节点通道,本地Agent默认禁止广播。 + susdt是一套全部开源的快速开发平台,毫无保留给个人及企业免费使用。 * 前端采用Vue、Element UI。 diff --git a/docs/rental/business-review-v2.2.md b/docs/rental/business-review-v2.2.md index 633c677..aa57e8c 100644 --- a/docs/rental/business-review-v2.2.md +++ b/docs/rental/business-review-v2.2.md @@ -1,5 +1,7 @@ # 能量与带宽出租业务复核与修正 V2.2 +说明:本文保留设计复核阶段记录。后续新增的Java/Vue/Node.js实现、部署步骤及当前验证边界见[implementation.md](implementation.md),不把历史“未实现”陈述视为当前代码状态。 + ## 1. 结论与适用范围 原 V2.1 的独立余额、供应商本地签名、链上独立核验、未知隔离、履约和回收分离方向可保留,但退款、人工付款、资源快照和多单回收存在实质缺口。V2.2 已在 [初始化 SQL](../../sql/rent_init.sql)、[主设计](schema-design.md) 和[逐表说明](table-functional-flows.md)中同步修正,表数由 15 增至 16。 diff --git a/docs/rental/implementation.md b/docs/rental/implementation.md new file mode 100644 index 0000000..d27a997 --- /dev/null +++ b/docs/rental/implementation.md @@ -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委托/回收或历史证明服务进行联调;这些必须在专用测试环境验收后再启用业务。本实现不自动开放主网广播、不自动建设历史节点、不自动出金。 diff --git a/docs/rental/schema-design.md b/docs/rental/schema-design.md index c37a663..b3db25a 100644 --- a/docs/rental/schema-design.md +++ b/docs/rental/schema-design.md @@ -1,6 +1,6 @@ # 能量/带宽出租表结构与业务流程 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. 简化范围和保留边界 diff --git a/docs/rental/table-functional-flows.md b/docs/rental/table-functional-flows.md index eb828b2..80c1ebb 100644 --- a/docs/rental/table-functional-flows.md +++ b/docs/rental/table-functional-flows.md @@ -2,7 +2,7 @@ ## 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 签名广播,云端独立核验后扣款、确认供应商应收;租期结束再回收资源。充值和供应商付款由人工审核处理。 diff --git a/docs/rental/validation-implementation.md b/docs/rental/validation-implementation.md new file mode 100644 index 0000000..0507486 --- /dev/null +++ b/docs/rental/validation-implementation.md @@ -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环境完成上述外部联调。 diff --git a/ruoyi-admin/src/main/resources/application-rental.yml b/ruoyi-admin/src/main/resources/application-rental.yml new file mode 100644 index 0000000..7da013d --- /dev/null +++ b/ruoyi-admin/src/main/resources/application-rental.yml @@ -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:} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java index d4c6e66..e239b77 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java @@ -142,6 +142,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { .antMatchers("/api/v1/wallet/**").permitAll() .antMatchers("/api/v1/order/**").permitAll() .antMatchers("/api/v1/payout/**").permitAll() + // 租赁商户及节点另用四域HMAC认证;绝不共用支付MD5签名。 + .antMatchers("/api/rental/v1/**", "/node/v1/socket").permitAll() .antMatchers("/api/telegram/webhook").permitAll() .antMatchers("/system/demoUsdt/**").permitAll() .anyRequest().authenticated() diff --git a/ruoyi-system/pom.xml b/ruoyi-system/pom.xml index 384bced..8258bfe 100644 --- a/ruoyi-system/pom.xml +++ b/ruoyi-system/pom.xml @@ -24,6 +24,22 @@ + + + org.springframework.boot + spring-boot-starter-websocket + + + com.squareup.okhttp3 + okhttp + 3.14.9 + + + com.h2database + h2 + 1.4.199 + test + junit diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/RentCredential.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/RentCredential.java index 86dd05c..3ed9357 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/RentCredential.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/RentCredential.java @@ -33,7 +33,7 @@ public class RentCredential extends BaseEntity private String apiKey; /** AES-GCM加密封装的API Secret,含IV和tag;禁止返回或记录明文 */ - @Excel(name = "AES-GCM加密封装的API Secret,含IV和tag;禁止返回或记录明文") + @com.fasterxml.jackson.annotation.JsonIgnore private String apiSecret; /** 外部AES主密钥版本,不存主密钥 */ @@ -184,7 +184,6 @@ public class RentCredential extends BaseEntity .append("ownerType", getOwnerType()) .append("ownerId", getOwnerId()) .append("apiKey", getApiKey()) - .append("apiSecret", getApiSecret()) .append("masterKeyVersion", getMasterKeyVersion()) .append("status", getStatus()) .append("expiresAt", getExpiresAt()) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalApiController.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalApiController.java new file mode 100644 index 0000000..0981baf --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalApiController.java @@ -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 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 app = store.get("app", number(credential, "owner_id"), false); + require("ACTIVE".equals(text(app, "status")), "应用已禁用"); + Map data = + json.readValue(body, new TypeReference>() {}); + if ("packages".equals(operation)) { + List> 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 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"))); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalChain.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalChain.java new file mode 100644 index 0000000..f1b11ed --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalChain.java @@ -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 body) { + return request("NILE".equals(network(network)) ? nile : mainnet, path, body); + } + + private JsonNode request(String base, String path, Map 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 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 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 verify( + Map 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 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 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); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalController.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalController.java new file mode 100644 index 0000000..37322a4 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalController.java @@ -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 body) { + return AjaxResult.success(provisioning.create(resource, body, user())); + } + + @PostMapping("/credential/issue") + @PreAuthorize("@ss.hasPermi('rent:credential:issue')") + public AjaxResult issue(@RequestBody Map 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 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 body) { + provisioning.policy(id, body, user()); + return AjaxResult.success(); + } + + @PostMapping("/package") + @PreAuthorize("@ss.hasPermi('rent:package:edit')") + public AjaxResult product(@RequestBody Map 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 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 body) { + Map 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 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 body) { + Map 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 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 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 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 body) { + require(body.get("order_ids") instanceof List, "缺少来源订单"); + List 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 body) { + String reason = input(body, "reason", 512); + long actor = user(); + if ("confirm".equals(action)) { + Map row = store.get("settlement", id, false), + account = store.get("account", number(row, "account_id"), false); + Map authorization; + try { + authorization = + new com.fasterxml.jackson.databind.ObjectMapper() + .readValue(text(row, "payment_evidence"), Map.class); + } catch (Exception ex) { + throw new IllegalArgumentException("缺少原付款授权收款地址"); + } + Map 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 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 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 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 body) { + String reason = input(body, "reason", 512); + long actor = user(); + tasks.tx( + () -> { + Map 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())); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalCrypto.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalCrypto.java new file mode 100644 index 0000000..c1dbd40 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalCrypto.java @@ -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(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalErrors.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalErrors.java new file mode 100644 index 0000000..e8b0d39 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalErrors.java @@ -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, "租赁操作暂未完成,请保留业务编号并检查配置或运行状态"); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalFunds.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalFunds.java new file mode 100644 index 0000000..6f8298d --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalFunds.java @@ -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 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 row = store.get("account", account, true); + Map 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 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 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 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 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")); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalHttp.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalHttp.java new file mode 100644 index 0000000..e5c2e53 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalHttp.java @@ -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); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalIdentity.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalIdentity.java new file mode 100644 index 0000000..b494c39 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalIdentity.java @@ -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 credential(String key) { + Map 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 credential) { + return crypto.decrypt(text(credential, "api_secret")); + } + + @Transactional(rollbackFor = Exception.class) + public Map 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 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 issue(String type, long owner, long actor) { + require("APP".equals(type) || "NODE".equals(type), "凭证主体非法"); + Map 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 credential = store.get("credential", id, true); + Map 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, + "主动吊销凭证"); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalJson.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalJson.java new file mode 100644 index 0000000..45c4783 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalJson.java @@ -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结构不完整"); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalLegacyGuard.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalLegacyGuard.java new file mode 100644 index 0000000..d72bf18 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalLegacyGuard.java @@ -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; + } + }); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalOrders.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalOrders.java new file mode 100644 index 0000000..9dc9244 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalOrders.java @@ -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 create(long appId, long user, Map request) { + // 锁应用行使同应用幂等竞争顺序化;不能仅依靠先查后插。 + Map 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 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 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 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 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 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 order = store.get("order", orderId, true); + Map 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 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 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("业务数据序列化失败"); + } + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalProvisioning.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalProvisioning.java new file mode 100644 index 0000000..0caaed6 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalProvisioning.java @@ -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 request, long actor) { + Map 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 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 request, long actor) { + Map 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 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 ownedWallet(long id, long actor, boolean lock) { + Map wallet = store.get("wallet", id, lock); + Map node = store.get("node", number(wallet, "node_id"), false); + require(number(node, "user_id") == actor, "无钱包权限"); + return wallet; + } + + @Transactional(rollbackFor = Exception.class) + public Map challenge(long id, long actor) { + Map 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 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 row = store.get(type, id, true); + Map 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 request, long actor) { + ownedWallet(id, actor, true); + Map 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, "供应商修改平台侧出租约束;不能替代本地广播授权"); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalQueries.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalQueries.java new file mode 100644 index 0000000..815a764 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalQueries.java @@ -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> list(String type, Long user, int page) { + String table = store.table(type); + String where = "1=1"; + List 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> rows = + store.rows( + "SELECT r.* FROM " + + table + + " r WHERE (" + + where + + ") ORDER BY r.id DESC LIMIT 50 OFFSET ?", + args.toArray()); + for (Map 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; + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalReconciliation.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalReconciliation.java new file mode 100644 index 0000000..f429e9f --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalReconciliation.java @@ -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 check(long afterId) { + List> accounts = + store.rows("SELECT * FROM rent_account WHERE id>? ORDER BY id LIMIT 100", afterId); + List> differences = new ArrayList<>(); + long last = afterId; + for (Map account : accounts) { + last = number(account, "id"); + Map 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> 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"); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalResponse.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalResponse.java new file mode 100644 index 0000000..b9ca726 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalResponse.java @@ -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 { + @Override + public boolean supports( + MethodParameter method, Class> converter) { + return true; + } + + @Override + public Object beforeBodyWrite( + Object body, + MethodParameter method, + MediaType mediaType, + Class> 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 result = new LinkedHashMap<>(); + ((Map) value).forEach((key, item) -> result.put(key.toString(), convert(item))); + return result; + } + if (value instanceof Collection) { + List result = new ArrayList<>(); + for (Object item : (Collection) value) { + result.add(convert(item)); + } + return result; + } + return value; + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalReviews.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalReviews.java new file mode 100644 index 0000000..bc6f27e --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalReviews.java @@ -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 request, long actor) { + Map 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 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 initial = store.get("refund", id, false); + long orderId = number(initial, "order_id"); + Map order = store.get("order", orderId, true); + Map 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 orderIds, long actor) { + require(orderIds != null && !orderIds.isEmpty() && orderIds.size() <= 100, "选择1至100笔订单"); + SortedSet sorted = new TreeSet<>(orderIds); + require(sorted.size() == orderIds.size(), "不能重复选择来源"); + List> sources = new ArrayList<>(); + Long account = null; + BigDecimal total = ZERO; + for (long orderId : sorted) { + Map 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 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 transition(long id, String action, long actor, String reason) { + Map 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 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); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalSocket.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalSocket.java new file mode 100644 index 0000000..cc453fc --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalSocket.java @@ -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 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 envelope = + json.readValue( + message.getPayload(), new TypeReference>() {}); + String body = input(envelope, "body", 60000); + RentalJson.bounded(body); + Map frame = + json.readValue(body, new TypeReference>() {}); + 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 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 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 payload = (Map) 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) 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 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 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 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 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); + } + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalSocketConfig.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalSocketConfig.java new file mode 100644 index 0000000..023ba49 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalSocketConfig.java @@ -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()); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalStore.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalStore.java new file mode 100644 index 0000000..57358aa --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalStore.java @@ -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 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> rows(String sql, Object... args) { + return jdbc.queryForList(sql, args); + } + + public Map one(String sql, Object... args) { + List> rows = rows(sql, args); + return rows.isEmpty() ? null : rows.get(0); + } + + public Map get(String table, long id, boolean lock) { + Map 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 data) { + Map values = new LinkedHashMap<>(data); + values.put("created_at", now()); + values.put("updated_at", now()); + values.put("version", 0L); + List 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 data) { + List args = new ArrayList<>(); + List 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)); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalTasks.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalTasks.java new file mode 100644 index 0000000..be23421 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalTasks.java @@ -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 tx(Supplier action) { + return transaction.execute(status -> action.get()); + } + + public void refresh(long id) { + Map previous = store.get("wallet", id, false); + Map snapshot = + chain.snapshot(text(previous, "network"), text(previous, "address")); + tx( + () -> { + Map 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 initial = store.get("order", orderId, false); + if (!"WAITING".equals(text(initial, "status"))) { + return; + } + if (!time(initial.get("dispatch_deadline")).isAfter(Instant.now())) { + tx( + () -> { + Map 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> 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 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 order = store.get("order", orderId, true); + if (!"WAITING".equals(text(order, "status")) + || !time(order.get("dispatch_deadline")) + .isAfter(Instant.now())) { + return false; + } + Map wallet = + store.get("wallet", number(candidate, "id"), true); + if (number(wallet, "version") != number(candidate, "version")) { + return false; + } + Map 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 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 order, + Map wallet, + String type, + long sun, + long limit, + long weight, + Map source) { + long nodeId = number(wallet, "node_id"), orderId = number(order, "id"); + Map 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 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 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 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 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 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 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 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 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 initial = + store.one("SELECT * FROM rent_task WHERE task_no=? AND node_id=?", taskNo, nodeId); + require(initial != null, "任务不属于节点"); + tx( + () -> { + Map order = + store.get("order", number(initial, "order_id"), true); + Map wallet = + store.get("wallet", number(initial, "wallet_id"), true); + Map 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 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 task = store.get("task", taskId, false); + Map 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 proof = + chain.verify( + task, + text(record, "tx_id"), + text(record, "owner_address"), + text(record, "receiver_address")); + tx( + () -> { + Map order = store.get("order", number(task, "order_id"), true); + Map wallet = + store.get("wallet", number(task, "wallet_id"), true); + Map current = store.get("task", taskId, true); + Map 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 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 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 task, + Map order, + Map 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 order = store.get("order", orderId, false); + if (!"RECOVERING".equals(text(order, "reclaim_status"))) { + return; + } + Map wallet = store.get("wallet", number(order, "wallet_id"), false); + Map 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 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 current = store.get("order", orderId, true); + Map 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 task = store.get("task", taskId, false); + require( + task.get("active_slot") != null + && !Arrays.asList("REJECTED", "FAILED").contains(text(task, "status")), + "只能补充原在途任务的交易证据"); + Map wallet = store.get("wallet", number(task, "wallet_id"), false); + Map 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 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 order = store.get("order", orderId, false); + if (!"SUCCESS".equals(text(order, "status")) + || !"WAITING".equals(text(order, "reclaim_status"))) { + return; + } + Map wallet = store.get("wallet", number(order, "wallet_id"), false); + Map 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 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; + }); + } + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalValues.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalValues.java new file mode 100644 index 0000000..8b794a6 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalValues.java @@ -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 map(Object... pairs) { + Map 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 row, String key) { + Object value = row.get(key); + return value == null ? "" : value.toString(); + } + + public static String input(Map 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 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 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(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalWorkers.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalWorkers.java new file mode 100644 index 0000000..e07379b --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalWorkers.java @@ -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 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> 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 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 { + 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> 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 row : rows) { + walletCursor = number(row, "id"); + try { + tasks.refresh(walletCursor); + } catch (Exception ex) { + LOG.warn("租赁钱包快照暂不可用,walletId={}", walletCursor); + } + } + } + + private void each(String sql, Consumer action) { + for (Map 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> 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 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 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 row = + tasks.tx( + () -> { + Map 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 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 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); + } + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/TronServiceProvider.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/TronServiceProvider.java index 575a30d..65b24ca 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/TronServiceProvider.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/TronServiceProvider.java @@ -44,4 +44,11 @@ public class TronServiceProvider { if (networkType == NETWORK_MAINNET) return mainnetService; 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网络类型非法"); + } } diff --git a/ruoyi-system/src/test/java/com/ruoyi/system/rental/RentalBusinessTest.java b/ruoyi-system/src/test/java/com/ruoyi/system/rental/RentalBusinessTest.java new file mode 100644 index 0000000..90d64b2 --- /dev/null +++ b/ruoyi-system/src/test/java/com/ruoyi/system/rental/RentalBusinessTest.java @@ -0,0 +1,1075 @@ +package com.ruoyi.system.rental; + +import static com.ruoyi.system.rental.RentalValues.*; + +import static org.junit.Assert.*; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.h2.jdbcx.JdbcDataSource; +import org.junit.Before; +import org.junit.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.*; +import java.util.concurrent.*; + +/** 隔离事务测试:使用真实仓储SQL及行锁,不连接项目MySQL、Redis或TRON。 */ +public class RentalBusinessTest { + private RentalStore store; + private RentalFunds funds; + private RentalOrders orders; + private RentalReviews reviews; + private RentalTasks tasks; + private RentalIdentity identity; + private TransactionTemplate tx; + private long payer; + private long supplier; + private long app; + private long product; + private long wallet; + private long node; + private boolean proofAvailable = true; + private static final String ADDRESS = "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf"; + private static final String OWNER = "TR7NHqjeKQxGTCi8q8ZY4pL8otgjLj6t"; + private final ObjectMapper json = new ObjectMapper(); + + @Before + public void setup() throws Exception { + JdbcDataSource source = new JdbcDataSource(); + source.setURL( + "jdbc:h2:mem:" + + UUID.randomUUID() + + ";MODE=MySQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=10000"); + JdbcTemplate jdbc = new JdbcTemplate(source); + store = new RentalStore(jdbc); + // 仅替换H2不支持的存储/字符集/JSON声明,保留16表字段、唯一键及事务SQL。 + String ddl = + new String( + Files.readAllBytes(Paths.get("../sql/rent_init.sql")), + StandardCharsets.UTF_8) + .replaceAll("(?m)^--.*$", "") + .replaceAll("CHARACTER SET ascii COLLATE ascii_bin", "") + .replaceAll("(?i)\\bJSON\\b", "LONGTEXT") + .replaceAll( + "ENGINE=InnoDB ROW_FORMAT=DYNAMIC DEFAULT CHARSET=utf8mb4" + + " COLLATE=utf8mb4_bin", + ""); + for (String sql : ddl.split(";")) { + if (!sql.trim().isEmpty()) { + jdbc.execute(sql); + } + } + tx = new TransactionTemplate(new DataSourceTransactionManager(source)); + funds = new RentalFunds(store); + orders = new RentalOrders(store, funds, json); + reviews = new RentalReviews(store, funds, orders); + RentalCrypto crypto = new RentalCrypto(); + java.lang.reflect.Field field = RentalCrypto.class.getDeclaredField("masterKey"); + field.setAccessible(true); + field.set(crypto, Base64.getEncoder().encodeToString(new byte[32])); + identity = new RentalIdentity(store, crypto); + payer = number(funds.account(10, "NILE"), "id"); + supplier = number(funds.account(20, "NILE"), "id"); + tx.execute( + status -> { + funds.post( + payer, + "TOPUP:NILE:fixture:0", + "TOPUP", + money("100"), + ZERO, + ZERO, + ZERO, + null, + null, + null, + 99, + "fixture", + "隔离测试充值"); + return null; + }); + app = store.insert("app", map("user_id", 10, "name", "test", "status", "ACTIVE")); + node = + store.insert( + "node", + map( + "user_id", + 20, + "node_no", + "NODE-TEST", + "name", + "test", + "agent_version", + "1", + "status", + "ACTIVE", + "created_by", + 20, + "connection_status", + "ONLINE", + "heartbeat_expires_at", + after(60))); + identity.issue("NODE", node, 20); + product = + store.insert( + "package", + map( + "package_code", + "E", + "revision", + 1, + "name", + "energy", + "network", + "NILE", + "resource_type", + "ENERGY", + "resource_quantity", + 65000, + "redundancy_percent", + "20", + "duration_seconds", + 3600, + "sale_amount", + money("10"), + "supplier_amount", + money("8"), + "supplier_fee_percent", + "5", + "fee_limit_sun", + 1000000, + "delegate_lock", + 0, + "rules", + "{}", + "status", + "ACTIVE")); + wallet = + store.insert( + "wallet", + map( + "node_id", + node, + "network", + "NILE", + "address", + OWNER, + "status", + "ACTIVE", + "ownership_verified_at", + now(), + "energy_enabled", + 1, + "bandwidth_enabled", + 1, + "energy_delegatable_sun", + 9000000000L, + "bandwidth_delegatable_sun", + 9000000000L, + "total_energy_limit", + 60000000, + "total_energy_weight", + 1000000, + "total_bandwidth_limit", + 1500000, + "total_bandwidth_weight", + 1000000, + "snapshot_block_height", + 100, + "snapshot_at", + now(), + "snapshot_expires_at", + after(60))); + RentalChain chain = + new RentalChain(json) { + @Override + public long relation( + String network, String owner, String receiver, String type) { + return 0; + } + + @Override + public Map snapshot(String network, String address) { + return map( + "snapshot_block_height", + 200, + "energy_delegatable_sun", + 9000000000L, + "bandwidth_delegatable_sun", + 9000000000L, + "total_energy_limit", + 60000000, + "total_energy_weight", + 1000000, + "total_bandwidth_limit", + 1500000, + "total_bandwidth_weight", + 1000000, + "energy_available", + 100000, + "bandwidth_available", + 10000, + "snapshot_at", + now(), + "snapshot_expires_at", + after(60)); + } + + @Override + public Map verify( + Map task, String tx, String owner, String receiver) { + return map( + "status", + "CONFIRMED", + "block_height", + 101, + "block_time", + now().minusSeconds(5), + "after_sun", + "DELEGATE".equals(text(task, "task_type")) + ? task.get("delegate_sun") + : 0, + "verified_total_limit", + 60000000, + "verified_total_weight", + 1000000, + "verified_resource_quantity", + 78000, + "delivery_proven", + proofAvailable); + } + }; + tasks = + new RentalTasks( + store, + chain, + identity, + orders, + funds, + new DataSourceTransactionManager(source)); + } + + private Map create(String number) { + return tx.execute( + status -> + orders.create( + app, + 10, + map( + "package_id", + product, + "merchant_order_no", + number, + "receiver_address", + ADDRESS))); + } + + private void expectFailure(Runnable action) { + try { + action.run(); + fail("应拒绝非法操作"); + } catch (IllegalArgumentException | org.springframework.dao.DataAccessException expected) { + /* 预期拒绝。 */ + } + } + + @Test + public void precisionAndOverflow() { + assertEquals(78000, target(65000, new BigDecimal("20"))); + assertEquals(1300000000L, principal(78000, 60000000, 1000000)); + assertEquals(78000, quantity(1300000000L, 60000000, 1000000)); + expectFailure(() -> target(1, ZERO)); + try { + principal(Long.MAX_VALUE, 1, Long.MAX_VALUE); + fail(); + } catch (ArithmeticException expected) { + /* 不允许溢出。 */ + } + } + + @Test + public void sharedHmacVectorAndDomainIsolation() { + String signature = + RentalCrypto.sign( + "test-secret", + "API", + "test-key", + 1700000000123L, + "abcdefghijklmnop", + "POST", + "/api/rental/v1/create", + "{\"amount\":\"1.000000\"}"); + assertEquals("47241a34f0813881384317eafbfc068dc9f7c6061a8fe269cb815e7820d48430", signature); + assertFalse( + RentalCrypto.equal( + signature, + RentalCrypto.sign( + "test-secret", + "NODE", + "test-key", + 1700000000123L, + "abcdefghijklmnop", + "POST", + "/api/rental/v1/create", + "{\"amount\":\"1.000000\"}"))); + } + + @Test + public void credentialNonceReplayRejectedAndSecretEncrypted() { + Map issued = identity.issue("APP", app, 10); + String key = text(issued, "api_key"), + secret = text(issued, "api_secret"), + nonce = RentalCrypto.random(); + long timestamp = System.currentTimeMillis(); + String signature = + RentalCrypto.sign( + secret, "API", key, timestamp, nonce, "POST", "/api/rental/v1/query", "{}"); + identity.authenticate( + key, + "APP", + "API", + timestamp, + nonce, + "POST", + "/api/rental/v1/query", + "{}", + signature); + expectFailure( + () -> + identity.authenticate( + key, + "APP", + "API", + timestamp, + nonce, + "POST", + "/api/rental/v1/query", + "{}", + signature)); + assertFalse( + text(store.get("credential", number(issued, "id"), false), "api_secret") + .contains(secret)); + } + + @Test + public void mysqlJsonNormalizationDoesNotBreakTaskSignature() throws Exception { + long id = number(create("CANONICAL"), "id"); + tasks.dispatch(id); + Map task = store.one("SELECT * FROM rent_task WHERE order_id=?", id); + Map intent = json.readValue(text(task, "intent"), Map.class); + String mysqlStyle = + json.writerWithDefaultPrettyPrinter().writeValueAsString(new HashMap<>(intent)); + String canonical = + json.writeValueAsString(new TreeMap<>(json.readValue(mysqlStyle, Map.class))); + Map credential = + store.get("credential", number(task, "credential_id"), false); + assertEquals( + text(task, "signature"), + RentalCrypto.sign( + identity.secret(credential), + "TASK", + text(credential, "api_key"), + time(task.get("signed_at")).toEpochMilli(), + text(task, "nonce"), + "PUSH", + "/node/v1/task", + canonical)); + } + + @Test + public void socketAuthenticationSyncAndOldCloseFenced() throws Exception { + RentalSocket socket = new RentalSocket(store, identity, tasks, json); + StubSocket first = new StubSocket(); + authenticate(socket, first); + Map firstAuth = + json.readValue( + text(json.readValue(first.messages.get(1), Map.class), "body"), Map.class); + Map credential = + store.one( + "SELECT * FROM rent_credential WHERE owner_type='NODE' AND owner_id=? AND" + + " status='ACTIVE'", + node); + Map sync = + map( + "type", + "SYNC_STATE", + "direction", + "CLIENT", + "session_id", + firstAuth.get("session_id"), + "session_epoch", + firstAuth.get("session_epoch"), + "sequence", + "1", + "message_id", + "sync1", + "payload", + map("events", Collections.emptyList())); + socket.handleTextMessage(first, envelope(credential, sync)); + assertEquals("ONLINE", text(store.get("node", node, false), "connection_status")); + StubSocket second = new StubSocket(); + authenticate(socket, second); + socket.afterConnectionClosed(first, org.springframework.web.socket.CloseStatus.NORMAL); + assertEquals("SYNCING", text(store.get("node", node, false), "connection_status")); + assertEquals(2, number(store.get("node", node, false), "session_epoch")); + assertFalse(first.isOpen()); + } + + @Test + public void socketReplayCannotRefreshHeartbeat() throws Exception { + RentalSocket socket = new RentalSocket(store, identity, tasks, json); + StubSocket session = new StubSocket(); + authenticate(socket, session); + Map auth = + json.readValue( + text(json.readValue(session.messages.get(1), Map.class), "body"), + Map.class); + Map credential = + store.one( + "SELECT * FROM rent_credential WHERE owner_type='NODE' AND owner_id=? AND" + + " status='ACTIVE'", + node); + org.springframework.web.socket.TextMessage frame = + envelope( + credential, + map( + "type", + "PING", + "direction", + "CLIENT", + "session_id", + auth.get("session_id"), + "session_epoch", + auth.get("session_epoch"), + "sequence", + "1", + "message_id", + "ping1", + "payload", + map())); + socket.handleTextMessage(session, frame); + assertTrue(session.isOpen()); + socket.handleTextMessage(session, frame); + assertFalse(session.isOpen()); + } + + private void authenticate(RentalSocket socket, StubSocket session) throws Exception { + socket.afterConnectionEstablished(session); + Map challenge = json.readValue(session.messages.get(0), Map.class); + Map credential = + store.one( + "SELECT * FROM rent_credential WHERE owner_type='NODE' AND owner_id=? AND" + + " status='ACTIVE'", + node); + socket.handleTextMessage( + session, + envelope( + credential, + map( + "type", + "AUTH", + "node_no", + "NODE-TEST", + "challenge", + challenge.get("challenge")))); + assertTrue(session.isOpen()); + } + + private org.springframework.web.socket.TextMessage envelope( + Map credential, Map frame) throws Exception { + long timestamp = System.currentTimeMillis(); + String nonce = RentalCrypto.random(), + key = text(credential, "api_key"), + body = json.writeValueAsString(frame); + return new org.springframework.web.socket.TextMessage( + json.writeValueAsString( + map( + "api_key", + key, + "timestamp", + timestamp, + "nonce", + nonce, + "body", + body, + "signature", + RentalCrypto.sign( + identity.secret(credential), + "NODE", + key, + timestamp, + nonce, + "FRAME", + "/node/v1/socket", + body)))); + } + + private static class StubSocket implements org.springframework.web.socket.WebSocketSession { + private final String id = UUID.randomUUID().toString(); + private boolean open = true; + private final List messages = new ArrayList<>(); + + @Override + public String getId() { + return id; + } + + @Override + public java.net.URI getUri() { + return java.net.URI.create("wss://test/node/v1/socket"); + } + + @Override + public org.springframework.http.HttpHeaders getHandshakeHeaders() { + return new org.springframework.http.HttpHeaders(); + } + + @Override + public Map getAttributes() { + return Collections.emptyMap(); + } + + @Override + public java.security.Principal getPrincipal() { + return null; + } + + @Override + public java.net.InetSocketAddress getLocalAddress() { + return null; + } + + @Override + public java.net.InetSocketAddress getRemoteAddress() { + return null; + } + + @Override + public String getAcceptedProtocol() { + return null; + } + + @Override + public void setTextMessageSizeLimit(int limit) {} + + @Override + public int getTextMessageSizeLimit() { + return 65536; + } + + @Override + public void setBinaryMessageSizeLimit(int limit) {} + + @Override + public int getBinaryMessageSizeLimit() { + return 0; + } + + @Override + public List getExtensions() { + return Collections.emptyList(); + } + + @Override + public void sendMessage(org.springframework.web.socket.WebSocketMessage message) { + messages.add(message.getPayload().toString()); + } + + @Override + public boolean isOpen() { + return open; + } + + @Override + public void close() { + open = false; + } + + @Override + public void close(org.springframework.web.socket.CloseStatus status) { + open = false; + } + } + + @Test + public void orderIdempotenceAndHold() { + long id = number(create("ONE"), "id"); + assertEquals(id, number(create("ONE"), "id")); + assertEquals(money("90"), amount(store.get("account", payer, false), "available_amount")); + assertEquals(1, store.rows("SELECT id FROM rent_ledger WHERE event_type='HOLD'").size()); + expectFailure( + () -> + tx.execute( + status -> + orders.create( + app, + 10, + map( + "package_id", + product, + "merchant_order_no", + "ONE", + "receiver_address", + OWNER)))); + } + + @Test + public void crossUserCannotReuseTopupEvidence() { + expectFailure( + () -> + tx.execute( + status -> { + funds.post( + supplier, + "TOPUP:NILE:fixture:0", + "TOPUP", + money("100"), + ZERO, + ZERO, + ZERO, + null, + null, + null, + 99, + "fixture", + "duplicate"); + return null; + })); + assertEquals(ZERO, amount(store.get("account", supplier, false), "available_amount")); + } + + @Test + public void insufficientBalanceRollsBackOrder() { + store.update("package", product, map("sale_amount", money("101"))); + expectFailure(() -> create("NO-MONEY")); + assertTrue(store.rows("SELECT id FROM rent_order").isEmpty()); + } + + @Test + public void cancelIsIdempotentAndDispatchedCannotCancel() { + long id = number(create("CANCEL"), "id"); + tx.execute( + status -> { + orders.cancel(id, 10); + orders.cancel(id, 10); + return null; + }); + assertEquals(money("100"), amount(store.get("account", payer, false), "available_amount")); + long other = number(create("DISPATCH"), "id"); + tasks.dispatch(other); + expectFailure( + () -> + tx.execute( + status -> { + orders.cancel(other, 10); + return null; + })); + } + + @Test + public void unknownKeepsFundsAndAllSlots() { + long id = number(create("UNKNOWN"), "id"); + tasks.dispatch(id); + Map task = store.one("SELECT * FROM rent_task WHERE order_id=?", id); + tasks.report( + node, map("task_no", task.get("task_no"), "event_id", "u1", "state", "UNKNOWN")); + task = store.get("task", number(task, "id"), false); + assertEquals("UNKNOWN", text(task, "status")); + assertEquals(1, number(task, "wallet_execution_slot")); + assertEquals("HELD", text(task, "reservation_status")); + assertEquals("HELD", text(store.get("order", id, false), "fund_status")); + } + + @Test + public void confirmedTransactionChargesOnceAndInvalidatesSnapshot() { + long id = number(create("SUCCESS"), "id"); + tasks.dispatch(id); + Map task = store.one("SELECT * FROM rent_task WHERE order_id=?", id); + Map event = + map( + "task_no", + task.get("task_no"), + "event_id", + "b1", + "state", + "BUILT", + "tx_id", + String.join("", Collections.nCopies(64, "a"))); + tasks.report(node, event); + tasks.report(node, event); + tasks.verify(number(task, "id")); + tasks.verify(number(task, "id")); + assertEquals("SUCCESS", text(store.get("order", id, false), "status")); + assertEquals( + money("7.6"), + amount(store.get("account", supplier, false), "supplier_pending_amount")); + Map current = store.get("wallet", wallet, false); + assertNull(current.get("snapshot_expires_at")); + assertEquals(101, number(current, "snapshot_min_block_height")); + assertEquals(1, number(store.get("order", id, false), "relation_slot")); + } + + @Test + public void rejectedRetryKeepsHold() { + long id = number(create("REJECT"), "id"); + tasks.dispatch(id); + Map task = store.one("SELECT * FROM rent_task WHERE order_id=?", id); + tasks.report( + node, map("task_no", task.get("task_no"), "event_id", "r1", "state", "REJECTED")); + assertEquals("WAITING", text(store.get("order", id, false), "status")); + assertEquals("HELD", text(store.get("order", id, false), "fund_status")); + assertEquals(0, number(store.get("wallet", wallet, false), "energy_reserved_sun")); + } + + @Test + public void concurrentOrdersNeverOverspend() throws Exception { + ExecutorService executor = Executors.newFixedThreadPool(2); + CountDownLatch start = new CountDownLatch(1); + store.update("package", product, map("sale_amount", money("80"))); + List> results = new ArrayList<>(); + for (String no : Arrays.asList("RACE-A", "RACE-B")) { + results.add( + executor.submit( + () -> { + start.await(); + try { + create(no); + return true; + } catch (Exception ex) { + return false; + } + })); + } + start.countDown(); + int success = 0; + for (Future result : results) { + if (result.get(15, TimeUnit.SECONDS)) { + success++; + } + } + executor.shutdownNow(); + assertEquals(1, success); + assertEquals(money("20"), amount(store.get("account", payer, false), "available_amount")); + } + + @Test + public void sameRelationQueuesAndDifferentResourceUsesSeparatePool() { + long first = number(create("RELATION-A"), "id"), + second = number(create("RELATION-B"), "id"); + tasks.dispatch(first); + tasks.dispatch(second); + assertEquals("WAITING", text(store.get("order", second, false), "status")); + long bandwidth = + store.insert( + "package", + map( + "package_code", + "B", + "revision", + 1, + "name", + "bandwidth", + "network", + "NILE", + "resource_type", + "BANDWIDTH", + "resource_quantity", + 1000, + "redundancy_percent", + "20", + "duration_seconds", + 3600, + "sale_amount", + money("10"), + "supplier_amount", + money("8"), + "supplier_fee_percent", + "5", + "fee_limit_sun", + 1000000, + "delegate_lock", + 0, + "rules", + "{}", + "status", + "ACTIVE")); + Map order = + tx.execute( + status -> + orders.create( + app, + 10, + map( + "package_id", + bandwidth, + "merchant_order_no", + "BANDWIDTH", + "receiver_address", + ADDRESS))); + tasks.dispatch(number(order, "id")); + Map current = store.get("wallet", wallet, false); + assertEquals(1300000000L, number(current, "energy_reserved_sun")); + assertEquals(800000000L, number(current, "bandwidth_reserved_sun")); + } + + private long confirmed(String merchant) { + long id = number(create(merchant), "id"); + tasks.dispatch(id); + Map task = store.one("SELECT * FROM rent_task WHERE order_id=?", id); + tasks.report( + node, + map( + "task_no", + task.get("task_no"), + "event_id", + merchant, + "state", + "BUILT", + "tx_id", + String.join("", Collections.nCopies(64, "c")))); + tasks.verify(number(task, "id")); + return id; + } + + @Test + public void reclaimUsesOriginalSunAndKeepsRelationUntilResourcesRecovered() { + long id = confirmed("RECLAIM"); + store.update("order", id, map("next_reclaim_at", after(-1))); + tasks.reclaim(id); + Map task = + store.one("SELECT * FROM rent_task WHERE order_id=? AND task_type='RECLAIM'", id); + assertEquals(1300000000L, number(task, "delegate_sun")); + assertNotNull(task.get("source_transaction_id")); + assertEquals("NONE", text(task, "reservation_status")); + tasks.report( + node, + map( + "task_no", + task.get("task_no"), + "event_id", + "reclaimBuilt", + "state", + "BUILT", + "tx_id", + String.join("", Collections.nCopies(64, "d")))); + tasks.verify(number(task, "id")); + assertEquals("RECOVERING", text(store.get("order", id, false), "reclaim_status")); + assertEquals(1, number(store.get("order", id, false), "relation_slot")); + tasks.recoverResource(id); + assertEquals("DONE", text(store.get("order", id, false), "reclaim_status")); + assertNull(store.get("order", id, false).get("relation_slot")); + assertEquals("SUCCESS", text(store.get("order", id, false), "status")); + } + + @Test + public void missingHistoricalProofNeverChargesAndOnlyRecoveredManualOrderCanRelease() { + proofAvailable = false; + long id = confirmed("NOHISTORY"); + Map order = store.get("order", id, false); + assertEquals("MANUAL_REVIEW", text(order, "status")); + assertEquals("HELD", text(order, "fund_status")); + expectFailure(() -> tasks.resolveRecovered(id, 99, "not recovered")); + store.update("order", id, map("next_reclaim_at", after(-1))); + tasks.reclaim(id); + Map task = + store.one("SELECT * FROM rent_task WHERE order_id=? AND task_type='RECLAIM'", id); + tasks.report( + node, + map( + "task_no", + task.get("task_no"), + "event_id", + "manualReclaim", + "state", + "BUILT", + "tx_id", + String.join("", Collections.nCopies(64, "e")))); + tasks.verify(number(task, "id")); + tasks.recoverResource(id); + tasks.resolveRecovered(id, 99, "原本金与资源已回收,未确认交付"); + assertEquals(money("100"), amount(store.get("account", payer, false), "available_amount")); + assertEquals("FAILED", text(store.get("order", id, false), "status")); + } + + @Test + public void merchantAndSupplierSameAccountNoDoubleLockOrWrongBalance() { + store.update("node", node, map("user_id", 10)); + long id = confirmed("SAMEACCOUNT"); + assertEquals(payer, number(store.get("order", id, false), "supplier_account_id")); + assertEquals(money("90"), amount(store.get("account", payer, false), "available_amount")); + assertEquals( + money("7.6"), + amount(store.get("account", payer, false), "supplier_pending_amount")); + } + + @Test + public void feeReturnedToSupplierIncludedInSettlementSourceAndReversalLinked() { + long id = confirmed("FEE-RETURN"); + long refund = + tx.execute( + status -> + reviews.refund( + id, + map( + "request_no", + "FEE1", + "reason", + "fee test", + "refund_amount", + "1", + "supplier_reverse_amount", + "0", + "platform_fee_reverse_amount", + "0.2", + "fee_return_to", + "SUPPLIER"), + 90)); + tx.execute( + status -> { + reviews.approveRefund(refund, true, 91); + return null; + }); + long settlement = + tx.execute(status -> reviews.settlement(Collections.singletonList(id), 90)); + assertEquals(money("7.8"), amount(store.get("settlement", settlement, false), "amount")); + assertNotNull( + store.one( + "SELECT reversal_of_id FROM rent_ledger WHERE business_key=?", + "REVERSAL:" + refund + ":FEE") + .get("reversal_of_id")); + } + + @Test + public void reconciliationReportsManualCorruptionWithoutRepairingIt() { + RentalReconciliation reconciliation = new RentalReconciliation(store); + assertTrue(((List) reconciliation.check(0).get("differences")).isEmpty()); + assertTrue(reconciliation.reservations().isEmpty()); + store.update("account", payer, map("available_amount", money("99"))); + assertFalse(((List) reconciliation.check(0).get("differences")).isEmpty()); + assertEquals(money("99"), amount(store.get("account", payer, false), "available_amount")); + } + + @Test + public void boundedJsonAndSsrfGuard() throws Exception { + expectFailure( + () -> + RentalJson.bounded( + String.join("", Collections.nCopies(33, "[")) + + "0" + + String.join("", Collections.nCopies(33, "]")))); + RentalJson.bounded("{\"quoted\":\"[[[\"}"); + expectFailure(() -> RentalHttp.checkUrl("https://example.com/path?token=1")); + assertFalse(RentalHttp.publicAddress(java.net.InetAddress.getByName("127.0.0.1"))); + assertFalse(RentalHttp.publicAddress(java.net.InetAddress.getByName("100.64.0.1"))); + assertFalse(RentalHttp.publicAddress(java.net.InetAddress.getByName("::1"))); + } + + @Test + public void tronWebMessageV2Utf8SignatureRecoversAndConsumesOnce() { + // 使用公开测试向量,签名由锁定版本TronWeb6.0.4离线生成;不是运行钱包。 + String address = "TMVQGm1qAQYVdetCeGRRkTWYYrLXuHK2HC", nonce = RentalCrypto.random(); + String signature = + "0x5e022ea29837ffca8a8940886b90308b3a66e092e3b00ba7ddff85c683bae2ed44888bfd2f1936680b3150598d956767d169334c2ed93f8b490da49aa3e447271b"; + store.update( + "wallet", + wallet, + map( + "address", + address, + "ownership_message", + "RENTAL OWNERSHIP TEST 中文", + "ownership_challenge", + nonce, + "challenge_expires_at", + after(300), + "challenge_consumed_at", + null)); + RentalProvisioning provisioning = new RentalProvisioning(store, orders); + tx.execute( + status -> { + provisioning.prove(wallet, nonce, signature, 20); + return null; + }); + assertEquals( + address, text(store.get("wallet", wallet, false), "ownership_verified_address")); + expectFailure( + () -> + tx.execute( + status -> { + provisioning.prove(wallet, nonce, signature, 20); + return null; + })); + } + + @Test + public void refundReviewAndPayingCannotRelease() { + long id = number(create("REFUND"), "id"); + tasks.dispatch(id); + Map task = store.one("SELECT * FROM rent_task WHERE order_id=?", id); + tasks.report( + node, + map( + "task_no", + task.get("task_no"), + "event_id", + "built", + "state", + "BUILT", + "tx_id", + String.join("", Collections.nCopies(64, "b")))); + tasks.verify(number(task, "id")); + long refund = + tx.execute( + status -> + reviews.refund( + id, + map( + "request_no", + "RF1", + "reason", + "test", + "refund_amount", + "2", + "supplier_reverse_amount", + "1", + "platform_fee_reverse_amount", + "0", + "fee_return_to", + "NONE"), + 90)); + expectFailure( + () -> + tx.execute( + status -> { + reviews.approveRefund(refund, true, 90); + return null; + })); + tx.execute( + status -> { + reviews.approveRefund(refund, true, 91); + reviews.approveRefund(refund, true, 91); + return null; + }); + assertEquals( + money("6.6"), + amount(store.get("account", supplier, false), "supplier_pending_amount")); + long settlement = + tx.execute(status -> reviews.settlement(Collections.singletonList(id), 90)); + tx.execute( + status -> { + reviews.transition(settlement, "approve", 91, "test"); + reviews.transition(settlement, "pay", 91, "test"); + return null; + }); + expectFailure( + () -> tx.execute(status -> reviews.transition(settlement, "reject", 91, "test"))); + assertEquals("PAYING", text(store.get("settlement", settlement, false), "status")); + } +} diff --git a/sql/rent_menu.sql b/sql/rent_menu.sql new file mode 100644 index 0000000..865cd0a --- /dev/null +++ b/sql/rent_menu.sql @@ -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');