Compare commits

..
Author SHA1 Message Date
admin 2ece12d44b rebrand: 收尾 —— 协议标识与表前缀一并换成 vupay
Docker Build (Gitea) / Build and Push Docker Image (push) Successful in 13s
之前刻意保留的三处,在没有订单数据的前提下一起改掉:
- 表前缀 bep_ → vupay_(6 张表 + gormigrate 的 vupay_migration)
- api_type 取值 "epusdt"/"epusdt_order" → "vupay"/"vupay_order"
- handler 包 app/handler/epusdt → app/handler/vupay、类型 Epusdt → Vupay、EpusdtSign → VupaySign

顺带清理:
- 删 docs/faq/vupay.md(整篇是「本项目和 EPusdt 的关系」的上游叙事)
- README 去掉「缘起于/原项目已转手」说明与上游致谢条目,联系邮箱不再指向 vupay.online
- 修 app/task/testenv_test.go 的 model.Init 调用(上一版加 MySQL 支持时漏了第三个参数,go build 不编译测试所以没暴露)

验证:go build ./... / go vet ./... / go test ./app/... 全通过;全仓 grep -i epusdt 归零
2026-11-25 09:22:48 +08:00
admin 79b6b914aa rebrand: 收银台 logo 图形换成 V 字标(原文件名 bepusdt.svg + 内容为 B 字标)
Docker Build (Gitea) / Build and Push Docker Image (push) Successful in 10s
2026-11-25 09:13:42 +08:00
admin 38231b15cb merge feat/rebrand-vupay:品牌改为 VUPAY
Docker Build (Gitea) / Build and Push Docker Image (push) Successful in 11s
2026-11-25 09:08:26 +08:00
admin a950fd2ead rebrand: BEpusdt → VUPAY
Docker Build (Gitea) / Build and Push Docker Image (push) Successful in 47s
展示层与标识符全量改名:
- module github.com/v03413/bepusdt → git.viaeon.com/admin/vupay(含全部 import)
- 二进制/镜像/容器/DB 名 bepusdt → vupay(Dockerfile、workflow IMAGE、compose、docs)
- 显示名 BEpusdt → VUPAY(前端 title、后端 banner、version 命令、通知文案)
- 默认路径 /var/lib/bepusdt → /var/lib/vupay,/var/log/bepusdt → /var/log/vupay
- Telegram 通知的频道按钮原来指向上游 t.me 群,改成站点链接(否则改名后是死链)

刻意保留(运行语义,改了会坏):
- api_type 取值 "epusdt" / "epusdt_order"(库里存量数据按此匹配)
- 表前缀 bep_(bep_order / bep_conf / …,改需 RENAME TABLE 迁移)
- 签名函数 EpusdtSign 与 handler 包名 epusdt(对外协议语义,非品牌)
- 所有加密/会话派生的字面量原样不动

验证:gofmt 通过、go build ./... 通过、全仓 grep -i bepusdt 归零
2026-11-25 09:06:06 +08:00
admin 7421d8574b merge ci/mysql-perf:bep_order 复合索引
Docker Build (Gitea) / Build and Push Docker Image (push) Successful in 16s
2026-11-25 08:50:13 +08:00
admin 92cca8a420 perf(db): bep_order 加 (status,trade_type) 复合索引
Docker Build (Gitea) / Build and Push Docker Image (push) Successful in 13s
动机:转账/回调任务反复跑 WHERE status=? AND trade_type IN (...),原来只有单列索引。
10 万行实测(同机 mysql:8.0,1 核):
  IN 两个值:   21.5ms → 0.9ms
  IN 单值:     25.4ms → 16.0ms
  COUNT:       11.4ms → 1.6ms
空表/小表无感,订单积累后差距明显。AutoMigrate 会在新库上自动建同名索引。

顺带:示例 compose 的小机器参数注释更新(buffer pool 256M、慢日志 1s)
2026-11-25 08:49:06 +08:00
admin f94687788d merge ci/compose-shared:MySQL 示例改用共享服务名 mysql
Docker Build (Gitea) / Build and Push Docker Image (push) Successful in 10s
2026-11-25 08:26:50 +08:00
admin fee63db19e docs(compose): MySQL 示例改成通用服务名 mysql + 共享网络
Docker Build (Gitea) / Build and Push Docker Image (push) Successful in 10s
- 服务名/容器名 db/bepusdt-db → mysql,DSN host 同步改成 mysql
- 挂 external 网络 shared-db(AcePanel 用 acepanel-network),同机其它容器可按 mysql:3306 复用
- 3306 只绑 127.0.0.1(宿主机/SSH 隧道用),不对外
- docs: 补「给同机其它容器共用」小节:建网络、其它项目怎么写、独立库+账号的 SQL、两个易错点
2026-11-25 08:24:45 +08:00
admin 4a866731f3 merge ci/build-cache:go build 缓存挂载 + 并行度限制 4(构建期 CPU 峰值 99%→35%,耗时 43s→9.4s)
Docker Build (Gitea) / Build and Push Docker Image (push) Successful in 10s
2026-11-24 21:28:56 +08:00
admin bf686e6f08 chore: 缓存热 + 采样
Docker Build (Gitea) / Build and Push Docker Image (push) Successful in 10s
2026-11-24 21:25:54 +08:00
admin b5c330e311 chore: 缓存已热,测第二次构建
Docker Build (Gitea) / Build and Push Docker Image (push) Successful in 10s
2026-11-24 21:22:49 +08:00
admin eea05adea1 perf(docker): go build 加 cache mount 并把并行编译钉在 4
Docker Build (Gitea) / Build and Push Docker Image (push) Successful in 45s
动机:构建期 go build 按 nproc=8 开并行,7~8 个 compile 进程把 8 核打满(实测整机 96-99%),
而这台机器还跑着 verify 生产 MySQL 和 Gitea。
- --mount=type=cache 让 /go/pkg/mod 与 go-build 缓存持久化,后续提交只重编 main 包
- -p 4 限制并行编译进程数,峰值从 8 核降到 4 核
2026-11-24 21:19:41 +08:00
admin a3f4587d1e merge docs/mysql-compose:MySQL 文档与 compose 示例
Docker Build (Gitea) / Build and Push Docker Image (push) Successful in 42s
2026-11-24 20:09:35 +08:00
admin 4e01e9809e docs: MySQL 段改成「本仓库已支持」,并补三份 compose 示例
Docker Build (Gitea) / Build and Push Docker Image (push) Successful in 45s
- docs/docker/docker.md:上游不支持 MySQL 的事实写清楚;本仓库自 e7a8dd9 起
  支持(MYSQL_DSN),给建库 SQL、DSN 三个必带参数各自的后果、8.0 版本建议
- 新增 docker-compose{.postgres,.mysql}.example.yml 三份可直接用的示例
- .env.example 补 MYSQL_DSN 与优先级说明
- .gitignore 忽略 compose 运行时产生的 data/ logs/ mysqldata/ pgdata/
- README 补本仓库差异说明(CI 镜像地址 + compose 示例 + MySQL 支持)
2026-11-24 20:08:28 +08:00
admin e7a8dd9681 merge feat/mysql:支持 MySQL(MYSQL_DSN)
Docker Build (Gitea) / Build and Push Docker Image (push) Successful in 42s
2026-11-24 20:02:21 +08:00
admin 0ae8a9be0f ci: latest tag 只在 main 分支打,特性分支不再顶掉 latest
Docker Build (Gitea) / Build and Push Docker Image (push) Successful in 42s
2026-11-24 20:01:22 +08:00
admin 647e1b96b1 feat(db): 支持 MySQL(MYSQL_DSN 环境变量 / --mysql 参数)
Docker Build (Gitea) / Build and Push Docker Image (push) Successful in 46s
- app/cmd/flag.go: 新增 MysqlDSNFlag(env MYSQL_DSN)
- start/reset: 读取并传给 model.Init
- model.Init 改为三选一:MySQL > PostgreSQL > SQLite
- 新增 initMysql():连接池参数对齐 Postgres 那套(10/100、30m 生命周期)
- order.go: return_url / notify_url 从 TEXT 改 VARCHAR(1024)
  MySQL 8 不允许 TEXT 列带 DEFAULT(Error 1101),改 varchar 三库通用

实测(真 mysql:8.0 容器):6 张表全部建出,bep_order 列类型符合预期
2026-11-24 19:58:08 +08:00
admin ca239fbce4 ci: 合入 Gitea Actions Docker 构建流程
Docker Build (Gitea) / Build and Push Docker Image (push) Successful in 43s
2026-11-24 19:14:16 +08:00
admin 963c80aaa0 ci: 修正 docker tag(分支名 ci/xxx 里的斜杠换成短横线)
Docker Build (Gitea) / Build and Push Docker Image (push) Successful in 1m40s
2026-11-24 19:10:04 +08:00
admin be344b97f7 ci: 触发重跑(已配好仓库级 TOKEN secret)
Docker Build (Gitea) / Build and Push Docker Image (push) Failing after 11s
2026-11-24 19:06:21 +08:00
admin 59d23a2dc7 ci: 加 Gitea Actions 构建并推送 Docker 镜像(git.viaeon.com/admin/bepusdt)
Docker Build (Gitea) / Build and Push Docker Image (push) Failing after 3s
2026-11-24 19:00:13 +08:00
v03413 8a91be6a15 chore: .gitignore update 2026-11-13 09:38:22 +08:00
v03413 8ff1bce889 docs: 更新安全问题反馈联系邮箱 2026-11-13 09:37:06 +08:00
v03413 5791328de4 refactor: 合并 TON 转账解析的入站消息处理并补充单元测试 2026-11-13 09:20:39 +08:00
v03413 566aa5a486 fix: 修正 stale issue 提示信息中的天数为 3 天 2026-11-10 14:37:55 +08:00
莫名 78db081b35 Merge pull request #248 from sylearn/feat/truncate-match-mode
fix: 前缀匹配按原子精度补齐后比较,并发订单不互相抢付款
2026-11-01 22:10:19 +08:00
sylearn c592d3fb7a fix: fold truncate matching into has_prefix
Per review, drop the separate truncate mode and use its logic for
has_prefix instead. Order amounts are stored without trailing zeros
(1.50 as "1.5"), so the plain string prefix check let the 1.5 order
claim a 1.51 payment meant for a concurrent order on the same address.
Truncate the received amount to the larger of the atom precision and
the order's own decimals, then compare exactly: overpayment below the
atom precision still matches, underpayment and overpayment of a full
atom no longer do.
2026-11-01 22:49:44 +09:00
sylearn 5cb1d6f099 feat: add truncate amount match mode
Truncate the received amount to the atom precision before an exact comparison, so overpayment below the atom precision still matches while concurrent orders on one address (1.50, 1.51, ...) never claim each other's payments.
2026-10-31 23:45:49 +09:00
莫名 ebff24a190 Merge pull request #246 from sylearn/fix/solana-forward-tolerates-slot-retries
fix(solana): keep scanning forward while a few slots retry
2026-10-29 17:33:31 +08:00
莫名 5a1f9def13 Merge pull request #244 from sylearn/fix/solana-pruned-slot-no-retry
fix(solana): give up on slots the node has cleaned up
2026-10-29 17:33:22 +08:00
莫名 448cda9022 Merge pull request #243 from sylearn/fix/solana-drop-stale-lookback
fix(solana): drop lookback ranges of finished orders
2026-10-29 17:33:12 +08:00
sylearn 6784a98c8e test(solana): cover backpressure threshold and recovery 2026-10-29 00:46:44 +08:00
sylearn d54669a8aa fix(solana): keep cleaned slots terminal under concurrency 2026-10-29 00:46:26 +08:00
sylearn 5b3a1ded6d fix(solana): keep lookback progress when the order query fails
lookbackOrdersPending ignored the query error, so a failed read counted
as "no order needs a lookback" and dropped the progress of a range that
was still needed. Return the error and keep the progress until the next
tick can check again.
2026-10-28 13:27:18 +08:00
sylearn 144cdb8c40 fix(solana): keep scanning forward while a few slots retry
syncSlotForward stops fetching the head slot as soon as any slot waits
for a retry. One slot that keeps failing with a timeout, 429 or -32004
therefore holds back every later payment until it succeeds or is given
up after about 7 minutes, although the following slots can be fetched
normally.

Pause forward scanning only when solanaForwardPauseRetries (10) slots
wait for a retry. That still stops new slots from piling into the retry
set during a node outage, while a single failing slot no longer delays
new payments.
2026-10-28 13:24:12 +08:00
sylearn 9131b9d5c4 fix(solana): give up on slots the node has cleaned up
getBlock returns -32001 (BlockCleanedUp) for a slot older than the
node's first available block. Retrying cannot succeed, yet the slot was
retried 10 times over about 7 minutes, and forward scanning stays paused
while any retry is pending.

In production a lookback range from a week earlier hit this for 627
slots at once: forward scanning stopped for about 10 minutes and the
node started to answer 429, which delayed a real payment by four
minutes.

Treat -32001 as final: log an ERROR with the slot number, clear any
retry left from an earlier failure of the same slot, and do not schedule
another one. Other errors keep the bounded retry. The existing retry
test now uses -32004 (block not available), a transient error.
2026-10-28 12:59:38 +08:00
sylearn 2fdb6e81d3 fix(solana): drop lookback ranges of finished orders
lookbackSlots keeps its progress (lookbackNext/lookbackEnd) across ticks,
but returns early through syncBreak once no order needs scanning. When an
order is paid, canceled or expires before its range is fully queued, the
remainder stays in memory. The next Solana order, possibly days later,
resumes that old range first.

In production the remainder was 627 slots from a week earlier. The RPC
node had already pruned them (-32001), every slot was retried, forward
scanning paused while retries were pending, and the node started to
answer 429. A payment made 90 seconds after the order was created was
seen four minutes late.

Before resuming, check that at least one order of the range still needs
a lookback (same condition as hasLookbackOrders); otherwise drop the
remaining range. The check runs before syncBreak so the state is also
cleared while scanning is idle.
2026-10-28 12:58:19 +08:00
莫名 07164853c3 Merge pull request #242 from sylearn/feat/solana-reconcile-expired-orders
feat(solana): reconcile expired orders against token account history
2026-10-19 17:17:48 +08:00
莫名 3a1201e485 Merge branch 'main' into feat/solana-reconcile-expired-orders 2026-10-19 17:14:33 +08:00
莫名 a88d36918a Merge pull request #238 from sylearn/fix/solana-no-skip-while-lagging
fix(solana): keep catching up instead of skipping slots
2026-10-19 17:12:43 +08:00
莫名 46665ce060 Merge pull request #237 from sylearn/fix/solana-slot-retry-limit
fix(solana): stop retrying permanently failing slots
2026-10-19 17:12:28 +08:00
莫名 a4ed778a94 Merge pull request #241 from sylearn/refactor/solana-parse-transaction
refactor(solana): extract transaction parsing with mainnet fixtures
2026-10-19 17:11:38 +08:00
莫名 03980768c7 Merge pull request #239 from sylearn/fix/solana-confirm-offset-from-status
fix(solana): check confirmations from the signature status
2026-10-19 17:11:17 +08:00
莫名 79a67fa942 Merge pull request #240 from sylearn/fix/lookback-window-end
fix(task): cover every pending order window in lookback
2026-10-19 17:10:52 +08:00
莫名 6f1b1ef6f6 Merge pull request #235 from sylearn/fix/solana-lookback-range
fix(solana): validate and resume lookback ranges
2026-10-19 17:09:02 +08:00
莫名 08bb49ea78 Merge pull request #236 from sylearn/fix/solana-skip-failed-transactions
fix(solana): skip transactions that failed on chain
2026-10-19 17:08:10 +08:00
sylearnandClaude Opus 5.5 014bb8e12b feat(solana): reconcile expired orders against token account history
Block scanning gives every slot one chance. A skipped or abandoned slot,
a restart, or an incomplete lookback range loses a payment for good, and
nothing finds it again.

Once a Solana order has been expired for a minute (up to two hours), look
it up once in the receiving token accounts' own history:

- token accounts: the wallet's associated token account, derived locally,
  plus any other account from getTokenAccountsByOwner when the node
  supports it (publicnode's free tier rejects that method);
- getSignaturesForAddress back to the order's creation time, keeping
  successful signatures inside the order window that no order has used;
- getTransaction, parsed with parseTransaction and checked with the
  existing orderTransferMatch. A match is marked confirming and then
  follows the normal confirm and callback flow.

RPC errors leave the order for the next round. Cost: a few RPC calls per
expired Solana order plus one getTransaction per candidate payment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:41:36 +08:00
sylearnandClaude Opus 5.5 efe4a3873e refactor(solana): extract transaction parsing with mainnet fixtures
Move the per-transaction body of slotParse into parseTransaction so the
same parser can be used on getTransaction results. No behavior change:
`git diff -w` shows only the loop/return edits.

Add mainnet fixtures for legacy transfer (USDT), legacy transferChecked,
a transfer to a token account created in the same transaction, and a v1
transaction; expected transfers come from an independent decoder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:37:45 +08:00
sylearnandClaude Opus 5.5 f46b4b7f74 fix(task): cover every pending order window in lookback
pendingLookbackUnix ended the lookback range at the expiry of the last
expired order in created_at order. When a batch mixes expired and still
waiting orders (common after a restart), or an earlier order has a
longer timeout, part of the other orders' windows was outside the range
but they were still marked as looked back.

End the range at the latest min(expired_at, now) over the batch. Used by
every chain's lookback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:25:18 +08:00
sylearnandClaude Opus 5.5 e7f857d21e fix(solana): check confirmations from the signature status
With block_offset_confirm enabled, tradeConfirmHandle compared the
order's slot with lastSlotNum, the forward scan cursor. The cursor stops
moving once no unexpired order is pending and is 0 after a restart, so a
payment matched shortly before expiry stayed "confirming" forever.

Use result.context.slot from the same getSignatureStatuses response
instead. This also removes the unsynchronized read of lastSlotNum from
the confirm goroutines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:23:52 +08:00
sylearnandClaude Opus 5.5 b0292c87dc fix(solana): keep catching up instead of skipping slots
The jump to the latest slot when the scanner falls more than
block_height_max_diff behind is meant for resuming after an idle period
(no pending orders) or on startup. It also fired while orders were
active, e.g. after a retry pause, dropping every slot in between without
a log; payments in those slots were never matched.

Now the scanner jumps only on startup or after idling, and otherwise
logs a warning and keeps catching up within blockQueueLimit per round.
A full queue does not count as idle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:23:17 +08:00
sylearnandClaude Opus 5.5 0354e07232 fix(solana): stop retrying permanently failing slots
- Give up a slot after 10 failed scans (about 7 minutes with the
  existing backoff) and log an ERROR with the slot number. Before, a slot
  that can never be fetched (e.g. "Block cleaned up", -32001) was retried
  forever, and forward sync stayed paused the whole time.
- A retry is queued as soon as its timer fires instead of being
  postponed while the queue is full, so a busy queue is never counted as
  a failed attempt.
- Add shared task test helpers (temporary log dir and SQLite).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:22:59 +08:00
sylearnandClaude Opus 5.5 1f127e237b fix(solana): skip transactions that failed on chain
- slotParse ignores transactions whose meta.err is not null. Failed
  transactions are still included in blocks with their instructions and
  token balances, but every transfer in them was rolled back.
- tradeConfirmHandle only confirms a signature that is finalized and has
  err == null; getSignatureStatuses reports failed transactions as
  finalized too.
- Add mainnet fixtures (failed v1 top-level transfer, failed v0 inner
  transfer, succeeded v0 inner transfer) and tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:22:43 +08:00
sylearn 6dcbc2ad00 fix(solana): validate and resume lookback ranges 2026-10-18 10:48:01 +08:00
v03413 d36d34fe04 fix: 订单 URL 字段改为 text
return_url/notify_url 原为 varchar(255),超长时 PostgreSQL 写入订单报错 (SQLSTATE 22001),由 AutoMigrate 自动变更列类型。

Fix #234
2026-10-15 18:07:53 +08:00
莫名 e769e32b1c Merge pull request #233 from sylearn/fix/solana-rpc-error-retry
fix(solana): retry failed block scans safely
2026-10-14 13:55:37 +08:00
sylearnandClaude Opus 5.5 16a46716c0 fix(solana): retry failed block scans safely
- Validate getBlock JSON, JSON-RPC error, result and result.transactions;
  record scan success only after a complete block is parsed.
- Treat skipped slots (result: null, -32007, -32009) as empty slots.
- Retry failed slots with bounded 2s/5s/15s/30s/60s backoff, one timer
  per slot; pause forward sync while retries are pending.
- Fill the slot queue only up to blockQueueLimit per round, keeping the
  existing BlockHeightMaxDiff jump-ahead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 13:50:23 +08:00
莫名 f2516d3212 Merge pull request #232 from sylearn/fix/solana-v1-transactions
fix(solana): support versioned v1 transactions
2026-10-14 10:11:25 +08:00
sylearn 3dafd2e7e1 fix(solana): support versioned v1 transactions 2026-10-14 02:54:37 +08:00
v03413 aa3bd5097f docs: update 2026-09-30 15:00:44 +08:00
v03413 50f7f16c28 docs: 更换 star 历史图表 2026-09-29 23:20:27 +08:00
v03413 9be43676aa docs: add pr submission guidance 2026-08-05 09:14:58 +08:00
莫名 4d88040fd4 Merge pull request #221 from betaxab/fix-ton-chain-transfer
修复 TON 链掉单问题
2026-08-03 14:24:10 +08:00
莫名 82f7bcfbed Merge branch 'main' into fix-ton-chain-transfer 2026-08-03 14:11:20 +08:00
v03413 fdbecadfb7 feat: 优化收银台支付页金额展示与二维码
在二维码内嵌入代币及网络 Logo,钱包地址高亮首尾字符,
并将法币金额与网络信息合并为一行,提升支付页可读性。

Ps:参考来自群友
2026-07-24 14:56:23 +08:00
v03413 4d6afb48e7 docs: add Alchemy and Infura RPC providers to FAQ 2026-07-24 10:24:36 +08:00
betaxab 7eb0263193 fix: Fixed the issue of dropped orders on the TON blockchain
fix: Set "lookbackDone" only after the lookback has truly completed.
misc: Move TON address validation to utils.
2026-07-24 03:57:58 +08:00
莫名 bf068e1775 Merge pull request #220 from zshuang15/fix/scanner-confirming-orders
fix: keep block scanner awake while orders await confirmation
2026-07-20 09:56:00 +08:00
Zhisheng HuangandClaude Opus 4.8 8c95b5b5b8 fix: keep block scanner awake while orders await confirmation
On EVM chains an order can stall forever in OrderStatusConfirming and never
fire its notify when block_offset_confirm is enabled, even though the payment
is on-chain and has far more than enough confirmations.

Block scanning is demand-driven: syncBreak() halts the forward scan once
hasLookbackOrders() finds no "receivable" orders, and receivableOrderStatuses()
only listed {Waiting, Expired}. When an order moves Waiting -> Confirming and it
is the only pending order, the scanner stops and the in-memory chainBlockNum
freezes. With block_offset_confirm enabled, tradeConfirmHandle() requires
chainBlockNum - RefBlockNum >= ConfirmedOffset, so a frozen chainBlockNum means
the order never reaches the threshold and stays Confirming indefinitely: no
notify is sent and the merchant is never credited. Low-traffic merchants hit
this on essentially every order.

Include OrderStatusConfirming in receivableOrderStatuses() so the scanner keeps
advancing while any order is awaiting confirmation.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 19:28:41 -07:00
v03413 b321da7bba feat: add checkout network ordering 2026-07-15 10:14:56 +08:00
v03413 fc86061ecc docs: add contributor acknowledgements 2026-07-14 13:50:44 +08:00
莫名 62fc6947b8 Merge pull request #219 from long2ice/fix/lock-trade-match-address
fix: use match_address when locking exclusive wallets
2026-07-14 09:14:38 +08:00
long2ice efd1ce348a fix: use match_address when locking exclusive wallets
LockTradeAddress queried bep_order with match_addr (wallet column),
causing Error 1054 and breaking exclusive address checks.
2026-07-14 01:11:03 +08:00
v03413 43c579198a fix: remove order fingerprint index 2026-07-08 17:45:24 +08:00
v03413 e180b52c9a Merge branch 'refs/heads/main' into Fingerprint
# Conflicts:
#	app/handler/epusdt/epusdt.go
#	app/model/order.go
#	app/model/trade.go
2026-07-08 17:38:16 +08:00
v03413 3ca46e7fb9 fix: enforce fingerprint checks on payments 2026-07-08 17:32:11 +08:00
v03413 8076cd4b75 refactor: remove MySQL support and add migrations 2026-07-08 15:47:40 +08:00
v03413 e5e847f18f feat: always allow payment type reselect 2026-07-08 10:45:51 +08:00
v03413 54e73e48e4 fix: filter empty TronGrid API keys 2026-07-08 09:22:52 +08:00
v03413 451da12e09 feat: add client fingerprint checks for orders 2026-07-08 09:20:29 +08:00
v03413 06694a92e8 fix: update default CoinGecko API endpoint 2026-06-29 14:16:01 +08:00
莫名 6bf42ddc1b Merge pull request #215 from betaxab/fix-tron-matchaddr
fix: wallet.go: Pre-initialize MatchAddr = Address to prevent issues: #213
2026-06-29 08:44:27 +08:00
betaxab 1f92306b03 fix: wallet.go: Pre-initialize MatchAddr = Address to prevent issues: #213 2026-06-27 19:32:26 +08:00
莫名 096cb9523a Merge pull request #212 from betaxab/pr-tradetypereselect-add-default-0
fix: order model: add default:0 value to fix #211
2026-06-26 15:37:17 +08:00
betaxab 79982c935f fix: order model: add default:0 value to fix #211 2026-06-26 13:17:50 +08:00
莫名 d1beeafbe8 Merge pull request #210 from betaxab/pr-allow-custom-coingecko-url
feat: syntax.vue: allow entering a custom coingecko api url
2026-06-25 21:25:17 +08:00
莫名 3ebfdb424c Merge branch 'main' into pr-allow-custom-coingecko-url 2026-06-25 20:57:58 +08:00
莫名 95503b75fd Merge pull request #209 from betaxab/pr-allow-use-external-themes
feat: static: allow the deployer to use an external checkout theme
2026-06-25 20:57:44 +08:00
莫名 7ef226b722 Merge branch 'main' into pr-allow-custom-coingecko-url 2026-06-25 20:53:20 +08:00
莫名 3639dad003 Merge branch 'main' into pr-allow-use-external-themes 2026-06-25 20:51:53 +08:00
betaxab bd50f293b4 feat: syntax.vue: allow entering a custom coingecko api url 2026-06-25 20:42:00 +08:00
莫名 482bbf92e2 Merge pull request #208 from betaxab/pr-update-action
ci: pr-check: docker setup actions update to v4
2026-06-25 20:41:38 +08:00
betaxab 275a2a3d22 feat: static: allow the deployer to use an external checkout theme 2026-06-25 15:55:46 +08:00
betaxab cec21fa0a7 ci: pr-check: docker setup actions update to v4 2026-06-25 15:31:45 +08:00
莫名 4ce3c9b2f6 Merge pull request #207 from betaxab/pr-fix-build
fix: epusdt handler: math package missing
2026-06-25 15:23:05 +08:00
betaxab a6381c4aac fix: epusdt handler: math package missing 2026-06-25 15:18:09 +08:00
莫名 1e5896ac96 Merge pull request #206 from v03413/pr-check
ci: add PR Docker build workflow
2026-06-25 09:43:08 +08:00
莫名 827bc48c1d Merge pull request #205 from betaxab/pr-add-tradetype-reselect-feat
feat: Add the ability to reselect order trade types
2026-06-24 09:32:58 +08:00
betaxab 36907635b6 docs: api.md: Improve the API documentation related to the reselect param 2026-06-24 01:22:25 +08:00
betaxab aafbac7b7b feat: Add the ability to reselect order trade types 2026-06-24 00:51:20 +08:00
156 changed files with 4169 additions and 1070 deletions
+7 -6
View File
@@ -2,13 +2,14 @@
LISTEN=127.0.0.1:8080
# 日志文件保存路径
LOG=/var/log/bepusdt/
LOG=/var/log/vupay/
# SQLite 数据库文件路径(如果使用 MySQL,此项可忽略)
SQLITE=/var/lib/bepusdt/sqlite.db
# MySQL 数据库
# MYSQL_DSN=user:password@tcp(127.0.0.1:3306)/bepusdt?charset=utf8mb4&parseTime=True&loc=Local&timeout=3s&readTimeout=10s&writeTimeout=10s
SQLITE=/var/lib/vupay/sqlite.db
# PostgreSQL 数据库
# POSTGRESQL_DSN=postgres://user:password@localhost:5432/bepusdt?sslmode=disable&connect_timeout=3
# POSTGRESQL_DSN=postgres://user:password@localhost:5432/vupay?sslmode=disable&connect_timeout=3&timezone=Asia/Shanghai
# MySQL 数据库(本仓库支持;DSN 里 charset=utf8mb4&parseTime=True&loc=Local 不能省)
# 优先级:MYSQL_DSN > POSTGRESQL_DSN > SQLITE
# MYSQL_DSN=user:password@tcp(127.0.0.1:3306)/vupay?charset=utf8mb4&parseTime=True&loc=Local&timeout=5s
+83
View File
@@ -0,0 +1,83 @@
name: Docker Build (Gitea)
on:
push:
branches:
- main
- 'ci/**'
tags:
- 'v*'
workflow_dispatch:
env:
REGISTRY: git.viaeon.com
IMAGE: git.viaeon.com/admin/vupay
jobs:
build-and-push:
name: Build and Push Docker Image
runs-on: ubuntu
env:
RUNNER_TOOL_CACHE: /toolcache
steps:
- name: Install Docker CLI
run: |
if ! command -v docker &> /dev/null; then
if command -v apk &> /dev/null; then
apk add --no-cache docker-cli git
elif command -v apt-get &> /dev/null; then
apt-get update && apt-get install -y docker.io git
else
curl -fsSL https://download.docker.com/linux/static/stable/x86_64/docker-24.0.7.tgz | tar xz -C /tmp
mv /tmp/docker/docker /usr/local/bin/
chmod +x /usr/local/bin/docker
fi
fi
docker --version
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
fetch-tags: true
- name: Prepare version
id: ver
run: |
SHORT_SHA=$(git rev-parse --short=7 HEAD)
BASE=$(git describe --tags --abbrev=0 2>/dev/null || echo "v0.0.0")
# 分支名可能带斜杠(ci/xxx),docker tag 不允许,统一换成短横线
REF_SLUG=$(echo "${GITHUB_REF_NAME}" | tr '/' '-')
echo "short_sha=${SHORT_SHA}" >> "$GITHUB_OUTPUT"
echo "ref_slug=${REF_SLUG}" >> "$GITHUB_OUTPUT"
echo "version=${BASE}-${SHORT_SHA}" >> "$GITHUB_OUTPUT"
echo "VERSION=${BASE}-${SHORT_SHA}"
- name: Login to Gitea Container Registry
run: |
echo "${{ secrets.TOKEN }}" | docker login "${{ env.REGISTRY }}" -u "${{ github.actor }}" --password-stdin 2>&1
- name: Build Docker image
run: |
# latest 只给 main,特性分支别把 latest 顶掉
TAGS="-t ${{ env.IMAGE }}:${{ steps.ver.outputs.short_sha }} -t ${{ env.IMAGE }}:${{ steps.ver.outputs.ref_slug }}"
if [ "${GITHUB_REF_NAME}" = "main" ]; then TAGS="$TAGS -t ${{ env.IMAGE }}:latest"; fi
docker build \
--label "org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}" \
--label "org.opencontainers.image.revision=${{ github.sha }}" \
--build-arg "VERSION=${{ steps.ver.outputs.version }}" \
$TAGS .
- name: Push Docker image
run: |
docker push "${{ env.IMAGE }}:${{ steps.ver.outputs.short_sha }}" 2>&1
docker push "${{ env.IMAGE }}:${{ steps.ver.outputs.ref_slug }}" 2>&1
if [ "${GITHUB_REF_NAME}" = "main" ]; then docker push "${{ env.IMAGE }}:latest" 2>&1; fi
- name: Summary
run: |
echo "镜像已推送:"
echo " ${{ env.IMAGE }}:${{ steps.ver.outputs.short_sha }}"
echo " ${{ env.IMAGE }}:${{ steps.ver.outputs.ref_slug }}"
echo " ${{ env.IMAGE }}:latest"
+2 -2
View File
@@ -1,5 +1,5 @@
name: BUG 反馈|使用异常|功能建议|其它问题
description: "提交在使用 BEpusdt 过程中遇到的 BUG 反馈、使用异常、对接失败等问题"
description: "提交在使用 VUPAY 过程中遇到的 BUG 反馈、使用异常、对接失败等问题"
body:
- type: checkboxes
attributes:
@@ -45,7 +45,7 @@ body:
attributes:
value: |-
## 日志信息
默认的日志目录在 `/var/log/bepusdt/` 下,请将相关时间段的日志内容粘贴在下面的代码块中。
默认的日志目录在 `/var/log/vupay/` 下,请将相关时间段的日志内容粘贴在下面的代码块中。
- type: textarea
attributes:
label: 日志内容
+1 -1
View File
@@ -1,5 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: Telegram Group
url: https://t.me/BEpusdtChat
url: https://t.me/VUPAYChat
about: Telegram 交流群组
+1 -1
View File
@@ -16,7 +16,7 @@ jobs:
days-before-issue-stale: 3
days-before-issue-close: 7
stale-issue-label: "stale"
stale-issue-message: "此议题由于30天内没有任何活动,现在标记为过时。"
stale-issue-message: "此议题由于3天内没有任何活动,现在标记为过时。"
close-issue-message: "此议题被标记为过时并且在7天内没有活动,因此已被关闭。请随时重新打开此议题以继续讨论。"
days-before-pr-stale: -1
days-before-pr-close: -1
+2 -2
View File
@@ -7,8 +7,8 @@ on:
tags:
- v*
env:
APP_NAME: bepusdt
DOCKERHUB_REPO: v03413/bepusdt
APP_NAME: vupay
DOCKERHUB_REPO: admin/vupay
jobs:
docker:
runs-on: ubuntu-latest
+2 -2
View File
@@ -4,9 +4,9 @@ on:
- cron: '0 16 * * *'
workflow_dispatch:
env:
APP_NAME: bepusdt
APP_NAME: vupay
DOCKER_HUB_USER: v03413
DOCKER_HUB_REPO: v03413/bepusdt
DOCKER_HUB_REPO: admin/vupay
jobs:
build:
runs-on: ubuntu-latest
+3 -4
View File
@@ -14,7 +14,7 @@ concurrency:
permissions:
contents: read
env:
APP_NAME: bepusdt
APP_NAME: vupay
jobs:
docker-build:
name: Docker Build
@@ -27,9 +27,9 @@ jobs:
fetch-depth: 0
fetch-tags: true
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
uses: docker/setup-qemu-action@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
uses: docker/setup-buildx-action@v4
- name: Generate App Version
run: |
echo "APP_VERSION=$(git rev-parse --short=7 HEAD)" >> $GITHUB_ENV
@@ -49,4 +49,3 @@ jobs:
VERSION=${{ env.VERSION_TAG }}
tags: |
${{ env.APP_NAME }}:pr-${{ github.event.pull_request.number }}
+6
View File
@@ -9,3 +9,9 @@ dist/
static/web
static/secure
*.log
AGENTS.md
CLAUDE.md
data/
logs/
mysqldata/
pgdata/
+3 -3
View File
@@ -1,12 +1,12 @@
version: 2
project_name: BEpusdt
project_name: VUPAY
env:
- GO111MODULE=on
builds:
- env:
- CGO_ENABLED=0
main: ./main
binary: bepusdt
binary: vupay
ldflags:
- -X '{{ .ModulePath }}/app.Version={{ .Env.VERSION }}'
- -s -w -buildid=
@@ -25,7 +25,7 @@ archives:
formats: [ zip ]
files:
- .env.example
- src: docs/bepusdt.service
- src: docs/vupay.service
dst: .
strip_parent: true
changelog:
+35 -23
View File
@@ -1,37 +1,36 @@
**❗️作者声明:本项目为研究学习区块链的开源项目,不提供任何形式的收费服务(谨防诈骗)
**❗️作者声明:本项目为研究学习区块链的开源项目,不提供任何形式的收费服务 (谨防诈骗)
,不鼓励任何衍生金融属性的交易行为,不负责任何使用本项目进行的三方行为;使用过程中遇见问题请提`issue`
或群里交流,开源项目请自重!**
---
# BEpusdt (Better Easy Payment USDT)
# VUPAY (Better Easy Payment USDT)
<p align="center">
<img src="./static/checkout/official/assets/img/bepusdt.svg" width="15%" alt="tether">
<img src="./static/checkout/official/assets/img/vupay.svg" width="15%" alt="tether">
</p>
<p align="center">
<a href="https://www.gnu.org/licenses/gpl-3.0.html">
<img src="https://img.shields.io/github/license/v03413/bepusdt" alt="license GPLV3">
<img src="https://img.shields.io/github/license/admin/vupay" alt="license GPLV3">
</a>
<a href="https://github.com/v03413/bepusdt">
<img src="https://img.shields.io/github/v/release/v03413/bepusdt" alt="GitHub Release">
<a href="https://git.viaeon.com/admin/vupay">
<img src="https://img.shields.io/github/v/release/admin/vupay" alt="GitHub Release">
</a>
<a href="https://github.com/v03413/bepusdt">
<img src="https://img.shields.io/github/downloads/v03413/bepusdt/total" alt="GitHub Release">
<a href="https://git.viaeon.com/admin/vupay">
<img src="https://img.shields.io/github/downloads/admin/vupay/total" alt="GitHub Release">
</a>
<a href="https://hub.docker.com/r/v03413/bepusdt">
<img src="https://img.shields.io/docker/pulls/v03413/bepusdt?style=flat-square&logo=docker" alt="Docker Pulls">
<a href="https://hub.docker.com/r/admin/vupay">
<img src="https://img.shields.io/docker/pulls/admin/vupay?style=flat-square&logo=docker" alt="Docker Pulls">
</a>
<a href="https://github.com/gin-gonic/gin">
<img src="https://img.shields.io/github/stars/v03413/bepusdt?style=flat-square&logo=github" alt="GitHub Stars">
<img src="https://img.shields.io/github/stars/admin/vupay?style=flat-square&logo=github" alt="GitHub Stars">
</a>
</p>
## 🪧 介绍
缘起于`Epusdt`,但不仅限于此,加入了一些新特性,致力于成为一款更好用的个人`加密货币`收款网关。
VUPAY 是一款个人`加密货币`收款网关:多链收款、订单自动回调、后台可视化管理。
> 原始 EPusdt 项目已被转手,现与本项目再没任何联系、两个项目完全独立运营,[具体说明](./docs/faq/epusdt.md)。
## 🎉 新特性
@@ -40,7 +39,7 @@
🔥 主流网络:TRON Ethereum BSC Polygon<br>
⚡ 其他网络: X-Layer Solana Aptos Arbitrum-One Base [完整列表](./docs/trade-type.md)
- ✅ 完全兼容 `Epusdt` 插件无缝替换
- ✅ 完全兼容 `Vupay` 插件无缝替换
- ️✅ 支持主流区块网络 不仅限于`USDT`
- ✅ 支持主流法定货币 汇率自动更新
- ✅ 轻依赖 单体二进制文件 部署便捷
@@ -55,19 +54,26 @@
Docker 快速启动,执行完命令打开地址`http://服务器IP:8080`即可看到初始页面
```bash
docker run -d --restart=unless-stopped -p 8080:8080 v03413/bepusdt:latest
docker run -d --restart=unless-stopped -p 8080:8080 admin/vupay:latest
```
> **本仓库(admin/VUPAY)额外提供:**
> - CI 自动构建镜像并推到 `git.viaeon.com/admin/vupay`(`.gitea/workflows/docker.yaml`)
> - 三份 compose 示例:`docker-compose.example.yml`(SQLite)、`docker-compose.postgres.example.yml`、
> `docker-compose.mysql.example.yml`
> - **新增 MySQL 支持**(`MYSQL_DSN`),上游只有 SQLite/PostgreSQL;用法见
> [Docker 部署指南 · MySQL](docs/docker/docker.md)
## 📃 技术文档
- 安装:[Docker](docs/docker/docker.md) [Linux](docs/linux/install.md) [1Panel](./docs/1panel/README.md) [宝塔](./docs/bt_panel/README.md)
- 开发:[API对接](docs/api/api.md) [订单回调](docs/notify/readme.md) [Python](https://github.com/luoyanglang/bepusdt-python-sdk) [PHP](https://github.com/v03413/bepusdt-php-sdk)
- 对接:[独角Next](docs/api/dujiao-next/dujiao-next.md) [彩虹易支付](https://github.com/v03413/Epay-BEpusdt) [whmcs](https://github.com/v03413/whmcs-gateway-epusdt) [其它](docs/api/other.md)
- 开发:[API对接](docs/api/api.md) [订单回调](docs/notify/readme.md) [Python](https://github.com/luoyanglang/vupay-python-sdk) [PHP](https://git.viaeon.com/admin/vupay-php-sdk)
- 对接:[独角Next](docs/api/dujiao-next/dujiao-next.md) [彩虹易支付](https://github.com/v03413/Epay-VUPAY) [whmcs](https://github.com/v03413/whmcs-gateway-vupay) [其它](docs/api/other.md)
- 其它:[https 配置](./docs/ssl.md) [时钟同步](docs/linux/systemd-timesyncd.md) [收银台修改](docs/checkout/README.md)
## 🖼 功能截图
| 前台收银 | 后台订单 | 订单通知 |
|--------------------------------------------------------|------------------------------------------------------|---------------------------------------------------------------|
| 前台收银 | 后台订单 | 订单通知 |
|-----------------------------------------------------------|----------------------------------------------------------|-----------------------------------------------------------------|
| <img src=./docs/images/checkout.png alt=收银台 width=300> | <img src=./docs/images/admin.png alt=后台订单 width=300> | <img src=./docs/images/telegram.png alt=Telegram通知 width=300> |
## ❓ 常见问题
@@ -80,13 +86,19 @@ docker run -d --restart=unless-stopped -p 8080:8080 v03413/bepusdt:latest
## 🏝️ 社区交流
- **Telegram 群组**:[https://t.me/BEpusdtChat](https://t.me/BEpusdtChat)
- **Telegram 频道**:[https://t.me/BEpusdtChannel](https://t.me/BEpusdtChannel)
- **Telegram 群组**:[https://t.me/VUPAYChat](https://t.me/VUPAYChat)
- **Telegram 频道**:[https://t.me/VUPAYChannel](https://t.me/VUPAYChannel)
- **安全问题反馈/联系**:https://u.viaeon.com
## 🙏 致谢
- [EPusdt](./docs/faq/epusdt.md)
感谢为本项目作出贡献的开发者:
<a href="https://git.viaeon.com/admin/vupay/graphs/contributors">
<img src="https://contrib.rocks/image?repo=admin/vupay" alt="VUPAY 贡献者清单">
</a>
## 🌟 Star 历史
[![Stargazers over time](https://starchart.cc/v03413/bepusdt.svg)](https://starchart.cc/v03413/bepusdt)
[![Star History Chart](https://api.star-history.com/chart?repos=admin/vupay&type=date&legend=top-left)](https://www.star-history.com/?repos=v03413%2Fvupay&type=date&legend=top-left)
+10 -10
View File
@@ -4,28 +4,28 @@ import "github.com/urfave/cli/v3"
var SQLiteFlag = &cli.StringFlag{
Name: "sqlite",
Value: "/var/lib/bepusdt/sqlite.db",
Value: "/var/lib/vupay/sqlite.db",
Usage: "SQLite 数据库文件路径",
Sources: cli.EnvVars("SQLITE"),
}
var MySQLDSNFlag = &cli.StringFlag{
Name: "mysql",
Value: "",
Usage: "MySQL 数据库连接字符串 (DSN),例如: user:password@tcp(127.0.0.1:3306)/bepusdt?charset=utf8mb4&parseTime=True&loc=Local&timeout=3s&readTimeout=10s&writeTimeout=10s",
Sources: cli.EnvVars("MYSQL_DSN"),
}
var PostgresDSNFlag = &cli.StringFlag{
Name: "postgres",
Value: "",
Usage: "PostgreSQL 数据库连接字符串 (DSN),例如: postgres://user:password@localhost:5432/bepusdt?sslmode=disable&connect_timeout=3",
Usage: "PostgreSQL 数据库连接字符串 (DSN),例如: postgres://user:password@localhost:5432/vupay?sslmode=disable&connect_timeout=3",
Sources: cli.EnvVars("POSTGRESQL_DSN"),
}
var MysqlDSNFlag = &cli.StringFlag{
Name: "mysql",
Value: "",
Usage: "MySQL 数据库连接字符串 (DSN),例如: user:pass@tcp(127.0.0.1:3306)/vupay?charset=utf8mb4&parseTime=True&loc=Local&timeout=3s",
Sources: cli.EnvVars("MYSQL_DSN"),
}
var LogFlag = &cli.StringFlag{
Name: "log",
Value: "/var/log/bepusdt/",
Value: "/var/log/vupay/",
Usage: "日志文件保存路径",
Sources: cli.EnvVars("LOG"),
}
+7 -7
View File
@@ -5,22 +5,22 @@ import (
"fmt"
"time"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/app/task"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/urfave/cli/v3"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/app/task"
"github.com/v03413/bepusdt/app/utils"
"golang.org/x/crypto/bcrypt"
)
var Reset = &cli.Command{
Name: "reset",
Usage: "忘记密码时,此命令可重置账号密码登录入口",
Flags: []cli.Flag{SQLiteFlag, MySQLDSNFlag, PostgresDSNFlag},
Flags: []cli.Flag{SQLiteFlag, PostgresDSNFlag, MysqlDSNFlag},
Before: func(ctx context.Context, c *cli.Command) (context.Context, error) {
mysql := c.String("mysql")
postgres := c.String("postgres")
sqlite := c.String("sqlite")
if err := model.Init(sqlite, mysql, postgres); err != nil {
postgres := c.String("postgres")
mysql := c.String("mysql")
if err := model.Init(sqlite, postgres, mysql); err != nil {
return ctx, fmt.Errorf("数据库初始化失败 %w", err)
}
+10 -10
View File
@@ -12,12 +12,12 @@ import (
"context"
"github.com/v03413/bepusdt/app"
"github.com/v03413/bepusdt/app/log"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/app/notifier"
"github.com/v03413/bepusdt/app/router"
"github.com/v03413/bepusdt/app/task"
"git.viaeon.com/admin/vupay/app"
"git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/app/notifier"
"git.viaeon.com/admin/vupay/app/router"
"git.viaeon.com/admin/vupay/app/task"
)
import (
@@ -27,12 +27,12 @@ import (
var Start = &cli.Command{
Name: "start",
Usage: "启动收款网关",
Flags: []cli.Flag{SQLiteFlag, MySQLDSNFlag, PostgresDSNFlag, LogFlag, ListenFlag},
Flags: []cli.Flag{SQLiteFlag, PostgresDSNFlag, MysqlDSNFlag, LogFlag, ListenFlag},
Before: func(ctx context.Context, c *cli.Command) (context.Context, error) {
mysql := c.String("mysql")
postgres := c.String("postgres")
mysql := c.String("mysql")
sqlite := c.String("sqlite")
if err := model.Init(sqlite, mysql, postgres); err != nil {
if err := model.Init(sqlite, postgres, mysql); err != nil {
return ctx, fmt.Errorf("数据库初始化失败 %w", err)
}
@@ -84,7 +84,7 @@ func start(ctx context.Context, cmd *cli.Command) error {
notifier.Welcome()
fmt.Println(fmt.Sprintf("日志保存路径:%s", log.GetPath()))
fmt.Println(fmt.Sprintf("BEpusdt 启动成功(%s),当前版本:%s", listen, app.Version))
fmt.Println(fmt.Sprintf("VUPAY 启动成功(%s),当前版本:%s", listen, app.Version))
// 等待中断信号
var signals = make(chan os.Signal, 1)
+2 -2
View File
@@ -4,15 +4,15 @@ import (
"context"
"fmt"
"git.viaeon.com/admin/vupay/app"
"github.com/urfave/cli/v3"
"github.com/v03413/bepusdt/app"
)
var Version = &cli.Command{
Name: "version",
Usage: "显示版本信息",
Action: func(ctx context.Context, cmd *cli.Command) error {
fmt.Println("BEpusdt 版本:" + app.Version)
fmt.Println("VUPAY 版本:" + app.Version)
return nil
},
+2 -2
View File
@@ -2,14 +2,14 @@ package conf
const (
Desc = "一款更好用的个人加密货币收款网关"
Github = "https://github.com/v03413/BEpusdt"
Github = "https://git.viaeon.com/admin/vupay"
)
const Debug = false
const (
Pid = "1000" // 暂时固定易支付商户ID
Api = "https://api.bepusdt.online"
Api = "https://api.vupay.online"
)
const (
+4 -4
View File
@@ -7,10 +7,10 @@ import (
"net/http"
"time"
"git.viaeon.com/admin/vupay/app"
"git.viaeon.com/admin/vupay/app/conf"
"git.viaeon.com/admin/vupay/app/log"
"github.com/tidwall/gjson"
"github.com/v03413/bepusdt/app"
"github.com/v03413/bepusdt/app/conf"
"github.com/v03413/bepusdt/app/log"
)
type Api struct {
@@ -30,7 +30,7 @@ func (Api) get(url string) ([]byte, error) {
return nil, fmt.Errorf("创建请求失败: %w", err)
}
req.Header.Set("User-Agent", fmt.Sprintf("BEpusdt/%s", app.Version))
req.Header.Set("User-Agent", fmt.Sprintf("VUPAY/%s", app.Version))
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
+5 -5
View File
@@ -5,12 +5,12 @@ import (
"strings"
"time"
"git.viaeon.com/admin/vupay/app/conf"
"git.viaeon.com/admin/vupay/app/handler/base"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/app/notifier"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/gin-gonic/gin"
"github.com/v03413/bepusdt/app/conf"
"github.com/v03413/bepusdt/app/handler/base"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/app/notifier"
"github.com/v03413/bepusdt/app/utils"
)
type Conf struct {
+2 -2
View File
@@ -5,11 +5,11 @@ import (
"fmt"
"time"
"git.viaeon.com/admin/vupay/app/handler/base"
"git.viaeon.com/admin/vupay/app/model"
"github.com/gin-gonic/gin"
"github.com/shopspring/decimal"
"github.com/spf13/cast"
"github.com/v03413/bepusdt/app/handler/base"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/go-cache"
)
+4 -4
View File
@@ -3,12 +3,12 @@ package admin
import (
"time"
"git.viaeon.com/admin/vupay/app/handler/base"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/app/task/notify"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/gin-gonic/gin"
"github.com/shopspring/decimal"
"github.com/v03413/bepusdt/app/handler/base"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/app/task/notify"
"github.com/v03413/bepusdt/app/utils"
)
type Order struct {
+2 -2
View File
@@ -3,9 +3,9 @@ package admin
import (
"fmt"
"git.viaeon.com/admin/vupay/app/handler/base"
"git.viaeon.com/admin/vupay/app/model"
"github.com/gin-gonic/gin"
"github.com/v03413/bepusdt/app/handler/base"
"github.com/v03413/bepusdt/app/model"
)
type Rate struct {
+2 -2
View File
@@ -4,9 +4,9 @@ import (
"fmt"
"strings"
"git.viaeon.com/admin/vupay/app/handler/base"
"git.viaeon.com/admin/vupay/app/model"
"github.com/gin-gonic/gin"
"github.com/v03413/bepusdt/app/handler/base"
"github.com/v03413/bepusdt/app/model"
)
type Wallet struct {
+5 -4
View File
@@ -4,13 +4,13 @@ import (
"strings"
"time"
"git.viaeon.com/admin/vupay/app/conf"
"git.viaeon.com/admin/vupay/app/handler/base"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/spf13/cast"
"github.com/v03413/bepusdt/app/conf"
"github.com/v03413/bepusdt/app/handler/base"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/app/utils"
"github.com/v03413/go-cache"
"golang.org/x/crypto/bcrypt"
)
@@ -35,6 +35,7 @@ func (Auth) Info(ctx *gin.Context) {
"trade_type": model.GetAllAlias(),
"trade_fiat": model.GetSupportFiat(),
"trade_crypto": model.GetSupportCrypto(),
"trade_network": model.GetAllNetwork(),
})
}
+1 -1
View File
@@ -3,8 +3,8 @@ package base
import (
"fmt"
"git.viaeon.com/admin/vupay/app/log"
"github.com/gin-gonic/gin"
"github.com/v03413/bepusdt/app/log"
)
type Result struct {
+3 -3
View File
@@ -7,11 +7,11 @@ import (
"net/http"
"sort"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/gin-gonic/gin"
"github.com/shopspring/decimal"
"github.com/spf13/cast"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/app/utils"
)
const Pid = "1000" // 固定商户号
@@ -121,7 +121,7 @@ func (e Epay) verify(data map[string]string) (submit, error) {
pid, ok := data["pid"]
if !ok || pid != Pid {
return params, fmt.Errorf("BEpusdt 易支付兼容模式,商户号【PID】必须固定为" + Pid)
return params, fmt.Errorf("VUPAY 易支付兼容模式,商户号【PID】必须固定为" + Pid)
}
var requiredFields = []string{"pid", "type", "out_trade_no", "notify_url", "return_url", "name", "money", "sign"}
@@ -1,20 +1,21 @@
package epusdt
package vupay
import (
"bytes"
"encoding/json"
"fmt"
"io"
"math"
"time"
"git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/gin-gonic/gin"
"github.com/shopspring/decimal"
"github.com/v03413/bepusdt/app/log"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/app/utils"
)
type Epusdt struct{}
type Vupay struct{}
type createReq struct {
OrderID string `json:"order_id" binding:"required"`
@@ -62,7 +63,22 @@ type methodsReq struct {
Currency string `json:"currency"`
}
func (Epusdt) Notify(ctx *gin.Context) {
func loadPayOrder(ctx *gin.Context, tradeID string) (model.Order, bool) {
order, ok := model.GetTradeOrder(tradeID)
if !ok {
ctx.JSON(200, respFailJson("order not found"))
return model.Order{}, false
}
if order.FingerprintBound() && !order.MatchFingerprint(utils.ClientFingerprint(ctx)) {
ctx.JSON(200, respFailJson("order not found"))
return model.Order{}, false
}
return order, true
}
func (Vupay) Notify(ctx *gin.Context) {
rawData, err := ctx.GetRawData()
if err != nil {
ctx.String(200, "fail")
@@ -81,7 +97,7 @@ func (Epusdt) Notify(ctx *gin.Context) {
return
}
if utils.EpusdtSign(m, model.AuthToken()) != sign {
if utils.VupaySign(m, model.AuthToken()) != sign {
ctx.String(200, "fail")
return
}
@@ -89,7 +105,7 @@ func (Epusdt) Notify(ctx *gin.Context) {
ctx.String(200, "ok")
}
func (Epusdt) CreateOrder(ctx *gin.Context) {
func (Vupay) CreateOrder(ctx *gin.Context) {
var req createOrderReq
if err := ctx.ShouldBindJSON(&req); err != nil {
ctx.JSON(200, respFailJson(fmt.Sprintf("CreateOrder: request error: %s", err.Error())))
@@ -121,7 +137,7 @@ func (Epusdt) CreateOrder(ctx *gin.Context) {
// 创建待付款订单
order, err := model.BuildPendingOrder(model.OrderParams{
Money: decimal.NewFromFloat(req.Amount),
ApiType: model.OrderApiTypeEpusdt,
ApiType: model.OrderApiTypeVupayOrder,
OrderId: req.OrderID,
RedirectUrl: req.RedirectURL,
NotifyUrl: req.NotifyURL,
@@ -148,10 +164,11 @@ func (Epusdt) CreateOrder(ctx *gin.Context) {
"expiration_time": uint64(order.ExpiredAt.Sub(time.Now()).Seconds()),
"payment_url": model.CheckoutUrl(host, order.TradeId),
"network": order.GetMethods(""),
"reselect": order.CanReselectPayment(),
}))
}
func (Epusdt) UpdateOrder(ctx *gin.Context) {
func (Vupay) UpdateOrder(ctx *gin.Context) {
// 接收 trade_id, currency, network 三个参数
var req updateOrderReq
if err := ctx.ShouldBindJSON(&req); err != nil {
@@ -165,15 +182,28 @@ func (Epusdt) UpdateOrder(ctx *gin.Context) {
host = "https://" + ctx.Request.Host
}
// 获取订单
order, ok := model.GetTradeOrder(req.TradeID)
order, ok := loadPayOrder(ctx, req.TradeID)
if !ok {
ctx.JSON(200, respFailJson("order not found"))
return
}
if order.TradeType != "" {
ctx.JSON(200, respFailJson("update order failed: order already has trade type"))
// 仅待付订单才可更新订单
if order.Status != model.OrderStatusWaiting {
ctx.JSON(200, respFailJson("update order failed: order status does not allow payment updates"))
return
}
if order.TradeType != "" && !order.CanReselectPayment() {
ctx.JSON(200, respFailJson("update order failed: order status does not allow payment updates"))
return
}
fp := utils.ClientFingerprint(ctx)
// 拒绝过期订单
remaining := time.Until(order.ExpiredAt)
if remaining <= 0 {
ctx.JSON(200, respFailJson("update order failed: order expired"))
return
}
@@ -188,14 +218,15 @@ func (Epusdt) UpdateOrder(ctx *gin.Context) {
// 注意:RebuildOrder 需要 OrderParams,我们需要从现有订单构造参数
money, _ := decimal.NewFromString(order.Money)
params := model.OrderParams{
Money: money,
OrderId: order.OrderId,
TradeType: tradeType, // 新的交易类型
RedirectUrl: order.ReturnUrl,
NotifyUrl: order.NotifyUrl,
Name: order.Name,
Timeout: int64(order.ExpiredAt.Sub(time.Now()).Seconds()),
Fiat: order.Fiat,
Money: money,
OrderId: order.OrderId,
TradeType: tradeType, // 新的交易类型
RedirectUrl: order.ReturnUrl,
NotifyUrl: order.NotifyUrl,
Name: order.Name,
Timeout: int64(math.Ceil(remaining.Seconds())),
Fiat: order.Fiat,
ClientFingerprint: fp,
}
newOrder, err := model.RebuildOrder(order, params)
@@ -219,7 +250,7 @@ func (Epusdt) UpdateOrder(ctx *gin.Context) {
}))
}
func (Epusdt) CreateTransaction(ctx *gin.Context) {
func (Vupay) CreateTransaction(ctx *gin.Context) {
var req createReq
if err := ctx.ShouldBindJSON(&req); err != nil {
ctx.JSON(200, respFailJson(fmt.Sprintf("请求参数错误:%s", err.Error())))
@@ -247,7 +278,7 @@ func (Epusdt) CreateTransaction(ctx *gin.Context) {
order, err := model.StartBuildOrder(model.OrderParams{
Money: decimal.NewFromFloat(req.Amount),
ApiType: model.OrderApiTypeEpusdt,
ApiType: model.OrderApiTypeVupay,
Address: req.Address,
AddressLocked: req.Amount == 0,
OrderId: req.OrderID,
@@ -282,7 +313,7 @@ func (Epusdt) CreateTransaction(ctx *gin.Context) {
}))
}
func (Epusdt) CancelTransaction(ctx *gin.Context) {
func (Vupay) CancelTransaction(ctx *gin.Context) {
var req cancelReq
if err := ctx.ShouldBindJSON(&req); err != nil {
ctx.JSON(200, respFailJson(fmt.Sprintf("请求参数错误:%s", err.Error())))
@@ -312,7 +343,7 @@ func (Epusdt) CancelTransaction(ctx *gin.Context) {
ctx.JSON(200, respSuccJson(gin.H{"trade_id": req.TradeID}))
}
func (Epusdt) Checkout(ctx *gin.Context) {
func (Vupay) Checkout(ctx *gin.Context) {
tradeId := ctx.Param("trade_id")
if _, ok := model.GetTradeOrder(tradeId); !ok {
ctx.String(200, "order not found")
@@ -326,39 +357,43 @@ func (Epusdt) Checkout(ctx *gin.Context) {
ctx.HTML(200, tmpl, gin.H{"trade_id": tradeId})
}
func (Epusdt) GetMethods(ctx *gin.Context) {
func (Vupay) GetMethods(ctx *gin.Context) {
var req methodsReq
if err := ctx.ShouldBindJSON(&req); err != nil {
ctx.JSON(200, respFailJson(fmt.Sprintf("request error: %s", err.Error())))
return
}
order, ok := model.GetTradeOrder(req.TradeID)
order, ok := loadPayOrder(ctx, req.TradeID)
if !ok {
ctx.JSON(200, respFailJson("order not found"))
return
}
if order.Status == model.OrderStatusExpired {
ctx.JSON(200, respFailJson("order expired"))
if order.Status != model.OrderStatusWaiting {
ctx.JSON(200, respFailJson("error: Invalid order status"))
return
}
if order.TradeType != "" && !order.CanReselectPayment() {
ctx.JSON(200, respFailJson("error: The order status does not allow retrieving the payment method"))
return
}
ctx.JSON(200, respSuccJson(gin.H{
"methods": order.GetMethods(model.Crypto(req.Currency)),
"methods": order.GetMethods(model.Crypto(req.Currency)),
"network_sort": model.GetC(model.PaymentNetworkSort),
}))
}
func (Epusdt) Info(ctx *gin.Context) {
func (Vupay) Info(ctx *gin.Context) {
var req infoReq
if err := ctx.ShouldBindJSON(&req); err != nil {
ctx.JSON(200, respFailJson(fmt.Sprintf("参数错误:%s", err.Error())))
return
}
order, ok := model.GetTradeOrder(req.TradeID)
order, ok := loadPayOrder(ctx, req.TradeID)
if !ok {
ctx.JSON(200, respFailJson("订单不存在"))
return
}
@@ -378,10 +413,11 @@ func (Epusdt) Info(ctx *gin.Context) {
"trade_url": order.GetTxUrl(), // 链上详情
"support_url": model.GetC(model.PaymentSupportUrl), // 客服链接
"redirect_url": order.RedirectUrl(), // 跳转地址
"reselect": order.CanReselectPayment(), // 是否允许确认交易类型后重选
}))
}
func (Epusdt) SignVerify(ctx *gin.Context) {
func (Vupay) SignVerify(ctx *gin.Context) {
rawData, err := ctx.GetRawData()
if err != nil {
ctx.JSON(200, respFailJson(fmt.Sprintf("json 数据读取错误 %s", err.Error())))
@@ -406,7 +442,7 @@ func (Epusdt) SignVerify(ctx *gin.Context) {
return
}
if utils.EpusdtSign(m, model.AuthToken()) != sign {
if utils.VupaySign(m, model.AuthToken()) != sign {
ctx.JSON(200, respFailJson("签名错误"))
ctx.Abort()
+1 -1
View File
@@ -48,7 +48,7 @@ func Init(dir string) error {
var err error
be, err = newLogger(filepath.Join(dir, "bepusdt.log"))
be, err = newLogger(filepath.Join(dir, "vupay.log"))
if err != nil {
return err
}
+14 -5
View File
@@ -7,9 +7,9 @@ import (
"sync"
"time"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/gin-gonic/gin"
"github.com/spf13/cast"
"github.com/v03413/bepusdt/app/utils"
"github.com/v03413/go-cache"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
@@ -47,10 +47,11 @@ var defaultConf = map[ConfKey]string{
PaymentMatchMode: string(Classic),
PaymentSupportUrl: "",
PaymentLookbackHour: "3",
PaymentNetworkSort: "",
SystemInstallLock: "0",
RateSyncCoingeckoApiUrl: "https://api.coingecko.com",
RateSyncHistoryDays: "30",
MqttTopicPrefix: "bepusdt",
MqttTopicPrefix: "vupay",
HomeRedirectUrl: "",
}
@@ -61,7 +62,7 @@ type Conf struct {
func (c Conf) TableName() string {
return "bep_conf"
return "vupay_conf"
}
func SetK(k ConfKey, v string) {
@@ -167,7 +168,7 @@ func ConfInit() {
fmt.Println()
fmt.Println("╔═══════════════════════════════════════════════════════════════════════")
fmt.Println("║ 🎉 欢迎使用 BEpusdt - 首次运行检测,初始化配置完成")
fmt.Println("║ 🎉 欢迎使用 VUPAY - 首次运行检测,初始化配置完成")
fmt.Println("╚═══════════════════════════════════════════════════════════════════════")
fmt.Println()
fmt.Println("┏━━ 🔐 后台登录信息 (请立即保存!)")
@@ -225,7 +226,15 @@ func GetInstallInfo() gin.H {
}
func GetTronGridApiKeys() []string {
return strings.Split(GetK(RpcEndpointTronGridApiKey), ",")
arr := strings.Split(GetC(RpcEndpointTronGridApiKey), ",")
keys := make([]string, 0)
for _, v := range arr {
if v != "" {
keys = append(keys, v)
}
}
return keys
}
func FillDefaultConf() {
+2 -1
View File
@@ -53,6 +53,7 @@ const (
PaymentMatchMode ConfKey = "payment_match_mode" // 订单金额匹配模式
PaymentSupportUrl ConfKey = "payment_support_url" // 订单支付客服链接
PaymentLookbackHour ConfKey = "payment_lookback_hour" // 订单回溯时间
PaymentNetworkSort ConfKey = "payment_network_sort" // 收银台网络顺序,逗号分隔
RpcEndpointPlasma ConfKey = "rpc_endpoint_plasma" // Plasma RPC节点
RpcEndpointBsc ConfKey = "rpc_endpoint_bsc" // BSC RPC节点
@@ -107,7 +108,7 @@ const (
)
const (
Classic MatchMode = "classic" // 经典模式,精确匹配
HasPrefix MatchMode = "has_prefix" // 前缀匹配,允许多付
HasPrefix MatchMode = "has_prefix" // 前缀匹配,按原子精度截断后比较,只容忍精度以下的多付
RoundOff MatchMode = "round_off" // 数值修约,四舍五入,允许容错
)
@@ -0,0 +1,31 @@
package migration
import (
"github.com/go-gormigrate/gormigrate/v2"
"gorm.io/gorm"
)
// 202607081430 - 删除 vupay_order.trade_type_reselect 列
func m202607081430DropOrderTradeTypeReselect() *gormigrate.Migration {
return &gormigrate.Migration{
ID: "202607081430_drop_order_trade_type_reselect",
Migrate: func(tx *gorm.DB) error {
if !tx.Migrator().HasTable("vupay_order") {
return nil
}
if tx.Migrator().HasColumn("vupay_order", "trade_type_reselect") {
return tx.Exec("ALTER TABLE vupay_order DROP COLUMN trade_type_reselect").Error
}
return nil
},
Rollback: func(tx *gorm.DB) error {
if !tx.Migrator().HasTable("vupay_order") {
return nil
}
if !tx.Migrator().HasColumn("vupay_order", "trade_type_reselect") {
return tx.Exec("ALTER TABLE vupay_order ADD COLUMN trade_type_reselect INTEGER NOT NULL DEFAULT 0").Error
}
return nil
},
}
}
+31
View File
@@ -0,0 +1,31 @@
package migration
import (
"github.com/go-gormigrate/gormigrate/v2"
"gorm.io/gorm"
)
const TableName = "vupay_migration"
var migrations = []*gormigrate.Migration{
m202607081430DropOrderTradeTypeReselect(),
}
func Run(db *gorm.DB, initModels []any) error {
if err := db.AutoMigrate(initModels...); err != nil {
return err
}
options := &gormigrate.Options{TableName: TableName}
// 旧版升级/全新安装,构建迁移表
if !db.Migrator().HasTable(TableName) {
if err := db.Exec("CREATE TABLE " + TableName + " (id VARCHAR(255) PRIMARY KEY)").Error; err != nil {
return err
}
}
m := gormigrate.New(db, options, migrations)
return m.Migrate()
}
+60 -55
View File
@@ -6,6 +6,7 @@ import (
"path/filepath"
"time"
"git.viaeon.com/admin/vupay/app/model/migration"
"github.com/glebarez/sqlite"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
@@ -24,19 +25,21 @@ type AutoTimeAt struct {
UpdatedAt *Datetime `gorm:"column:updated_at;not null;comment:最后更新时间" json:"updated_at"`
}
func Init(path, mysql, postgres string) error {
if postgres != "" {
return initPostgres(postgres)
// Init 按优先级选择数据库:MySQL DSN > PostgreSQL DSN > SQLite 文件。
// 三者互斥,填了哪个用哪个;都不填就走 SQLite(默认)。
func Init(db, postgresDSN, mysqlDSN string) error {
switch {
case mysqlDSN != "":
return initMysql(mysqlDSN)
case postgresDSN != "":
return initPostgres(postgresDSN)
default:
return initSqlite(db)
}
if mysql != "" {
return initMySQL(mysql)
}
return initSqlite(path)
}
func initSqlite(path string) error {
if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
func initSqlite(db string) error {
if err := os.MkdirAll(filepath.Dir(db), os.ModePerm); err != nil {
return fmt.Errorf("创建数据库目录失败:%w", err)
}
@@ -47,7 +50,7 @@ func initSqlite(path string) error {
"&_pragma=busy_timeout(8000)"+ // 8 秒超时,兼顾慢速磁盘
"&_pragma=synchronous(NORMAL)"+ // NORMAL 模式,性能与安全平衡
"&_pragma=wal_autocheckpoint(1500)", // 适中的 checkpoint 频率
path)
db)
Db, err = gorm.Open(sqlite.Open(dsn), &gorm.Config{})
if err != nil {
@@ -82,49 +85,6 @@ func initSqlite(path string) error {
return nil
}
func initMySQL(dsn string) error {
var err error
Db, err = gorm.Open(mysql.New(mysql.Config{
DSN: dsn,
DefaultStringSize: 256, // string 类型字段的默认长度
DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
SkipInitializeWithVersion: false, // 根据当前 MySQL 版本自动配置
}), &gorm.Config{})
if err != nil {
return fmt.Errorf("数据库初始化失败:%w", err)
}
{
sqlDB, err := Db.DB()
if err != nil {
return fmt.Errorf("获取数据库连接失败:%w", err)
}
sqlDB.SetMaxOpenConns(100)
sqlDB.SetMaxIdleConns(10)
sqlDB.SetConnMaxLifetime(time.Hour)
}
if err = AutoMigrate(); err != nil {
return fmt.Errorf("数据库结构迁移失败:%w", err)
}
var count int64
Db.Model(&Conf{}).Count(&count)
if count == 0 {
ConfInit()
}
FillDefaultConf()
RefreshC()
return nil
}
func initPostgres(dsn string) error {
// 首次启动可能出现 SLOW SQL 告警,这是由于连接池首次连接预热引起的,后续连接将正常
@@ -166,7 +126,13 @@ func initPostgres(dsn string) error {
}
func AutoMigrate() error {
return Db.AutoMigrate(&Wallet{}, &Order{}, &NotifyRecord{}, &Conf{}, &Rate{})
return migration.Run(Db, []any{
&Wallet{},
&Order{},
&NotifyRecord{},
&Conf{},
&Rate{},
})
}
func Close() {
@@ -187,3 +153,42 @@ func Close() {
_, _ = fmt.Fprintln(os.Stderr, fmt.Sprintf("数据库资源关闭错误:%s", err.Error()))
}
}
func initMysql(dsn string) error {
// 建议 DSN 里带上 charset=utf8mb4&parseTime=True&loc=Local,
// 否则中文/时间字段会出问题:中文变 ?,时间按 UTC 存进去。
Db, err = gorm.Open(mysql.New(mysql.Config{
DSN: dsn,
DefaultStringSize: 256,
SkipInitializeWithVersion: false,
}), &gorm.Config{})
if err != nil {
return err
}
{
sqlDB, err := Db.DB()
if err != nil {
return err
}
sqlDB.SetMaxIdleConns(10)
sqlDB.SetMaxOpenConns(100)
sqlDB.SetConnMaxLifetime(30 * time.Minute)
sqlDB.SetConnMaxIdleTime(10 * time.Minute)
}
if err = AutoMigrate(); err != nil {
return err
}
var count int64
Db.Model(&Conf{}).Count(&count)
if count == 0 {
ConfInit()
}
FillDefaultConf()
RefreshC()
return nil
}
+1 -1
View File
@@ -8,7 +8,7 @@ type NotifyRecord struct {
func (nr NotifyRecord) TableName() string {
return "bep_notify"
return "vupay_notify"
}
func IsNeedNotifyByTxid(txid string) bool {
+60 -36
View File
@@ -9,12 +9,12 @@ import (
"strings"
"time"
"git.viaeon.com/admin/vupay/app/conf"
"git.viaeon.com/admin/vupay/app/core"
"git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/shopspring/decimal"
"github.com/spf13/cast"
"github.com/v03413/bepusdt/app/conf"
"github.com/v03413/bepusdt/app/core"
"github.com/v03413/bepusdt/app/log"
"github.com/v03413/bepusdt/app/utils"
)
const (
@@ -55,37 +55,39 @@ const (
)
const (
OrderApiTypeEpusdt = "epusdt" // epusdt
OrderApiTypeEpay = "epay" // 彩虹易支付
OrderApiTypeAdmin = "admin" // 管理后台
OrderApiTypeVupay = "vupay" // vupay
OrderApiTypeVupayOrder = "vupay_order" // vupay create-order
OrderApiTypeEpay = "epay" // 彩虹易支付
OrderApiTypeAdmin = "admin" // 管理后台
)
type Order struct {
Id
OrderId string `gorm:"column:order_id;type:varchar(128);not null;index;comment:商户ID" json:"order_id"`
TradeId string `gorm:"column:trade_id;type:varchar(128);not null;uniqueIndex;comment:本地ID" json:"trade_id"`
TradeType TradeType `gorm:"column:trade_type;type:varchar(20);not null;index;comment:交易类型" json:"trade_type"`
Fiat Fiat `gorm:"column:fiat;type:varchar(16);not null;index;default:CNY;comment:法定货币" json:"fiat"`
Crypto Crypto `gorm:"column:crypto;type:varchar(16);not null;index;default:USDT;comment:加密货币" json:"crypto"`
CurrencyLimit string `gorm:"column:currency_limit;type:varchar(255);not null;default:'';comment:限定币种" json:"currency_limit"`
Rate string `gorm:"column:rate;type:varchar(10);not null;comment:交易汇率" json:"rate"`
Amount string `gorm:"column:amount;type:varchar(32);not null;default:0.00;comment:交易数额" json:"amount"`
Money string `gorm:"column:money;type:varchar(32);not null;default:0.00;comment:交易金额" json:"money"`
Address string `gorm:"column:address;type:varchar(128);index;not null;comment:收款地址" json:"address"`
FromAddress string `gorm:"column:from_address;type:varchar(128);not null;default:'';comment:支付地址" json:"from_address"`
MatchAddress string `gorm:"column:match_address;type:varchar(128);not null;default:'';comment:校验地址" json:"match_address"`
AddressLocked bool `gorm:"column:address_locked;not null;default:false;comment:地址锁定 1:独占 0:共享" json:"address_locked"`
Status int `gorm:"column:status;not null;default:1;index;index:idx_order_notify_retry,priority:1;comment:交易状态" json:"status"`
Name string `gorm:"column:name;type:varchar(64);not null;default:'';comment:商品名称" json:"name"`
ApiType string `gorm:"column:api_type;type:varchar(20);not null;default:'epusdt';comment:API类型" json:"api_type"`
ReturnUrl string `gorm:"column:return_url;type:varchar(255);not null;default:'';comment:同步地址" json:"return_url"`
NotifyUrl string `gorm:"column:notify_url;type:varchar(255);not null;default:'';comment:异步地址" json:"notify_url"`
NotifyNum int `gorm:"column:notify_num;not null;default:0;index:idx_order_notify_retry,priority:3;comment:回调次数" json:"notify_num"`
NotifyState int `gorm:"column:notify_state;not null;default:0;index:idx_order_notify_retry,priority:2;comment:回调状态 1:成功 0:失败" json:"notify_state"`
RefHash string `gorm:"column:ref_hash;type:varchar(128);not null;default:'';index;comment:交易哈希" json:"ref_hash"`
RefBlockNum int `gorm:"column:ref_block_num;not null;default:0;comment:区块索引" json:"ref_block_num"`
ExpiredAt time.Time `gorm:"column:expired_at;not null;comment:失效时间" json:"expired_at"`
ConfirmedAt *time.Time `gorm:"column:confirmed_at;not null;comment:交易确认时间" json:"confirmed_at"`
OrderId string `gorm:"column:order_id;type:varchar(128);not null;index;comment:商户ID" json:"order_id"`
TradeId string `gorm:"column:trade_id;type:varchar(128);not null;uniqueIndex;comment:本地ID" json:"trade_id"`
TradeType TradeType `gorm:"column:trade_type;type:varchar(20);not null;index;index:idx_order_status_trade,priority:2;comment:交易类型" json:"trade_type"`
Fiat Fiat `gorm:"column:fiat;type:varchar(16);not null;index;default:CNY;comment:法定货币" json:"fiat"`
Crypto Crypto `gorm:"column:crypto;type:varchar(16);not null;index;default:USDT;comment:加密货币" json:"crypto"`
CurrencyLimit string `gorm:"column:currency_limit;type:varchar(255);not null;default:'';comment:限定币种" json:"currency_limit"`
Rate string `gorm:"column:rate;type:varchar(10);not null;comment:交易汇率" json:"rate"`
Amount string `gorm:"column:amount;type:varchar(32);not null;default:0.00;comment:交易数额" json:"amount"`
Money string `gorm:"column:money;type:varchar(32);not null;default:0.00;comment:交易金额" json:"money"`
Address string `gorm:"column:address;type:varchar(128);index;not null;comment:收款地址" json:"address"`
FromAddress string `gorm:"column:from_address;type:varchar(128);not null;default:'';comment:支付地址" json:"from_address"`
MatchAddress string `gorm:"column:match_address;type:varchar(128);not null;default:'';comment:校验地址" json:"match_address"`
AddressLocked bool `gorm:"column:address_locked;not null;default:false;comment:地址锁定 1:独占 0:共享" json:"address_locked"`
Status int `gorm:"column:status;not null;default:1;index;index:idx_order_notify_retry,priority:1;index:idx_order_status_trade,priority:1;comment:交易状态" json:"status"`
Name string `gorm:"column:name;type:varchar(64);not null;default:'';comment:商品名称" json:"name"`
ApiType string `gorm:"column:api_type;type:varchar(20);not null;default:'vupay';comment:API类型" json:"api_type"`
ReturnUrl string `gorm:"column:return_url;type:varchar(1024);not null;default:'';comment:同步地址" json:"return_url"`
NotifyUrl string `gorm:"column:notify_url;type:varchar(1024);not null;default:'';comment:异步地址" json:"notify_url"`
NotifyNum int `gorm:"column:notify_num;not null;default:0;index:idx_order_notify_retry,priority:3;comment:回调次数" json:"notify_num"`
NotifyState int `gorm:"column:notify_state;not null;default:0;index:idx_order_notify_retry,priority:2;comment:回调状态 1:成功 0:失败" json:"notify_state"`
RefHash string `gorm:"column:ref_hash;type:varchar(128);not null;default:'';index;comment:交易哈希" json:"ref_hash"`
RefBlockNum int `gorm:"column:ref_block_num;not null;default:0;comment:区块索引" json:"ref_block_num"`
ExpiredAt time.Time `gorm:"column:expired_at;not null;comment:失效时间" json:"expired_at"`
ConfirmedAt *time.Time `gorm:"column:confirmed_at;not null;comment:交易确认时间" json:"confirmed_at"`
ClientFingerprint string `gorm:"column:client_fingerprint;type:varchar(64);not null;default:'';comment:'客户端指纹'" json:"-"`
AutoTimeAt
}
@@ -108,6 +110,27 @@ func (o *Order) SetCanceled() error {
return Db.Save(o).Error
}
// CanReselectPayment 判断订单是否支持重选交易类型
func (o *Order) CanReselectPayment() bool {
if o.Status != OrderStatusWaiting {
return false
}
if o.ApiType != OrderApiTypeVupayOrder && o.ApiType != OrderApiTypeAdmin {
return false
}
return true
}
func (o *Order) FingerprintBound() bool {
return o.ClientFingerprint != ""
}
func (o *Order) MatchFingerprint(fingerprint string) bool {
return !o.FingerprintBound() || o.ClientFingerprint == fingerprint
}
func (o *Order) SetExpired() {
o.Status = OrderStatusExpired
@@ -202,9 +225,10 @@ func (o *Order) BuildNotifyParams() string {
func (o *Order) GetMethods(crypto Crypto) []MethodItem {
var items = make([]MethodItem, 0)
if o.TradeType != "" {
// 已经选好了付款网络,没必要再给出可选项
if o.Status != OrderStatusWaiting {
return items
}
if o.TradeType != "" && !o.CanReselectPayment() {
return items
}
@@ -314,7 +338,7 @@ func (o *Order) Network() any {
}
func (o *Order) TableName() string {
return "bep_order"
return "vupay_order"
}
func GetTradeOrder(tradeId string) (Order, bool) {
@@ -396,7 +420,7 @@ func LockTradeAddress(wallets []Wallet, t TradeType) (Wallet, string, error) {
status := []int{OrderStatusConfirming, OrderStatusWaiting}
for _, w := range wallets {
var o Order
Db.Where("match_addr = ? and status in (?) and trade_type = ? and address_locked = ?", w.GetMatchAddr(), status, t, true).Order("id desc").Limit(1).Find(&o)
Db.Where("match_address = ? and status in (?) and trade_type = ? and address_locked = ?", w.GetMatchAddr(), status, t, true).Order("id desc").Limit(1).Find(&o)
if o.ID == 0 {
return w, zero, nil
}
+5 -5
View File
@@ -10,12 +10,12 @@ import (
"strings"
"time"
"git.viaeon.com/admin/vupay/app"
"git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/shopspring/decimal"
"github.com/spf13/cast"
"github.com/tidwall/gjson"
"github.com/v03413/bepusdt/app"
"github.com/v03413/bepusdt/app/log"
"github.com/v03413/bepusdt/app/utils"
"gorm.io/gorm"
)
@@ -30,7 +30,7 @@ type Rate struct {
}
func (r *Rate) TableName() string {
return "bep_rate"
return "vupay_rate"
}
func (r *Rate) BeforeCreate(*gorm.DB) error {
@@ -68,7 +68,7 @@ func CoingeckoRate() error {
}
req.Header.Set("x-cg-demo-api-key", GetC(RateSyncCoingeckoApiKey))
req.Header.Set("User-Agent", fmt.Sprintf("BEpusdt/%s", app.Version))
req.Header.Set("User-Agent", fmt.Sprintf("VUPAY/%s", app.Version))
resp, err := client.Do(req)
if err != nil {
+20 -1
View File
@@ -4,8 +4,8 @@ import (
"fmt"
"strings"
"git.viaeon.com/admin/vupay/app/conf"
"github.com/shopspring/decimal"
"github.com/v03413/bepusdt/app/conf"
)
// supportFiat 支持的法定货币
@@ -342,6 +342,15 @@ func GetAllAlias() map[string]string {
return alias
}
func GetAllNetwork() map[string]string {
var networks = make(map[string]string)
for _, c := range registry {
networks[string(c.Network)] = c.NetworkName
}
return networks
}
func GetAllTradeConfig() map[string]TradeTypeConf {
var config = make(map[string]TradeTypeConf)
@@ -387,6 +396,16 @@ func GetTxUrl(t TradeType, hash string) string {
return "https://tronscan.org/#/transaction/" + hash
}
func GetTradeContract(t TradeType) string {
c, ok := registry[t]
if !ok {
return ""
}
return c.Contract
}
func GetTradeDecimal(t TradeType) int32 {
c, ok := registry[t]
if !ok {
+47 -17
View File
@@ -6,26 +6,27 @@ import (
"sync"
"time"
"git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/shopspring/decimal"
"github.com/spf13/cast"
"github.com/v03413/bepusdt/app/log"
"github.com/v03413/bepusdt/app/utils"
)
type OrderParams struct {
Money decimal.Decimal `json:"money"` // 交易金额 (单位:法币)s
ApiType string `json:"api_type"` // 支付 API 类型
Address string `json:"address"` // 收款地址
OrderId string `json:"order_id"` // 商户订单 ID
TradeType TradeType `json:"trade_type"` // 交易类型
RedirectUrl string `json:"redirect_url"` // 成功跳转地址
NotifyUrl string `json:"notify_url"` // 异步通知地址
Name string `json:"name"` // 商品名称
Timeout int64 `json:"timeout"` // 订单超时时间(秒)
Rate string `json:"rate"` // 强制指定汇率
Fiat Fiat `json:"fiat"` // 法币类型
CurrencyLimit string `json:"currency_limit"` // 限定币种
AddressLocked bool `json:"address_locked"` // 地址独占锁定
Money decimal.Decimal `json:"money"` // 交易金额 (单位:法币)s
ApiType string `json:"api_type"` // 支付 API 类型
Address string `json:"address"` // 收款地址
OrderId string `json:"order_id"` // 商户订单 ID
TradeType TradeType `json:"trade_type"` // 交易类型
RedirectUrl string `json:"redirect_url"` // 成功跳转地址
NotifyUrl string `json:"notify_url"` // 异步通知地址
Name string `json:"name"` // 商品名称
Timeout int64 `json:"timeout"` // 订单超时时间(秒)
Rate string `json:"rate"` // 强制指定汇率
Fiat Fiat `json:"fiat"` // 法币类型
CurrencyLimit string `json:"currency_limit"` // 限定币种
AddressLocked bool `json:"address_locked"` // 地址独占锁定
ClientFingerprint string `json:"client_fingerprint"` // 客户端指纹
}
type Addr struct {
@@ -49,7 +50,8 @@ func StartBuildOrder(p OrderParams) (Order, error) {
if !utils.IsValidTronAddress(p.Address) &&
!utils.IsValidEvmAddress(p.Address) &&
!utils.IsValidSolanaAddress(p.Address) &&
!utils.IsValidAptosAddress(p.Address) {
!utils.IsValidAptosAddress(p.Address) &&
!utils.IsValidTonAddress(p.Address) {
return order, fmt.Errorf("钱包地址格式错误:%s", p.Address)
}
@@ -188,6 +190,10 @@ func RebuildOrder(t Order, p OrderParams) (Order, error) {
return t, err
}
if t.TradeType == "" && p.ClientFingerprint != "" {
t.ClientFingerprint = p.ClientFingerprint
}
t.Fiat = p.Fiat
t.Address = data.Wallet.GetPaymentAddr()
t.MatchAddress = data.Wallet.GetMatchAddr()
@@ -198,7 +204,31 @@ func RebuildOrder(t Order, p OrderParams) (Order, error) {
t.Rate = fmt.Sprintf("%v", data.Rate)
t.ExpiredAt = CalcTradeExpiredAt(p.Timeout)
return t, Db.Save(&t).Error
query := Db.Model(&Order{}).Where("id = ?", t.ID)
if p.ClientFingerprint != "" {
query = query.Where("(client_fingerprint = '' OR client_fingerprint = ?)", p.ClientFingerprint)
}
res := query.Updates(map[string]any{
"fiat": t.Fiat,
"address": t.Address,
"match_address": t.MatchAddress,
"crypto": t.Crypto,
"amount": t.Amount,
"money": t.Money,
"trade_type": t.TradeType,
"rate": t.Rate,
"expired_at": t.ExpiredAt,
"client_fingerprint": t.ClientFingerprint,
})
if res.Error != nil {
return t, res.Error
}
if res.RowsAffected == 0 {
return t, fmt.Errorf("client fingerprint mismatch")
}
return t, nil
}
// BuildPendingOrder 创建待支付订单(不锁定地址和汇率)
+6 -5
View File
@@ -4,8 +4,8 @@ import (
"errors"
"strings"
"github.com/v03413/bepusdt/app/conf"
"github.com/v03413/bepusdt/app/utils"
"git.viaeon.com/admin/vupay/app/conf"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/xssnick/tonutils-go/address"
)
@@ -30,7 +30,7 @@ type Wallet struct {
func (wa *Wallet) TableName() string {
return "bep_wallet"
return "vupay_wallet"
}
func (wa *Wallet) SetStatus(status uint8) {
@@ -40,6 +40,7 @@ func (wa *Wallet) SetStatus(status uint8) {
func (wa *Wallet) Validate() error {
tradeType := TradeType(wa.TradeType)
wa.MatchAddr = wa.Address
switch tradeType {
case TronTrx, UsdtTrc20, UsdcTrc20:
@@ -55,7 +56,7 @@ func (wa *Wallet) Validate() error {
return errors.New("钱包地址格式不合法,请检查")
}
case UsdtTon:
if !strings.HasPrefix(wa.Address, "UQ") {
if !utils.IsValidTonAddress(wa.Address) {
return errors.New("TON 地址必须以 UQ 开头")
}
owner, err := address.ParseAddr(wa.Address)
@@ -69,7 +70,7 @@ func (wa *Wallet) Validate() error {
wa.MatchAddr = addr.Bounce(false).String()
return nil
case TonGram:
if !strings.HasPrefix(wa.Address, "UQ") {
if !utils.IsValidTonAddress(wa.Address) {
return errors.New("TON 地址必须以 UQ 开头")
}
owner, err := address.ParseAddr(wa.Address)
+3 -3
View File
@@ -5,9 +5,9 @@ import (
"os"
"sync"
"git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/model"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/v03413/bepusdt/app/log"
"github.com/v03413/bepusdt/app/model"
)
type activeConf struct {
@@ -55,7 +55,7 @@ func Reload() error {
opts.AddBroker(fmt.Sprintf("tcp://%s:%s", newConf.host, newConf.port))
opts.SetUsername(newConf.user)
opts.SetPassword(newConf.pass)
opts.SetClientID(fmt.Sprintf("BEpusdt %d", os.Getpid()))
opts.SetClientID(fmt.Sprintf("VUPAY %d", os.Getpid()))
opts.SetAutoReconnect(true)
opts.SetOrderMatters(false)
opts.SetOnConnectHandler(onConnectHandler)
+1 -1
View File
@@ -1,8 +1,8 @@
package mqtt
import (
"git.viaeon.com/admin/vupay/app/log"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/v03413/bepusdt/app/log"
)
// Publish 发布消息。若 MQTT 未连接则静默丢弃,返回 nil。
+1 -1
View File
@@ -3,8 +3,8 @@ package mqtt
import (
"fmt"
"git.viaeon.com/admin/vupay/app/log"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/v03413/bepusdt/app/log"
)
type callback struct {
+1 -1
View File
@@ -1,6 +1,6 @@
package notifier
import "github.com/v03413/bepusdt/app/model"
import "git.viaeon.com/admin/vupay/app/model"
type None struct{}
+2 -2
View File
@@ -1,8 +1,8 @@
package notifier
import (
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/app/utils"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/app/utils"
)
const (
+7 -8
View File
@@ -6,15 +6,15 @@ import (
"strings"
"time"
"git.viaeon.com/admin/vupay/app"
"git.viaeon.com/admin/vupay/app/conf"
"git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
"github.com/spf13/cast"
"github.com/tidwall/gjson"
"github.com/v03413/bepusdt/app"
"github.com/v03413/bepusdt/app/conf"
"github.com/v03413/bepusdt/app/log"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/app/utils"
"github.com/v03413/tronprotocol/core"
)
@@ -201,7 +201,7 @@ func (t *Telegram) TronResourceChange(res model.TronResource) {
func (t *Telegram) Welcome() {
text := `
👋 欢迎使用 BEpusdt,` + conf.Desc + `,如果您看到此消息,说明系统已启动成功!
👋 欢迎使用 VUPAY,` + conf.Desc + `,如果您看到此消息,说明系统已启动成功!
📌当前版本:` + app.Version + `
🎉开源地址:` + conf.Github + `
@@ -212,8 +212,7 @@ func (t *Telegram) Welcome() {
ReplyMarkup: models.InlineKeyboardMarkup{
InlineKeyboard: [][]models.InlineKeyboardButton{
{
{Text: "📢 关注频道", URL: "https://t.me/BEpusdtChannel"},
{Text: "💬 社区交流", URL: "https://t.me/BEpusdtChat"},
{Text: "🌐 访问站点", URL: "https://u.viaeon.com"},
},
},
},
+1 -1
View File
@@ -3,7 +3,7 @@ package notifier
import (
"testing"
"github.com/v03413/bepusdt/app/model"
"git.viaeon.com/admin/vupay/app/model"
)
func TestNonOrderTransferTitleUsesMatchAddress(t *testing.T) {
+1 -1
View File
@@ -1,7 +1,7 @@
package notifier
import (
"github.com/v03413/bepusdt/app/model"
"git.viaeon.com/admin/vupay/app/model"
)
type Wechat struct{}
+1 -1
View File
@@ -1,8 +1,8 @@
package router
import (
"git.viaeon.com/admin/vupay/app/handler/admin"
"github.com/gin-gonic/gin"
"github.com/v03413/bepusdt/app/handler/admin"
)
func adminInit(e *gin.Engine) {
+1 -1
View File
@@ -1,8 +1,8 @@
package router
import (
"git.viaeon.com/admin/vupay/app/handler/auth"
"github.com/gin-gonic/gin"
"github.com/v03413/bepusdt/app/handler/auth"
)
func authInit(e *gin.Engine) {
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"strings"
"testing"
"github.com/v03413/bepusdt/static"
"git.viaeon.com/admin/vupay/static"
)
func TestLangGeCheckoutTemplateIsEmbedded(t *testing.T) {
+1 -1
View File
@@ -1,8 +1,8 @@
package router
import (
"git.viaeon.com/admin/vupay/app/handler/epay"
"github.com/gin-gonic/gin"
"github.com/v03413/bepusdt/app/handler/epay"
)
func epayInit(engine *gin.Engine) {
+5 -5
View File
@@ -5,13 +5,13 @@ import (
"fmt"
"net/http"
"git.viaeon.com/admin/vupay/app/conf"
"git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/model"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/memstore"
"github.com/gin-gonic/gin"
"github.com/spf13/cast"
"github.com/v03413/bepusdt/app/conf"
"github.com/v03413/bepusdt/app/log"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/go-cache"
)
@@ -59,7 +59,7 @@ func Handler() *gin.Engine {
{
staticInit(engine)
epusdtInit(engine)
vupayInit(engine)
epayInit(engine)
adminInit(engine)
authInit(engine)
@@ -131,7 +131,7 @@ func noRoute() gin.HandlerFunc {
func copyright() gin.HandlerFunc {
return func(ctx *gin.Context) {
ctx.Writer.Header().Set("Payment-Gateway", "https://github.com/v03413/BEpusdt")
ctx.Writer.Header().Set("Payment-Gateway", "https://git.viaeon.com/admin/vupay")
}
}
+26 -8
View File
@@ -7,13 +7,14 @@ import (
"html/template"
"io/fs"
"net/http"
"os"
"path"
"strings"
"git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/static"
"github.com/gin-gonic/gin"
"github.com/v03413/bepusdt/app/log"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/static"
)
func staticInit(e *gin.Engine) {
@@ -22,8 +23,11 @@ func staticInit(e *gin.Engine) {
template.Must(tmpl.ParseFS(static.Secure, "secure/secure.html"))
template.Must(tmpl.ParseFS(static.Payment, "payment/views/*.html"))
checkoutFS, checkoutRoot, checkoutSourceDesc := checkoutSource()
log.Info("当前使用", checkoutSourceDesc)
// 注册收银台模板和静态资源
entries, err := fs.ReadDir(static.Checkout, "checkout")
entries, err := fs.ReadDir(checkoutFS, checkoutRoot)
if err != nil {
panic(errors.New(fmt.Sprintf("收银台模板读取异常:%v", err)))
}
@@ -34,18 +38,18 @@ func staticInit(e *gin.Engine) {
}
name := entry.Name()
dir := path.Join("checkout", name)
checkout, err := readCheckoutInfoFromFS(static.Checkout, dir)
dir := path.Join(checkoutRoot, name)
checkout, err := readCheckoutInfoFromFS(checkoutFS, dir)
if err != nil {
panic(err)
}
if registerTemplatesFromFS(tmpl, static.Checkout, dir, name) {
if registerTemplatesFromFS(tmpl, checkoutFS, dir, name) {
model.RegisterCheckout(name, checkout)
log.Info("前台收银模板注册成功:", name)
}
registerAssetsFromFS(e, static.Checkout, dir, "/checkout/"+name+"/assets")
registerAssetsFromFS(e, checkoutFS, dir, "/checkout/"+name+"/assets")
}
e.SetHTMLTemplate(tmpl)
@@ -53,6 +57,20 @@ func staticInit(e *gin.Engine) {
e.StaticFS("/secure/assets", http.FS(subFS(static.Secure, "secure/assets")))
}
func checkoutSource() (fs.FS, string, string) {
const externalStaticDir = "static"
const checkoutRoot = "checkout"
const externalCheckoutDir = externalStaticDir + "/" + checkoutRoot
if info, err := os.Stat(externalCheckoutDir); err == nil && info.IsDir() {
return os.DirFS(externalStaticDir), checkoutRoot, "外部收银台模板目录:" + externalCheckoutDir
} else if err != nil && !errors.Is(err, os.ErrNotExist) {
return static.Checkout, checkoutRoot, "内嵌收银台模板(外部目录读取失败:" + err.Error() + ")"
}
return static.Checkout, checkoutRoot, "内嵌收银台模板"
}
func readCheckoutInfoFromFS(src fs.FS, baseDir string) (model.Checkout, error) {
infoPath := path.Join(baseDir, "checkout.json")
data, err := fs.ReadFile(src, infoPath)
+3 -3
View File
@@ -1,13 +1,13 @@
package router
import (
"git.viaeon.com/admin/vupay/app/handler/vupay"
"github.com/gin-gonic/gin"
"github.com/v03413/bepusdt/app/handler/epusdt"
)
func epusdtInit(engine *gin.Engine) {
func vupayInit(engine *gin.Engine) {
epGrp := engine.Group("/pay")
epHdr := new(epusdt.Epusdt)
epHdr := new(vupay.Vupay)
{
epGrp.GET("/checkout/:trade_id", epHdr.Checkout)
}
+60
View File
@@ -0,0 +1,60 @@
package task
import (
"testing"
"git.viaeon.com/admin/vupay/app/model"
"github.com/shopspring/decimal"
)
func TestAmountMatchHasPrefix(t *testing.T) {
initTaskTestEnv(t, map[model.ConfKey]string{model.PaymentMatchMode: string(model.HasPrefix)})
cases := []struct {
paid, order string
want bool
}{
{"1.5", "1.5", true},
{"1.50123", "1.5", true},
{"1.509", "1.5", true},
{"1.51", "1.5", false},
{"1.4999", "1.5", false},
{"2", "2", true},
{"2.009", "2", true},
{"2.01", "2", false},
{"2.5", "2", false},
{"10.379", "10.37", true},
{"10.38", "10.37", false},
{"20", "2", false},
{"100.5", "100", false},
{"123.456789", "123.45", true},
// 订单金额小数位多于原子精度时按订单金额的小数位截断
{"1.5059", "1.505", true},
{"1.506", "1.505", false},
}
for _, c := range cases {
got := amountMatch(decimal.RequireFromString(c.paid), c.order, string(model.UsdtTrc20))
if got != c.want {
t.Errorf("paid %s order %s: got %v, want %v", c.paid, c.order, got, c.want)
}
}
}
// 同一地址并发订单按原子精度递增金额,截断后每笔付款最多对应其中一笔
func TestAmountMatchHasPrefixConcurrentOrders(t *testing.T) {
initTaskTestEnv(t, map[model.ConfKey]string{model.PaymentMatchMode: string(model.HasPrefix)})
orders := []string{"1.5", "1.51", "1.52"}
payments := map[string]string{"1.5": "1.5", "1.50123": "1.5", "1.51": "1.51", "1.519": "1.51", "1.52": "1.52"}
for paid, want := range payments {
var matched []string
for _, o := range orders {
if amountMatch(decimal.RequireFromString(paid), o, string(model.UsdtTrc20)) {
matched = append(matched, o)
}
}
if len(matched) != 1 || matched[0] != want {
t.Errorf("paid %s matched %v, want only %s", paid, matched, want)
}
}
}
+5 -5
View File
@@ -10,16 +10,16 @@ import (
"sync"
"time"
"git.viaeon.com/admin/vupay/app/conf"
blockapi "git.viaeon.com/admin/vupay/app/core"
"git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/panjf2000/ants/v2"
"github.com/shopspring/decimal"
"github.com/smallnest/chanx"
"github.com/spf13/cast"
"github.com/tidwall/gjson"
"github.com/v03413/bepusdt/app/conf"
blockapi "github.com/v03413/bepusdt/app/core"
"github.com/v03413/bepusdt/app/log"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/app/utils"
)
type aptos struct {
+2 -2
View File
@@ -4,9 +4,9 @@ import (
"context"
"time"
"git.viaeon.com/admin/vupay/app/conf"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/smallnest/chanx"
"github.com/v03413/bepusdt/app/conf"
"github.com/v03413/bepusdt/app/utils"
)
func arbitrumInit() {
+2 -2
View File
@@ -4,9 +4,9 @@ import (
"context"
"time"
"git.viaeon.com/admin/vupay/app/conf"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/smallnest/chanx"
"github.com/v03413/bepusdt/app/conf"
"github.com/v03413/bepusdt/app/utils"
)
func baseInit() {
+3 -3
View File
@@ -4,10 +4,10 @@ import (
"context"
"time"
"git.viaeon.com/admin/vupay/app/conf"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/smallnest/chanx"
"github.com/v03413/bepusdt/app/conf"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/app/utils"
)
func bscInit() {
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"context"
"time"
"github.com/v03413/bepusdt/app/model"
"git.viaeon.com/admin/vupay/app/model"
)
type rConf struct {
+3 -3
View File
@@ -4,10 +4,10 @@ import (
"context"
"time"
"git.viaeon.com/admin/vupay/app/conf"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/smallnest/chanx"
"github.com/v03413/bepusdt/app/conf"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/app/utils"
)
func ethInit() {
+5 -5
View File
@@ -12,16 +12,16 @@ import (
"sync"
"time"
"git.viaeon.com/admin/vupay/app/conf"
blockapi "git.viaeon.com/admin/vupay/app/core"
"git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/panjf2000/ants/v2"
"github.com/shopspring/decimal"
"github.com/smallnest/chanx"
"github.com/spf13/cast"
"github.com/tidwall/gjson"
"github.com/v03413/bepusdt/app/conf"
blockapi "github.com/v03413/bepusdt/app/core"
"github.com/v03413/bepusdt/app/log"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/app/utils"
)
const (
+2 -2
View File
@@ -7,10 +7,10 @@ import (
"strings"
"time"
"git.viaeon.com/admin/vupay/app/model"
appMqtt "git.viaeon.com/admin/vupay/app/mqtt"
"github.com/shopspring/decimal"
"github.com/spf13/cast"
"github.com/v03413/bepusdt/app/model"
appMqtt "github.com/v03413/bepusdt/app/mqtt"
"github.com/v03413/go-cache"
)
+6 -6
View File
@@ -4,11 +4,11 @@ import (
"context"
"time"
"github.com/v03413/bepusdt/app/log"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/app/notifier"
"github.com/v03413/bepusdt/app/task/notify"
"github.com/v03413/bepusdt/app/utils"
"git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/app/notifier"
"git.viaeon.com/admin/vupay/app/task/notify"
"git.viaeon.com/admin/vupay/app/utils"
)
func init() {
@@ -35,7 +35,7 @@ func notifyRetry(context.Context) {
func notifyRoll(context.Context) {
for _, o := range model.GetOrderByStatus(model.OrderStatusWaiting) {
notify.Bepusdt(o)
notify.Vupay(o)
}
}
+19 -19
View File
@@ -10,12 +10,12 @@ import (
"strings"
"time"
"git.viaeon.com/admin/vupay/app"
"git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/app/notifier"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/spf13/cast"
"github.com/v03413/bepusdt/app"
"github.com/v03413/bepusdt/app/log"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/app/notifier"
"github.com/v03413/bepusdt/app/utils"
"github.com/v03413/go-cache"
"gorm.io/gorm"
@@ -45,7 +45,7 @@ func Handle(order model.Order) error {
if order.ApiType == model.OrderApiTypeEpay {
err = epay(ctx, order)
} else {
err = epusdt(ctx, order)
err = vupay(ctx, order)
}
if err != nil {
@@ -66,7 +66,7 @@ func epay(ctx context.Context, order model.Order) error {
return err2
}
postReq.Header.Set("Powered-By", "https://github.com/v03413/bepusdt")
postReq.Header.Set("Powered-By", "https://git.viaeon.com/admin/vupay")
resp, err := client.Do(postReq)
if err != nil {
return err
@@ -102,7 +102,7 @@ func epay(ctx context.Context, order model.Order) error {
return nil
}
func epusdt(ctx context.Context, order model.Order) error {
func vupay(ctx context.Context, order model.Order) error {
var data = make(map[string]interface{})
var body = EpNotify{
TradeId: order.TradeId,
@@ -123,7 +123,7 @@ func epusdt(ctx context.Context, order model.Order) error {
}
// 签名
body.Signature = utils.EpusdtSign(data, model.AuthToken())
body.Signature = utils.VupaySign(data, model.AuthToken())
// 再次序列化
jsonBody, err = json.Marshal(body)
@@ -136,8 +136,8 @@ func epusdt(ctx context.Context, order model.Order) error {
}
postReq.Header.Set("Content-Type", "application/json")
postReq.Header.Set("Powered-By", "https://github.com/v03413/bepusdt")
postReq.Header.Set("User-Agent", "BEpusdt/"+app.Version)
postReq.Header.Set("Powered-By", "https://git.viaeon.com/admin/vupay")
postReq.Header.Set("User-Agent", "VUPAY/"+app.Version)
resp, err := client.Do(postReq)
if err != nil {
markNotifyFail(order, err.Error())
@@ -160,8 +160,8 @@ func epusdt(ctx context.Context, order model.Order) error {
return nil
}
func Bepusdt(o model.Order) {
if o.ApiType != model.OrderApiTypeEpusdt {
func Vupay(o model.Order) {
if o.ApiType != model.OrderApiTypeVupay && o.ApiType != model.OrderApiTypeVupayOrder {
return
}
@@ -169,13 +169,13 @@ func Bepusdt(o model.Order) {
var authToken = model.AuthToken()
var client = &http.Client{Timeout: time.Second * 5}
go func() {
if err := deliverBepusdtStatusUpdate(model.Db, client, authToken, o); err != nil {
log.Warn("notify BEpusdt Error:", err.Error())
if err := deliverVupayStatusUpdate(model.Db, client, authToken, o); err != nil {
log.Warn("notify VUPAY Error:", err.Error())
}
}()
}
func deliverBepusdtStatusUpdate(db *gorm.DB, client *http.Client, authToken string, o model.Order) error {
func deliverVupayStatusUpdate(db *gorm.DB, client *http.Client, authToken string, o model.Order) error {
if client == nil {
client = &http.Client{Timeout: time.Second * 5}
}
@@ -189,7 +189,7 @@ func deliverBepusdtStatusUpdate(db *gorm.DB, client *http.Client, authToken stri
return nil
}
var key = fmt.Sprintf("bepusdt_notify_%d_%s", current.Status, current.TradeId)
var key = fmt.Sprintf("vupay_notify_%d_%s", current.Status, current.TradeId)
if _, ok := cache.Get(key); ok {
return nil
}
@@ -215,7 +215,7 @@ func deliverBepusdtStatusUpdate(db *gorm.DB, client *http.Client, authToken stri
return err
}
body.Signature = utils.EpusdtSign(data, authToken)
body.Signature = utils.VupaySign(data, authToken)
jsonBody, _ = json.Marshal(body)
req, err := http.NewRequest("POST", current.NotifyUrl, strings.NewReader(string(jsonBody)))
@@ -224,7 +224,7 @@ func deliverBepusdtStatusUpdate(db *gorm.DB, client *http.Client, authToken stri
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Powered-By", "https://github.com/v03413/BEpusdt")
req.Header.Set("Powered-By", "https://git.viaeon.com/admin/vupay")
resp, err := client.Do(req)
if err != nil {
return err
+19 -19
View File
@@ -7,9 +7,9 @@ import (
"testing"
"time"
applog "github.com/v03413/bepusdt/app/log"
applog "git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/model"
"github.com/glebarez/sqlite"
"github.com/v03413/bepusdt/app/model"
"gorm.io/gorm"
)
@@ -52,25 +52,25 @@ func newWaitingOrder(notifyURL string) model.Order {
confirmedAt := now
return model.Order{
OrderId: "merchant-order-1",
TradeId: "trade-order-1",
TradeType: model.UsdtTrc20,
Fiat: "CNY",
Crypto: "USDT",
Rate: "7.00",
Amount: "1.00",
Money: "7.00",
Address: "TTestAddress1234567890",
Status: model.OrderStatusWaiting,
ApiType: model.OrderApiTypeEpusdt,
NotifyUrl: notifyURL,
ExpiredAt: now.Add(10 * time.Minute),
ConfirmedAt: &confirmedAt,
AutoTimeAt: model.AutoTimeAt{CreatedAt: (*model.Datetime)(&now), UpdatedAt: (*model.Datetime)(&now)},
OrderId: "merchant-order-1",
TradeId: "trade-order-1",
TradeType: model.UsdtTrc20,
Fiat: "CNY",
Crypto: "USDT",
Rate: "7.00",
Amount: "1.00",
Money: "7.00",
Address: "TTestAddress1234567890",
Status: model.OrderStatusWaiting,
ApiType: model.OrderApiTypeVupay,
NotifyUrl: notifyURL,
ExpiredAt: now.Add(10 * time.Minute),
ConfirmedAt: &confirmedAt,
AutoTimeAt: model.AutoTimeAt{CreatedAt: (*model.Datetime)(&now), UpdatedAt: (*model.Datetime)(&now)},
}
}
func TestDeliverBepusdtStatusUpdateDoesNotHoldDBWhileHTTPIsPending(t *testing.T) {
func TestDeliverVupayStatusUpdateDoesNotHoldDBWhileHTTPIsPending(t *testing.T) {
db := newNotifyTestDB(t)
initNotifyTestLog(t)
@@ -90,7 +90,7 @@ func TestDeliverBepusdtStatusUpdateDoesNotHoldDBWhileHTTPIsPending(t *testing.T)
errCh := make(chan error, 1)
go func() {
errCh <- deliverBepusdtStatusUpdate(db, &http.Client{Timeout: 2 * time.Second}, "test-auth-token", order)
errCh <- deliverVupayStatusUpdate(db, &http.Client{Timeout: 2 * time.Second}, "test-auth-token", order)
}()
select {
+2 -2
View File
@@ -4,9 +4,9 @@ import (
"context"
"time"
"git.viaeon.com/admin/vupay/app/conf"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/smallnest/chanx"
"github.com/v03413/bepusdt/app/conf"
"github.com/v03413/bepusdt/app/utils"
)
func plasmaInit() {
+2 -2
View File
@@ -4,9 +4,9 @@ import (
"context"
"time"
"git.viaeon.com/admin/vupay/app/conf"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/smallnest/chanx"
"github.com/v03413/bepusdt/app/conf"
"github.com/v03413/bepusdt/app/utils"
)
func polygonInit() {
+2 -2
View File
@@ -5,9 +5,9 @@ import (
"fmt"
"time"
"git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/model"
"github.com/spf13/cast"
"github.com/v03413/bepusdt/app/log"
"github.com/v03413/bepusdt/app/model"
)
func init() {
+356 -111
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"math/big"
@@ -11,17 +12,17 @@ import (
"sync"
"time"
"git.viaeon.com/admin/vupay/app/conf"
blockapi "git.viaeon.com/admin/vupay/app/core"
"git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/btcsuite/btcd/btcutil/base58"
"github.com/panjf2000/ants/v2"
"github.com/shopspring/decimal"
"github.com/smallnest/chanx"
"github.com/spf13/cast"
"github.com/tidwall/gjson"
"github.com/v03413/bepusdt/app/conf"
blockapi "github.com/v03413/bepusdt/app/core"
"github.com/v03413/bepusdt/app/log"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/app/utils"
)
// 参考文档
@@ -31,8 +32,17 @@ import (
type solana struct {
slotConfirmedOffset int
lastSlotNum int
forwardIdle bool // 因没有待支付订单而暂停了向前扫描
slotQueue *chanx.UnboundedChan[int]
client *http.Client
retryMu sync.Mutex
retryAttempts map[int]int
retryScheduled map[int]*time.Timer
retryStopped map[int]struct{}
lookbackMu sync.Mutex
lookbackNext int
lookbackEnd int
lookbackOrderIDs []int64
}
type solanaTokenOwner struct {
@@ -48,6 +58,7 @@ func init() {
Register(Task{Callback: sol.syncSlotForward, Duration: time.Second * 5})
Register(Task{Callback: sol.tradeConfirmHandle, Duration: time.Second * 5})
Register(Task{Callback: sol.lookbackSlots, Duration: time.Second * 15})
Register(Task{Callback: sol.reconcileExpiredOrders, Duration: time.Minute})
}
func newSolana() solana {
@@ -56,12 +67,25 @@ func newSolana() solana {
lastSlotNum: 0,
slotQueue: chanx.NewUnboundedChan[int](context.Background(), 30),
client: utils.NewHttpClient(),
retryAttempts: make(map[int]int),
retryScheduled: make(map[int]*time.Timer),
retryStopped: make(map[int]struct{}),
}
}
func (s *solana) syncSlotForward(ctx context.Context) {
if syncBreak(conf.Solana, s.slotQueue.Len()) {
func solanaGetBlockPayload(slot int) []byte {
return []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"getBlock","params":[%d,{"encoding":"json","maxSupportedTransactionVersion":1,"transactionDetails":"full","rewards":false}]}`, slot))
}
func (s *solana) syncSlotForward(ctx context.Context) {
if queued := s.slotQueue.Len(); syncBreak(conf.Solana, queued) {
if queued < blockQueueLimit {
s.forwardIdle = true
}
return
}
if s.pendingSlotRetryCount() >= solanaForwardPauseRetries {
return
}
@@ -97,22 +121,25 @@ func (s *solana) syncSlotForward(ctx context.Context) {
return
}
if now-s.lastSlotNum > cast.ToInt(model.GetC(model.BlockHeightMaxDiff)) { // 区块高度变化过大,强制丢块重扫
s.lastSlotNum = now
if lag := now - s.lastSlotNum; lag > cast.ToInt(model.GetC(model.BlockHeightMaxDiff)) {
if s.lastSlotNum == 0 || s.forwardIdle { // 启动或空闲后恢复扫描:直接从最新高度开始
s.lastSlotNum = now
} else { // 扫描期间落后:继续追赶,不能跳过,其中可能有付款
log.Task.Warn(fmt.Sprintf("Solana 扫描落后 %d 个 slot,继续追赶", lag))
}
}
s.forwardIdle = false
if now == s.lastSlotNum { // 区块高度没有变化
if now <= s.lastSlotNum { // 区块高度没有变化或节点返回旧高度
return
}
for n := s.lastSlotNum + 1; n <= now; n++ {
// 待扫描区块入列
// 只填充队列的可用容量;消费后由下一轮继续追赶,避免长时间故障恢复时瞬间过度扫描。
for n := s.lastSlotNum + 1; n <= now && s.slotQueue.Len() < blockQueueLimit; n++ {
s.slotQueue.In <- n
s.lastSlotNum = n
}
s.lastSlotNum = now
}
func (s *solana) slotDispatch(ctx context.Context) {
@@ -144,13 +171,13 @@ func (s *solana) slotDispatch(ctx context.Context) {
func (s *solana) slotParse(n any) {
slot := n.(int)
post := []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"getBlock","params":[%d,{"encoding":"json","maxSupportedTransactionVersion":0,"transactionDetails":"full","rewards":false}]}`, slot))
post := solanaGetBlockPayload(slot)
network := conf.Solana
conf.RecordSuccess(network, cast.ToString(slot))
resp, err := s.client.Post(model.Endpoint(conf.Solana), "application/json", bytes.NewBuffer(post))
if err != nil {
conf.RecordFailure(network)
s.scheduleSlotRetry(slot)
log.Task.Warn("slotParse Error sending request:", err)
return
@@ -159,6 +186,7 @@ func (s *solana) slotParse(n any) {
defer resp.Body.Close()
if resp.StatusCode != 200 {
conf.RecordFailure(network)
s.scheduleSlotRetry(slot)
log.Task.Warn("slotParse Error response status code:", resp.StatusCode)
return
@@ -167,65 +195,115 @@ func (s *solana) slotParse(n any) {
body, err := io.ReadAll(resp.Body)
if err != nil {
conf.RecordFailure(network)
s.slotQueue.In <- slot
s.scheduleSlotRetry(slot)
log.Task.Warn("slotParse Error reading response body:", err)
return
}
timestamp := time.Unix(gjson.GetBytes(body, "result.blockTime").Int(), 0)
result, err := validateSolanaBlockResponse(body)
if errors.Is(err, errSolanaBlockCleanedUp) { // 节点已清理该 slot,重试也拿不到;放弃,不暂停向前扫描
conf.RecordFailure(network)
s.stopSlotRetry(slot)
log.Task.Error(fmt.Sprintf("Solana slot %d 已被节点清理,无法扫描,该 slot 内的付款需要人工核对:%s", slot, err))
for _, trans := range gjson.GetBytes(body, "result.transactions").Array() {
hash := trans.Get("transaction.signatures.0").String()
return
}
if err != nil {
conf.RecordFailure(network)
s.scheduleSlotRetry(slot)
log.Task.Warn("slotParse Error JSON-RPC response:", err)
// 解析账号索引
accountKeys := make([]string, 0)
for _, key := range trans.Get("transaction.message.accountKeys").Array() {
return
}
conf.RecordSuccess(network, cast.ToString(slot))
s.resetSlotRetry(slot)
if result.Type == gjson.Null {
log.Task.Info(fmt.Sprintf("区块已跳过(Solana) %d 成功率:%s", slot, conf.GetSuccessRate(network)))
return
}
timestamp := time.Unix(result.Get("blockTime").Int(), 0)
for _, trans := range result.Get("transactions").Array() {
if transfers := s.parseTransaction(trans, slot, timestamp); len(transfers) > 0 {
transferQueue.In <- transfers
}
}
log.Task.Info(fmt.Sprintf("区块扫描完成(Solana) %d 成功率:%s", slot, conf.GetSuccessRate(network)))
}
// parseTransaction 解析单笔交易中的 USDT/USDC 转账;getBlock 返回的交易项与 getTransaction 的结果结构相同,都可以传入
func (s *solana) parseTransaction(trans gjson.Result, slot int, timestamp time.Time) []transfer {
if !solanaTxSucceeded(trans.Get("meta.err")) {
return nil
}
hash := trans.Get("transaction.signatures.0").String()
// 解析账号索引
accountKeys := make([]string, 0)
for _, key := range trans.Get("transaction.message.accountKeys").Array() {
accountKeys = append(accountKeys, key.String())
}
for _, v := range []string{"readonly", "writable"} {
for _, key := range trans.Get("meta.loadedAddresses." + v).Array() {
accountKeys = append(accountKeys, key.String())
}
for _, v := range []string{"readonly", "writable"} {
for _, key := range trans.Get("meta.loadedAddresses." + v).Array() {
accountKeys = append(accountKeys, key.String())
}
// 查找SPL Token索引
splTokenIndex := int64(-1)
for i, v := range accountKeys {
if v == conf.SolSplToken {
splTokenIndex = int64(i)
break
}
}
// SPL Token的Mint地址,即不包含 Token 交易信息
if splTokenIndex == -1 {
return nil
}
// 解析 Token 账户 【Token Wallet => Owner Wallet】
tokenAccountMap := make(map[string]solanaTokenOwner)
for _, v := range []string{"postTokenBalances", "preTokenBalances"} {
for _, itm := range trans.Get("meta." + v).Array() {
tradeType, ok := model.GetContractTrade(itm.Get("mint").String())
if !ok || itm.Get("programId").String() != conf.SolSplToken {
continue
}
tokenAccountMap[accountKeys[itm.Get("accountIndex").Int()]] = solanaTokenOwner{
TradeType: tradeType,
Address: itm.Get("owner").String(),
}
}
}
// 查找SPL Token索引
splTokenIndex := int64(-1)
for i, v := range accountKeys {
if v == conf.SolSplToken {
splTokenIndex = int64(i)
transArr := make([]transfer, 0)
break
}
}
// SPL Token的Mint地址,即不包含 Token 交易信息
if splTokenIndex == -1 {
// 解析外部指令
for _, instr := range trans.Get("transaction.message.instructions").Array() {
if instr.Get("programIdIndex").Int() != splTokenIndex {
continue
}
// 解析 Token 账户 【Token Wallet => Owner Wallet】
tokenAccountMap := make(map[string]solanaTokenOwner)
for _, v := range []string{"postTokenBalances", "preTokenBalances"} {
for _, itm := range trans.Get("meta." + v).Array() {
tradeType, ok := model.GetContractTrade(itm.Get("mint").String())
if !ok || itm.Get("programId").String() != conf.SolSplToken {
transArr = append(transArr, s.parseTransfer(instr, accountKeys, tokenAccountMap))
}
continue
}
tokenAccountMap[accountKeys[itm.Get("accountIndex").Int()]] = solanaTokenOwner{
TradeType: tradeType,
Address: itm.Get("owner").String(),
}
}
}
transArr := make([]transfer, 0)
// 解析外部指令
for _, instr := range trans.Get("transaction.message.instructions").Array() {
// 解析内部指令
for _, itm := range trans.Get("meta.innerInstructions").Array() {
for _, instr := range itm.Get("instructions").Array() {
if instr.Get("programIdIndex").Int() != splTokenIndex {
continue
@@ -233,41 +311,169 @@ func (s *solana) slotParse(n any) {
transArr = append(transArr, s.parseTransfer(instr, accountKeys, tokenAccountMap))
}
// 解析内部指令
for _, itm := range trans.Get("meta.innerInstructions").Array() {
for _, instr := range itm.Get("instructions").Array() {
if instr.Get("programIdIndex").Int() != splTokenIndex {
continue
}
transArr = append(transArr, s.parseTransfer(instr, accountKeys, tokenAccountMap))
}
}
// 过滤无关交易
result := make([]transfer, 0)
for _, t := range transArr {
if t.FromAddress == "" || t.RecvAddress == "" || t.Amount.IsZero() {
continue
}
t.TxHash = hash
t.Network = conf.Solana
t.BlockNum = slot
t.Timestamp = timestamp
result = append(result, t)
}
if len(result) > 0 {
transferQueue.In <- result
}
}
log.Task.Info(fmt.Sprintf("区块扫描完成(Solana) %d 成功率:%s", slot, conf.GetSuccessRate(network)))
// 过滤无关交易
result := make([]transfer, 0)
for _, t := range transArr {
if t.FromAddress == "" || t.RecvAddress == "" || t.Amount.IsZero() {
continue
}
t.TxHash = hash
t.Network = conf.Solana
t.BlockNum = slot
t.Timestamp = timestamp
result = append(result, t)
}
return result
}
// 执行失败的交易同样会被打包进区块,指令和代币余额也照常保留,但转账已经回滚;只有 err 为 null 才算执行成功
func solanaTxSucceeded(err gjson.Result) bool {
return err.Exists() && err.Type == gjson.Null
}
// getSignatureStatuses 对执行失败的交易同样返回 finalized,必须同时检查 err
func solanaSignatureFinalized(status gjson.Result) bool {
return status.Get("confirmationStatus").String() == "finalized" && solanaTxSucceeded(status.Get("err"))
}
// Solana JSON-RPC 错误码,参考 https://github.com/anza-xyz/agave/blob/master/rpc-client-api/src/custom_error.rs
const (
solanaErrBlockCleanedUp = -32001
solanaErrSlotSkipped = -32007
solanaErrLongTermStorageSlotSkipped = -32009
)
// 节点只保留最近一段时间的区块,更早的 slot 返回 -32001,换一个时间重试也不会有
var errSolanaBlockCleanedUp = errors.New("block cleaned up")
func validateSolanaBlockResponse(body []byte) (gjson.Result, error) {
if !gjson.ValidBytes(body) {
return gjson.Result{}, fmt.Errorf("invalid JSON response")
}
data := gjson.ParseBytes(body)
if rpcErr := data.Get("error"); rpcErr.Exists() {
switch rpcErr.Get("code").Int() {
case solanaErrSlotSkipped, solanaErrLongTermStorageSlotSkipped: // 被跳过的 slot 没有区块,按空 slot 处理
return gjson.Result{Type: gjson.Null}, nil
case solanaErrBlockCleanedUp:
return gjson.Result{}, fmt.Errorf("%w: %s", errSolanaBlockCleanedUp, rpcErr.Raw)
}
return gjson.Result{}, fmt.Errorf("RPC error: %s", rpcErr.Raw)
}
result := data.Get("result")
if !result.Exists() {
return gjson.Result{}, fmt.Errorf("missing result")
}
if result.Type != gjson.Null && !result.Get("transactions").Exists() {
return gjson.Result{}, fmt.Errorf("missing result.transactions")
}
return result, nil
}
func (s *solana) scheduleSlotRetry(slot int) {
s.retryMu.Lock()
if _, stopped := s.retryStopped[slot]; stopped {
s.retryMu.Unlock()
return
}
if _, ok := s.retryScheduled[slot]; ok {
s.retryMu.Unlock()
return
}
attempt := s.retryAttempts[slot] + 1
if attempt > solanaSlotMaxRetries { // 放弃该 slot,否则向前扫描会一直暂停
delete(s.retryAttempts, slot)
s.retryMu.Unlock()
log.Task.Error(fmt.Sprintf("Solana slot %d 连续 %d 次扫描失败,已放弃,该 slot 内的付款需要人工核对", slot, solanaSlotMaxRetries))
return
}
s.retryAttempts[slot] = attempt
// 待重试的 slot 数量有限,到期直接入队;不再因队列堆积而延后,否则堆积会被计为失败次数
var timer *time.Timer
timer = time.AfterFunc(solanaRetryDelay(attempt), func() {
s.retryMu.Lock()
if s.retryScheduled[slot] != timer {
s.retryMu.Unlock()
return
}
delete(s.retryScheduled, slot)
s.retryMu.Unlock()
s.slotQueue.In <- slot
})
s.retryScheduled[slot] = timer
s.retryMu.Unlock()
}
func (s *solana) stopSlotRetry(slot int) {
s.retryMu.Lock()
delete(s.retryAttempts, slot)
if timer, ok := s.retryScheduled[slot]; ok {
timer.Stop()
delete(s.retryScheduled, slot)
}
s.retryStopped[slot] = struct{}{}
s.retryMu.Unlock()
// 防止同一 slot 的并发请求在终态响应之后重新建立重试;并发请求结束后无需长期保留。
time.AfterFunc(time.Minute, func() {
s.retryMu.Lock()
delete(s.retryStopped, slot)
s.retryMu.Unlock()
})
}
func (s *solana) resetSlotRetry(slot int) {
s.retryMu.Lock()
defer s.retryMu.Unlock()
delete(s.retryAttempts, slot)
if timer, ok := s.retryScheduled[slot]; ok {
timer.Stop()
delete(s.retryScheduled, slot)
}
}
func (s *solana) pendingSlotRetryCount() int {
s.retryMu.Lock()
defer s.retryMu.Unlock()
return len(s.retryAttempts)
}
// 单个 slot 最多重试 10 次,按 solanaRetryDelay 约 7 分钟
const solanaSlotMaxRetries = 10
// 待重试的 slot 达到这个数量,说明节点整体故障,暂停向前扫描,避免新 slot 不断进入重试;
// 个别 slot 失败时继续向前扫描,否则一个 slot 的重试会让之后的付款最多等约 7 分钟
const solanaForwardPauseRetries = 10
func solanaRetryDelay(attempt int) time.Duration {
delays := [...]time.Duration{2 * time.Second, 5 * time.Second, 15 * time.Second, 30 * time.Second, time.Minute}
if attempt < 1 {
attempt = 1
}
if attempt > len(delays) {
attempt = len(delays)
}
return delays[attempt-1]
}
func (s *solana) parseTransfer(instr gjson.Result, accountKeys []string, tokenAccountMap map[string]solanaTokenOwner) transfer {
@@ -325,15 +531,6 @@ func (s *solana) tradeConfirmHandle(ctx context.Context) {
var wg sync.WaitGroup
var handle = func(o model.Order) {
if model.GetC(model.BlockOffsetConfirm) == "1" {
if s.lastSlotNum == 0 {
return
}
if s.lastSlotNum-o.RefBlockNum < s.slotConfirmedOffset {
return
}
}
post := []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"getSignatureStatuses","params":[["%s"],{"searchTransactionHistory":true}]}`, o.RefHash))
req, _ := http.NewRequestWithContext(ctx, "POST", model.Endpoint(conf.Solana), bytes.NewBuffer(post))
resp, err := s.client.Do(req)
@@ -365,7 +562,13 @@ func (s *solana) tradeConfirmHandle(ctx context.Context) {
return
}
if data.Get("result.value.0.confirmationStatus").String() == "finalized" {
// 用同一响应里节点当前的 slot 计算确认数,不依赖向前扫描进度:扫描在没有待支付订单时会暂停,重启后为 0
if model.GetC(model.BlockOffsetConfirm) == "1" && data.Get("result.context.slot").Int()-int64(o.RefBlockNum) < int64(s.slotConfirmedOffset) {
return
}
if solanaSignatureFinalized(data.Get("result.value.0")) {
markFinalConfirmed(o)
}
@@ -384,26 +587,68 @@ func (s *solana) tradeConfirmHandle(ctx context.Context) {
}
func (s *solana) lookbackSlots(ctx context.Context) {
s.lookbackMu.Lock()
defer s.lookbackMu.Unlock()
// 回溯到一半时订单已支付、取消,或已超出回溯时间,剩余区间不再需要。扫描空闲时这里不会执行到下面,
// 不清空的话进度会一直保留,下一笔订单到来时接着扫这段旧 slot,节点可能早已清理
if s.lookbackNext != 0 {
pending, err := lookbackOrdersPending(s.lookbackOrderIDs)
if err != nil { // 查询失败不等于订单已结束,保留进度,下一轮再判断
log.Task.Warn("Solana 回溯订单查询失败,稍后重试:", err)
return
}
if !pending {
log.Task.Info(fmt.Sprintf("Solana 回溯的订单已不需要回溯,丢弃剩余回溯区间 %d-%d", s.lookbackNext, s.lookbackEnd))
s.resetLookback()
}
}
if syncBreak(conf.Solana, s.slotQueue.Len()) {
return
}
startAt, endAt, ok := getLookbackUnix(conf.Solana)
if !ok {
return
if s.lookbackNext == 0 {
startAt, endAt, orderIDs, ok := pendingLookbackUnix(conf.Solana)
if !ok {
return
}
start, end := blockapi.New().GetBoundaryHeights(startAt, endAt, conf.Solana)
if !validSolanaLookbackRange(start, end) {
log.Task.Warn("Solana 回溯区块范围无效,稍后重试:", start, "-", end)
return
}
s.lookbackNext = int(start)
s.lookbackEnd = int(end)
s.lookbackOrderIDs = orderIDs
}
start, end := blockapi.New().GetBoundaryHeights(startAt, endAt, conf.Solana)
for i := int(start); i <= int(end); i++ {
for s.lookbackNext <= s.lookbackEnd && s.slotQueue.Len() < blockQueueLimit {
select {
case <-ctx.Done():
return
default:
}
if syncBreak(conf.Solana, s.slotQueue.Len()) {
return
}
s.slotQueue.In <- i
time.Sleep(time.Millisecond * 200)
s.slotQueue.In <- s.lookbackNext
s.lookbackNext++
}
if s.lookbackNext > s.lookbackEnd {
markLookbackDone(s.lookbackOrderIDs)
s.resetLookback()
}
}
func (s *solana) resetLookback() {
s.lookbackNext = 0
s.lookbackEnd = 0
s.lookbackOrderIDs = nil
}
func validSolanaLookbackRange(start, end int64) bool {
return start > 0 && end >= start
}
+65
View File
@@ -0,0 +1,65 @@
package task
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"git.viaeon.com/admin/vupay/app/model"
)
func TestSolanaConfirmOffsetUsesRPCSlot(t *testing.T) {
tests := []struct {
name string
confirmations int
want int
}{
{name: "enough confirmations", confirmations: 100, want: model.OrderStatusSuccess},
{name: "waiting for confirmations", confirmations: 25, want: model.OrderStatusConfirming},
}
const slot = 451914288
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/notify" {
_, _ = w.Write([]byte("ok"))
return
}
// 主网 getSignatureStatuses 对该交易的真实返回,只改 context.slot
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":{"context":{"slot":%d},"value":[{"confirmationStatus":"finalized","confirmations":null,"err":null,"slot":%d,"status":{"Ok":null}}]},"id":1}`, slot+tt.confirmations, slot)
}))
defer srv.Close()
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL, model.BlockOffsetConfirm: "1"})
order := createTestOrder(t, model.Order{
OrderId: "merchant-order-1",
TradeId: "trade-order-1",
TradeType: model.UsdcSolana,
Rate: "7.00",
Amount: "390.990618",
Money: "2736.93",
Address: "F7p3dFrjRTbtRp8FRF6qHLomXbKRBzpvBLjtQcfcgmNe",
Status: model.OrderStatusConfirming,
ApiType: model.OrderApiTypeVupay,
NotifyUrl: srv.URL + "/notify",
RefHash: "DohbsAfxAerDTAX9XS1b9jXY5XYMXQsCnyY3qu42eEEcTeJ6UzMbFs3JTdY14QgNKQPdy6yezdgbqLbnRVj6YB6",
RefBlockNum: slot,
ExpiredAt: time.Now().Add(10 * time.Minute),
}, time.Now().Add(-time.Minute))
s := newSolana() // lastSlotNum 为 0,相当于重启后或扫描已暂停
s.tradeConfirmHandle(t.Context())
if got := getTestOrder(t, order.TradeId).Status; got != tt.want {
t.Fatalf("order status = %d, want %d", got, tt.want)
}
if tt.want == model.OrderStatusSuccess {
waitOrderNotified(t, order.TradeId)
}
})
}
}
+163
View File
@@ -0,0 +1,163 @@
package task
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
"git.viaeon.com/admin/vupay/app/model"
"github.com/tidwall/gjson"
)
func scanSolanaTestBlock(t *testing.T, block []byte) []transfer {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write(block)
}))
defer srv.Close()
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL})
s := newSolana()
s.slotParse(solanaFixtureSlot(block))
return drainTransferQueue()
}
func TestSolanaTxSucceeded(t *testing.T) {
tests := []struct {
name string
tx string
want bool
}{
{name: "succeeded", tx: `{"meta":{"err":null}}`, want: true},
{name: "instruction error", tx: `{"meta":{"err":{"InstructionError":[1,{"Custom":6001}]}}}`},
{name: "missing err", tx: `{"meta":{}}`},
{name: "missing meta", tx: `{"meta":null}`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := solanaTxSucceeded(gjson.Get(tt.tx, "meta.err")); got != tt.want {
t.Fatalf("solanaTxSucceeded = %v, want %v", got, tt.want)
}
})
}
}
func TestSolanaSlotParseSkipsFailedTransactions(t *testing.T) {
tests := []struct {
fixture string
// 把 meta.err 改为 null 后应解析出的转账数,证明没有转账只是因为交易失败
transfersIfSucceeded int
}{
{fixture: "failed_v1_transfer.json", transfersIfSucceeded: 3},
{fixture: "failed_v0_inner_transfer.json", transfersIfSucceeded: 1},
}
for _, tt := range tests {
t.Run(tt.fixture, func(t *testing.T) {
block := readSolanaFixture(t, tt.fixture)
if got := scanSolanaTestBlock(t, block); len(got) != 0 {
t.Fatalf("failed transaction produced %d transfers: %+v", len(got), got)
}
errRaw := gjson.GetBytes(block, "result.transactions.0.meta.err").Raw
succeeded := bytes.Replace(block, []byte(`"err":`+errRaw), []byte(`"err":null`), 1)
if bytes.Equal(succeeded, block) {
t.Fatalf("fixture has no meta.err to clear")
}
if got := scanSolanaTestBlock(t, succeeded); len(got) != tt.transfersIfSucceeded {
t.Fatalf("transfers = %d, want %d", len(got), tt.transfersIfSucceeded)
}
})
}
}
func TestSolanaSlotParseKeepsSucceededTransactions(t *testing.T) {
got := scanSolanaTestBlock(t, readSolanaFixture(t, "success_v0_inner_transfer.json"))
if len(got) != 1 {
t.Fatalf("transfers = %d, want 1", len(got))
}
tr := got[0]
if tr.TxHash != "DohbsAfxAerDTAX9XS1b9jXY5XYMXQsCnyY3qu42eEEcTeJ6UzMbFs3JTdY14QgNKQPdy6yezdgbqLbnRVj6YB6" ||
tr.TradeType != model.UsdcSolana ||
tr.RecvAddress != "F7p3dFrjRTbtRp8FRF6qHLomXbKRBzpvBLjtQcfcgmNe" ||
tr.Amount.String() != "390.990618" {
t.Fatalf("unexpected transfer: %+v", tr)
}
}
// 主网 getSignatureStatuses 的真实返回
const (
solanaFailedSignatureStatus = `{"confirmationStatus":"finalized","confirmations":null,"err":{"InstructionError":[1,{"Custom":6001}]},"slot":458281527,"status":{"Err":{"InstructionError":[1,{"Custom":6001}]}}}`
solanaSucceededSignatureStatus = `{"confirmationStatus":"finalized","confirmations":null,"err":null,"slot":451914288,"status":{"Ok":null}}`
)
func TestSolanaSignatureFinalized(t *testing.T) {
tests := []struct {
name string
status string
want bool
}{
{name: "finalized", status: solanaSucceededSignatureStatus, want: true},
{name: "finalized but failed", status: solanaFailedSignatureStatus},
{name: "confirmed", status: `{"confirmationStatus":"confirmed","confirmations":12,"err":null,"slot":451914288,"status":{"Ok":null}}`},
{name: "not found", status: `null`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := solanaSignatureFinalized(gjson.Parse(tt.status)); got != tt.want {
t.Fatalf("solanaSignatureFinalized = %v, want %v", got, tt.want)
}
})
}
}
func TestSolanaTradeConfirmIgnoresFailedTransaction(t *testing.T) {
var notified atomic.Bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/notify" {
notified.Store(true)
_, _ = w.Write([]byte("ok"))
return
}
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":{"context":{"slot":458281967},"value":[%s]},"id":1}`, solanaFailedSignatureStatus)
}))
defer srv.Close()
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL})
order := createTestOrder(t, model.Order{
OrderId: "merchant-order-1",
TradeId: "trade-order-1",
TradeType: model.UsdcSolana,
Rate: "7.00",
Amount: "225.966818",
Money: "1581.77",
Address: "GpsvqTPP7triXkqH8mVtXEM6at9DJ41UHy5dYPTFe16H",
Status: model.OrderStatusConfirming,
ApiType: model.OrderApiTypeVupay,
NotifyUrl: srv.URL + "/notify",
RefHash: "53bZ2UeqMGryYjbjKgB2nAo8umAMsPTP4dzBhR94SdV7f4YaxDvWqEdL5WQ46JSHsmLph3hBmEdHzTMdnYKMsbRz",
RefBlockNum: 458281527,
ExpiredAt: time.Now().Add(10 * time.Minute),
}, time.Now().Add(-time.Minute))
s := newSolana()
s.tradeConfirmHandle(t.Context())
if got := getTestOrder(t, order.TradeId); got.Status != model.OrderStatusConfirming {
t.Fatalf("order status = %d after failed transaction, want confirming", got.Status)
}
time.Sleep(200 * time.Millisecond)
if notified.Load() {
t.Fatalf("callback sent for failed transaction")
}
}
+72
View File
@@ -0,0 +1,72 @@
package task
import (
"fmt"
"sync/atomic"
"testing"
"time"
"git.viaeon.com/admin/vupay/app/model"
)
// 模拟 n 个 slot 正在等待重试
func (s *solana) setPendingSlotRetries(first, n int) {
s.retryMu.Lock()
defer s.retryMu.Unlock()
for slot := first; slot < first+n; slot++ {
s.retryAttempts[slot] = 1
}
}
// 一个 slot 在等待重试时,向前扫描照常推进,之后的付款不用等它重试完
func TestSolanaForwardContinuesWhileFewSlotsRetry(t *testing.T) {
var head atomic.Int64
srv := newSolanaSlotTestServer(t, &head)
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL, model.BlockHeightMaxDiff: fmt.Sprint(solanaTestMaxDiff)})
createSolanaWaitingOrder(t)
const last = 458000000
s := newSolana()
s.lastSlotNum = last
s.setPendingSlotRetries(last-9, solanaForwardPauseRetries-1)
head.Store(last + 5)
s.syncSlotForward(t.Context())
if s.lastSlotNum != last+5 {
t.Fatalf("lastSlotNum = %d, want %d: forward sync paused by one slot retry", s.lastSlotNum, last+5)
}
select {
case got := <-s.slotQueue.Out:
if got != last+1 {
t.Fatalf("first queued slot = %d, want %d", got, last+1)
}
case <-time.After(time.Second):
t.Fatalf("no slot queued while one slot retries")
}
}
// 很多 slot 同时等待重试,说明节点整体故障,暂停向前扫描
func TestSolanaForwardPausesWhileManySlotsRetry(t *testing.T) {
var head atomic.Int64
srv := newSolanaSlotTestServer(t, &head)
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL, model.BlockHeightMaxDiff: fmt.Sprint(solanaTestMaxDiff)})
createSolanaWaitingOrder(t)
const last = 458000000
s := newSolana()
s.lastSlotNum = last
s.setPendingSlotRetries(last-solanaForwardPauseRetries, solanaForwardPauseRetries)
head.Store(last + 5)
s.syncSlotForward(t.Context())
if s.lastSlotNum != last || s.slotQueue.Len() != 0 {
t.Fatalf("lastSlotNum = %d, queued = %d; want forward sync paused at %d", s.lastSlotNum, s.slotQueue.Len(), last)
}
s.resetSlotRetry(last - solanaForwardPauseRetries)
s.syncSlotForward(t.Context())
if s.lastSlotNum != last+5 {
t.Fatalf("lastSlotNum = %d after retries dropped below threshold, want %d", s.lastSlotNum, last+5)
}
}
+103
View File
@@ -0,0 +1,103 @@
package task
import (
"fmt"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
"git.viaeon.com/admin/vupay/app/model"
)
func newSolanaSlotTestServer(t *testing.T, head *atomic.Int64) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":%d,"id":1}`, head.Load())
}))
t.Cleanup(srv.Close)
return srv
}
func createSolanaWaitingOrder(t *testing.T) {
t.Helper()
createTestOrder(t, model.Order{
OrderId: "merchant-order-1",
TradeId: "trade-order-1",
TradeType: model.UsdcSolana,
Rate: "7.00",
Amount: "1.23",
Money: "8.61",
Address: "GpsvqTPP7triXkqH8mVtXEM6at9DJ41UHy5dYPTFe16H",
Status: model.OrderStatusWaiting,
ApiType: model.OrderApiTypeVupay,
ExpiredAt: time.Now().Add(10 * time.Minute),
}, time.Now().Add(-time.Minute))
}
// 落后阈值设为 10,用 20 个 slot 的落后量验证,队列不会超过 chanx 的初始容量
const solanaTestMaxDiff = 10
func TestSolanaForwardCatchesUpWhileOrdersActive(t *testing.T) {
var head atomic.Int64
srv := newSolanaSlotTestServer(t, &head)
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL, model.BlockHeightMaxDiff: fmt.Sprint(solanaTestMaxDiff)})
createSolanaWaitingOrder(t)
const last = 458000000
s := newSolana()
s.lastSlotNum = last
head.Store(last + 2*solanaTestMaxDiff)
s.syncSlotForward(t.Context())
if s.lastSlotNum != last+2*solanaTestMaxDiff {
t.Fatalf("lastSlotNum = %d, want %d", s.lastSlotNum, last+2*solanaTestMaxDiff)
}
select {
case got := <-s.slotQueue.Out:
if got != last+1 {
t.Fatalf("first queued slot = %d, want %d: slots were skipped", got, last+1)
}
case <-time.After(time.Second):
t.Fatalf("no slot queued: slots %d-%d were skipped", last+1, last+2*solanaTestMaxDiff)
}
}
func TestSolanaForwardSkipsAfterIdle(t *testing.T) {
var head atomic.Int64
srv := newSolanaSlotTestServer(t, &head)
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL, model.BlockHeightMaxDiff: fmt.Sprint(solanaTestMaxDiff)})
const last = 458000000
s := newSolana()
s.lastSlotNum = last
head.Store(last + 2*solanaTestMaxDiff)
s.syncSlotForward(t.Context()) // 没有订单,暂停扫描
if s.lastSlotNum != last {
t.Fatalf("lastSlotNum = %d while idle, want %d", s.lastSlotNum, last)
}
createSolanaWaitingOrder(t)
s.syncSlotForward(t.Context())
if s.lastSlotNum != last+2*solanaTestMaxDiff || s.slotQueue.Len() != 0 {
t.Fatalf("lastSlotNum = %d, queued = %d; want a jump to %d after idle", s.lastSlotNum, s.slotQueue.Len(), last+2*solanaTestMaxDiff)
}
}
func TestSolanaForwardSkipsOnStartup(t *testing.T) {
var head atomic.Int64
srv := newSolanaSlotTestServer(t, &head)
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL, model.BlockHeightMaxDiff: fmt.Sprint(solanaTestMaxDiff)})
createSolanaWaitingOrder(t)
s := newSolana()
head.Store(458000000)
s.syncSlotForward(t.Context())
if s.lastSlotNum != 458000000 || s.slotQueue.Len() != 0 {
t.Fatalf("lastSlotNum = %d, queued = %d; want a jump to the latest slot on startup", s.lastSlotNum, s.slotQueue.Len())
}
}
+101
View File
@@ -0,0 +1,101 @@
package task
import (
"testing"
"time"
"git.viaeon.com/admin/vupay/app/model"
)
func createSolanaLookbackOrder(t *testing.T, tradeID string, status int) model.Order {
t.Helper()
return createTestOrder(t, model.Order{
OrderId: "merchant-" + tradeID,
TradeId: tradeID,
TradeType: model.UsdcSolana,
Rate: "7.00",
Amount: "1.23",
Money: "8.61",
Address: "GpsvqTPP7triXkqH8mVtXEM6at9DJ41UHy5dYPTFe16H",
Status: status,
ApiType: model.OrderApiTypeVupay,
ExpiredAt: time.Now().Add(10 * time.Minute),
}, time.Now().Add(-time.Minute))
}
// 上一笔订单回溯到一半就取消了;一周后新订单到来时,不能接着扫上一笔订单留下的旧 slot
func TestSolanaLookbackDropsRangeOfFinishedOrders(t *testing.T) {
initTaskTestEnv(t, nil)
lookbackDone.Clear()
canceled := createSolanaLookbackOrder(t, "lookback-canceled", model.OrderStatusCanceled)
waiting := createSolanaLookbackOrder(t, "lookback-waiting", model.OrderStatusWaiting)
lookbackDone.Store(waiting.ID, struct{}{}) // 新订单的回溯不在本测试范围,避免请求区块高度接口
s := newSolana()
s.lookbackNext, s.lookbackEnd, s.lookbackOrderIDs = 459552217, 459552221, []int64{canceled.ID}
s.lookbackSlots(t.Context())
select {
case slot := <-s.slotQueue.Out:
t.Fatalf("queued slot %d from the range of a canceled order", slot)
case <-time.After(200 * time.Millisecond):
}
if s.lookbackNext != 0 || s.lookbackEnd != 0 || s.lookbackOrderIDs != nil {
t.Fatalf("lookback progress kept: next = %d, end = %d, orders = %v", s.lookbackNext, s.lookbackEnd, s.lookbackOrderIDs)
}
}
// 查询订单失败时不能当作订单已结束,保留进度,下一轮再判断
func TestSolanaLookbackKeepsRangeOnDatabaseError(t *testing.T) {
initTaskTestEnv(t, nil)
lookbackDone.Clear()
waiting := createSolanaLookbackOrder(t, "lookback-waiting", model.OrderStatusWaiting)
const start, end = 462296900, 462296904
s := newSolana()
s.lookbackNext, s.lookbackEnd, s.lookbackOrderIDs = start, end, []int64{waiting.ID}
db, err := model.Db.DB()
if err != nil {
t.Fatalf("get db: %v", err)
}
if err := db.Close(); err != nil {
t.Fatalf("close db: %v", err)
}
s.lookbackSlots(t.Context())
if s.lookbackNext != start || s.lookbackEnd != end {
t.Fatalf("lookback progress dropped on a database error: next = %d, end = %d", s.lookbackNext, s.lookbackEnd)
}
}
func TestSolanaLookbackResumesRangeOfPendingOrders(t *testing.T) {
initTaskTestEnv(t, nil)
lookbackDone.Clear()
waiting := createSolanaLookbackOrder(t, "lookback-waiting", model.OrderStatusWaiting)
const start, end = 462296900, 462296904
s := newSolana()
s.lookbackNext, s.lookbackEnd, s.lookbackOrderIDs = start, end, []int64{waiting.ID}
s.lookbackSlots(t.Context())
for want := start; want <= end; want++ {
select {
case got := <-s.slotQueue.Out:
if got != want {
t.Fatalf("queued slot = %d, want %d", got, want)
}
case <-time.After(time.Second):
t.Fatalf("slot %d not queued", want)
}
}
if s.lookbackNext != 0 {
t.Fatalf("lookbackNext = %d after the range was queued, want 0", s.lookbackNext)
}
if _, done := lookbackDone.Load(waiting.ID); !done {
t.Fatalf("order %d not marked as looked back", waiting.ID)
}
}
+65
View File
@@ -0,0 +1,65 @@
package task
import (
"testing"
"time"
"git.viaeon.com/admin/vupay/app/conf"
"git.viaeon.com/admin/vupay/app/model"
"github.com/tidwall/gjson"
)
// 预期结果由独立的解码脚本从主网交易得出:只统计两端代币账户都在 token balances 中的 USDT/USDC transfer、transferChecked
func TestSolanaParseTransactionMainnetFixtures(t *testing.T) {
type want struct {
from, to, amount string
tradeType model.TradeType
}
tests := []struct {
fixture string
want []want
}{
{fixture: "success_legacy_transfer.json", want: []want{
{from: "218mr4Lpgn5nFX4vBmgSDUSj4uvtTnx5jmwC5cZFHfSn", to: "Mdv6q9cauwiPLTn43SXuLtitAsDbNHtT3sFbknNvr6b", amount: "5.36", tradeType: model.UsdtSolana},
}},
{fixture: "success_legacy_transfer_checked.json", want: []want{
{from: "8HrXbX3MdyEpgwiA1MkqR5max8gugvpX7ay4DFDd53aH", to: "8tjDqRuhYN1PZcZkwLy9sRTUb1hbJNyijJeAESxG5zxv", amount: "0.0024", tradeType: model.UsdcSolana},
}},
{fixture: "success_transfer_creates_token_account.json", want: []want{ // 同一笔交易里先创建收款方代币账户(非 ATA)
{from: "Bj7j6d8sybC7rLTmGMCB4K4p6yC1v4RQvdAptDzTiURv", to: "8YKSSNbwE72ftktZS3V1NXvd8ekHzVfLk7GkBsvy8E2i", amount: "2560.021449", tradeType: model.UsdcSolana},
}},
{fixture: "success_v0_inner_transfer.json", want: []want{ // 地址查找表 + 内部指令
{from: "GMCJvYGf5Ex2ARiMquaBDqU6iKM8uiEQkB8jCnoNfHpC", to: "F7p3dFrjRTbtRp8FRF6qHLomXbKRBzpvBLjtQcfcgmNe", amount: "390.990618", tradeType: model.UsdcSolana},
}},
{fixture: "success_v1_transfer.json", want: []want{
{from: "2LAYGGSiF3QfyQEG1Gb3UGAsuzvD21zjHEW88v2XZ7cW", to: "FDRRDey8oQeRMgM5msEzy4yayKccuN2k47UdSnNNVVGQ", amount: "103.347262", tradeType: model.UsdcSolana},
{from: "FDRRDey8oQeRMgM5msEzy4yayKccuN2k47UdSnNNVVGQ", to: "6EVgUURuvprazVdpd717E9uqruHcqRPbhRKDm5Czdidu", amount: "103.347262", tradeType: model.UsdcSolana},
}},
{fixture: "failed_v1_transfer.json"},
{fixture: "failed_v0_inner_transfer.json"},
}
s := &solana{}
for _, tt := range tests {
t.Run(tt.fixture, func(t *testing.T) {
block := readSolanaFixture(t, tt.fixture)
trans := gjson.GetBytes(block, "result.transactions.0")
slot := solanaFixtureSlot(block)
timestamp := time.Unix(gjson.GetBytes(block, "result.blockTime").Int(), 0)
got := s.parseTransaction(trans, slot, timestamp)
if len(got) != len(tt.want) {
t.Fatalf("transfers = %d, want %d: %+v", len(got), len(tt.want), got)
}
for i, w := range tt.want {
g := got[i]
if g.FromAddress != w.from || g.RecvAddress != w.to || g.Amount.String() != w.amount || g.TradeType != w.tradeType {
t.Fatalf("transfer %d = %s -> %s %s %s, want %s -> %s %s %s", i, g.FromAddress, g.RecvAddress, g.Amount, g.TradeType, w.from, w.to, w.amount, w.tradeType)
}
if g.TxHash != trans.Get("transaction.signatures.0").String() || g.Network != conf.Solana || g.BlockNum != slot || !g.Timestamp.Equal(timestamp) {
t.Fatalf("transfer %d metadata = %s %s %d %s", i, g.TxHash, g.Network, g.BlockNum, g.Timestamp)
}
}
})
}
}
+98
View File
@@ -0,0 +1,98 @@
package task
import (
"errors"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"git.viaeon.com/admin/vupay/app/model"
)
const solanaBlockCleanedUpResponse = `{"jsonrpc":"2.0","error":{"code":-32001,"message":"Block 459552217 cleaned up, does not exist on node. First available block: 461715420"},"id":1}`
func TestValidateSolanaBlockResponseCleanedUp(t *testing.T) {
if _, err := validateSolanaBlockResponse([]byte(solanaBlockCleanedUpResponse)); !errors.Is(err, errSolanaBlockCleanedUp) {
t.Fatalf("error = %v, want errSolanaBlockCleanedUp", err)
}
}
// 并发处理同一个 slot 时,较晚返回的普通错误不能在 BlockCleanedUp 已经终止后重新建立重试
func TestSolanaSlotParseCleanedUpWinsConcurrentFailure(t *testing.T) {
firstStarted := make(chan struct{})
releaseFirst := make(chan struct{})
var calls atomic.Int64
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if calls.Add(1) == 1 {
close(firstStarted)
<-releaseFirst
w.WriteHeader(http.StatusTooManyRequests)
return
}
_, _ = w.Write([]byte(solanaBlockCleanedUpResponse))
}))
defer srv.Close()
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL})
const slot = 459552217
s := newSolana()
t.Cleanup(s.stopSlotRetryTimers)
done := make(chan struct{})
go func() {
s.slotParse(slot)
close(done)
}()
<-firstStarted
s.slotParse(slot)
close(releaseFirst)
<-done
if got := s.pendingSlotRetryCount(); got != 0 {
t.Fatalf("pending retries after concurrent cleaned up = %d, want 0", got)
}
s.retryMu.Lock()
_, scheduled := s.retryScheduled[slot]
s.retryMu.Unlock()
if scheduled {
t.Fatalf("concurrent failure rescheduled cleaned up slot")
}
}
// 节点已清理的 slot 只请求一次就放弃,不留下待重试记录,向前扫描不会因此暂停;之前因为限流留下的重试也一并清除
func TestSolanaSlotParseGivesUpCleanedUpSlot(t *testing.T) {
var cleaned atomic.Bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !cleaned.Load() {
w.WriteHeader(http.StatusTooManyRequests)
return
}
_, _ = w.Write([]byte(solanaBlockCleanedUpResponse))
}))
defer srv.Close()
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL})
const slot = 459552217
s := newSolana()
t.Cleanup(s.stopSlotRetryTimers)
s.slotParse(slot)
if got := s.pendingSlotRetryCount(); got != 1 {
t.Fatalf("pending retries after 429 = %d, want 1", got)
}
s.expireSlotRetryTimer(slot)
cleaned.Store(true)
s.slotParse(slot)
if got := s.pendingSlotRetryCount(); got != 0 {
t.Fatalf("pending retries after cleaned up = %d, want 0: forward sync stays paused", got)
}
s.retryMu.Lock()
_, scheduled := s.retryScheduled[slot]
s.retryMu.Unlock()
if scheduled {
t.Fatalf("cleaned up slot still scheduled for retry")
}
}
+256
View File
@@ -0,0 +1,256 @@
package task
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"net/http"
"sync"
"time"
"filippo.io/edwards25519"
"git.viaeon.com/admin/vupay/app/conf"
"git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/model"
"github.com/btcsuite/btcd/btcutil/base58"
"github.com/tidwall/gjson"
)
// 订单过期后,按收款账户的链上历史对账一次。
// 扫块每个 slot 只有一次机会,跳块、放弃重试的 slot、重启、回溯范围不完整都会让有效期内的付款漏掉;
// 收款账户的签名列表是独立的链上历史,可以把这些付款找回来。
const (
solanaReconcileDelay = time.Minute // 过期后等待交易 finalized 再对账
solanaReconcileWindow = 2 * time.Hour // 只对最近过期的订单对账
solanaSignaturePageLimit = 1000
solanaAssociatedTokenProgram = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
)
// solanaReconciled 记录已完成对账的订单 ID;RPC 失败的订单不记录,下一轮重试
var solanaReconciled sync.Map // key: int64 order ID, value: struct{}
func (s *solana) reconcileExpiredOrders(ctx context.Context) {
now := time.Now()
var orders []model.Order
model.Db.Where("status = ? and trade_type in (?)", model.OrderStatusExpired, model.GetNetworkTrades(conf.Solana)).
Where("expired_at > ? and expired_at < ?", now.Add(-solanaReconcileWindow), now.Add(-solanaReconcileDelay)).
Find(&orders)
for _, o := range orders {
if ctx.Err() != nil {
return
}
if _, done := solanaReconciled.Load(o.ID); done {
continue
}
if err := s.reconcileOrder(ctx, o); err != nil {
log.Task.Warn(fmt.Sprintf("Solana 订单对账失败,稍后重试 %s:%v", o.TradeId, err))
continue
}
solanaReconciled.Store(o.ID, struct{}{})
}
}
func (s *solana) reconcileOrder(ctx context.Context, o model.Order) error {
accounts, err := s.tokenAccounts(ctx, orderMatchAddress(o), model.GetTradeContract(o.TradeType))
if err != nil {
return err
}
for _, account := range accounts {
signatures, err := s.orderSignatures(ctx, account, o)
if err != nil {
return err
}
for _, signature := range signatures {
var used int64
model.Db.Model(&model.Order{}).Where("ref_hash = ?", signature).Count(&used)
if used > 0 {
continue
}
trans, err := s.rpcCall(ctx, "getTransaction", signature,
map[string]any{"encoding": "json", "maxSupportedTransactionVersion": 1, "commitment": "finalized"})
if err != nil {
return err
}
if trans.Type == gjson.Null {
return fmt.Errorf("getTransaction %s: transaction not found", signature)
}
timestamp := time.Unix(trans.Get("blockTime").Int(), 0)
for _, t := range s.parseTransaction(trans, int(trans.Get("slot").Int()), timestamp) {
if !orderTransferMatch(o, t) {
continue
}
if err := o.MarkConfirming(t.BlockNum, t.FromAddress, t.TxHash, t.Timestamp, t.Amount); err != nil {
return err
}
log.Task.Info(fmt.Sprintf("Solana 对账找回付款 %s:%s", o.TradeId, t.TxHash))
return nil
}
}
}
return nil
}
// tokenAccounts 返回钱包在该 mint 下的代币账户:总是包含关联代币账户(ATA),节点支持 getTokenAccountsByOwner 时再加上其他代币账户。
// 部分节点(如 publicnode 免费节点)不提供 getTokenAccountsByOwner,此时只检查 ATA,绝大多数付款都转入 ATA。
func (s *solana) tokenAccounts(ctx context.Context, owner, mint string) ([]string, error) {
ata, err := solanaAssociatedTokenAccount(owner, mint)
if err != nil {
return nil, err
}
accounts := []string{ata}
result, err := s.rpcCall(ctx, "getTokenAccountsByOwner", owner, map[string]any{"mint": mint},
map[string]any{"encoding": "base64", "dataSlice": map[string]int{"offset": 0, "length": 0}, "commitment": "finalized"})
if err != nil {
return accounts, nil
}
for _, account := range result.Get("value.#.pubkey").Array() {
if account.String() != ata {
accounts = append(accounts, account.String())
}
}
return accounts, nil
}
// solanaAssociatedTokenAccount 按 Associated Token Account 程序的规则推导地址:
// seeds = [钱包, Token 程序, mint],从 bump 255 往下找第一个不在 ed25519 曲线上的哈希
func solanaAssociatedTokenAccount(owner, mint string) (string, error) {
seeds := [][]byte{base58.Decode(owner), base58.Decode(conf.SolSplToken), base58.Decode(mint)}
for _, seed := range seeds {
if len(seed) != 32 {
return "", fmt.Errorf("invalid Solana address: %s / %s", owner, mint)
}
}
program := base58.Decode(solanaAssociatedTokenProgram)
for bump := 255; bump >= 0; bump-- {
h := sha256.New()
for _, seed := range seeds {
h.Write(seed)
}
h.Write([]byte{byte(bump)})
h.Write(program)
h.Write([]byte("ProgramDerivedAddress"))
addr := h.Sum(nil)
if _, err := new(edwards25519.Point).SetBytes(addr); err != nil {
return base58.Encode(addr), nil
}
}
return "", fmt.Errorf("no associated token account for %s / %s", owner, mint)
}
// orderSignatures 返回代币账户在订单有效期内执行成功的交易签名;签名按时间倒序分页返回
func (s *solana) orderSignatures(ctx context.Context, account string, o model.Order) ([]string, error) {
var result []string
opts := map[string]any{"limit": solanaSignaturePageLimit, "commitment": "finalized"}
for {
page, err := s.rpcCall(ctx, "getSignaturesForAddress", account, opts)
if err != nil {
return nil, err
}
items := page.Array()
for _, itm := range items {
if !itm.Get("blockTime").Exists() || itm.Get("blockTime").Type == gjson.Null {
continue
}
at := time.Unix(itm.Get("blockTime").Int(), 0)
if !o.CreatedAt.Before(at) { // 已早于订单创建时间
return result, nil
}
if o.ExpiredAt.After(at) && solanaTxSucceeded(itm.Get("err")) {
result = append(result, itm.Get("signature").String())
}
}
if len(items) < solanaSignaturePageLimit {
return result, nil
}
opts["before"] = items[len(items)-1].Get("signature").String()
}
}
func (s *solana) rpcCall(ctx context.Context, method string, params ...any) (gjson.Result, error) {
post, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": method, "params": params})
if err != nil {
return gjson.Result{}, err
}
req, err := http.NewRequestWithContext(ctx, "POST", model.Endpoint(conf.Solana), bytes.NewBuffer(post))
if err != nil {
return gjson.Result{}, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := s.client.Do(req)
if err != nil {
return gjson.Result{}, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return gjson.Result{}, fmt.Errorf("%s response status code %d", method, resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return gjson.Result{}, err
}
if !gjson.ValidBytes(body) {
return gjson.Result{}, fmt.Errorf("%s invalid JSON response", method)
}
data := gjson.ParseBytes(body)
if rpcErr := data.Get("error"); rpcErr.Exists() {
return gjson.Result{}, fmt.Errorf("%s RPC error: %s", method, rpcErr.Raw)
}
if !data.Get("result").Exists() {
return gjson.Result{}, fmt.Errorf("%s missing result", method)
}
return data.Get("result"), nil
}
+243
View File
@@ -0,0 +1,243 @@
package task
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
"git.viaeon.com/admin/vupay/app/model"
"github.com/tidwall/gjson"
)
const (
reconcileTestOwner = "F7p3dFrjRTbtRp8FRF6qHLomXbKRBzpvBLjtQcfcgmNe"
reconcileTestSignature = "DohbsAfxAerDTAX9XS1b9jXY5XYMXQsCnyY3qu42eEEcTeJ6UzMbFs3JTdY14QgNKQPdy6yezdgbqLbnRVj6YB6"
reconcileTestSlot = 451914288
)
type reconcileTestRPC struct {
blockTime int64 // 交易时间,同时用于签名列表和 getTransaction
signatureErr string // 签名列表里的 err 字段
paidAccount string // 签名列表里有这笔付款的代币账户,默认是收款钱包的 ATA
extraAccount string // getTokenAccountsByOwner 额外返回的代币账户;为空时该方法报错,模拟 publicnode 免费节点
failSignatures atomic.Bool
getTransaction atomic.Int64
}
// 按 JSON-RPC 方法返回;getTransaction 使用主网交易 success_v0_inner_transfer.json,只改 blockTime
func newReconcileTestServer(t *testing.T, rpc *reconcileTestRPC) *httptest.Server {
t.Helper()
ata, err := solanaAssociatedTokenAccount(reconcileTestOwner, model.GetTradeContract(model.UsdcSolana))
if err != nil {
t.Fatalf("derive ATA: %v", err)
}
if rpc.paidAccount == "" {
rpc.paidAccount = ata
}
trans := gjson.GetBytes(readSolanaFixture(t, "success_v0_inner_transfer.json"), "result.transactions.0").Raw
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/notify" {
_, _ = w.Write([]byte("ok"))
return
}
body, _ := io.ReadAll(r.Body)
switch gjson.GetBytes(body, "method").String() {
case "getTokenAccountsByOwner":
if rpc.extraAccount == "" {
_, _ = w.Write([]byte(`{"jsonrpc":"2.0","error":{"code":-32602,"message":"Indexed requests require a personal token"},"id":1}`))
return
}
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":{"context":{"slot":%d},"value":[{"pubkey":"%s","account":{}},{"pubkey":"%s","account":{}}]},"id":1}`, reconcileTestSlot+1000, ata, rpc.extraAccount)
case "getSignaturesForAddress":
if rpc.failSignatures.Load() {
_, _ = w.Write([]byte(`{"jsonrpc":"2.0","error":{"code":-32005,"message":"Node is behind"},"id":1}`))
return
}
if gjson.GetBytes(body, "params.0").String() != rpc.paidAccount {
_, _ = w.Write([]byte(`{"jsonrpc":"2.0","result":[],"id":1}`))
return
}
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":[{"signature":"%s","slot":%d,"err":%s,"memo":null,"blockTime":%d,"confirmationStatus":"finalized"}],"id":1}`, reconcileTestSignature, reconcileTestSlot, rpc.signatureErr, rpc.blockTime)
case "getSignatureStatuses":
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":{"context":{"slot":%d},"value":[{"confirmationStatus":"finalized","confirmations":null,"err":null,"slot":%d,"status":{"Ok":null}}]},"id":1}`, reconcileTestSlot+1000, reconcileTestSlot)
case "getTransaction":
rpc.getTransaction.Add(1)
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":{"slot":%d,"blockTime":%d,%s,"id":1}`, reconcileTestSlot, rpc.blockTime, trans[1:])
default:
t.Errorf("unexpected method: %s", body)
}
}))
t.Cleanup(srv.Close)
return srv
}
func createReconcileTestOrder(t *testing.T, tradeID, amount string) model.Order {
t.Helper()
return createTestOrder(t, model.Order{
NotifyUrl: model.GetC(model.RpcEndpointSolana) + "/notify",
OrderId: "merchant-" + tradeID,
TradeId: tradeID,
TradeType: model.UsdcSolana,
Rate: "7.00",
Amount: amount,
Money: "2736.93",
Address: reconcileTestOwner,
Status: model.OrderStatusExpired,
ApiType: model.OrderApiTypeVupay,
ExpiredAt: time.Now().Add(-5 * time.Minute),
}, time.Now().Add(-15*time.Minute))
}
func initReconcileTest(t *testing.T, rpc *reconcileTestRPC) *solana {
t.Helper()
srv := newReconcileTestServer(t, rpc)
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL})
solanaReconciled.Clear()
s := newSolana()
return &s
}
func TestSolanaReconcileFindsMissedPayment(t *testing.T) {
rpc := &reconcileTestRPC{blockTime: time.Now().Add(-10 * time.Minute).Unix(), signatureErr: "null"}
s := initReconcileTest(t, rpc)
order := createReconcileTestOrder(t, "trade-order-1", "390.990618")
s.reconcileExpiredOrders(t.Context())
got := getTestOrder(t, order.TradeId)
if got.Status != model.OrderStatusConfirming || got.RefHash != reconcileTestSignature || got.RefBlockNum != reconcileTestSlot ||
got.FromAddress != "GMCJvYGf5Ex2ARiMquaBDqU6iKM8uiEQkB8jCnoNfHpC" {
t.Fatalf("order = status %d ref %s slot %d from %s, want confirming with the payment", got.Status, got.RefHash, got.RefBlockNum, got.FromAddress)
}
if got.ConfirmedAt == nil || got.ConfirmedAt.Unix() != rpc.blockTime {
t.Fatalf("confirmed_at = %v, want the transaction time", got.ConfirmedAt)
}
// 之后按原流程确认并回调:订单虽已过期,但付款时间在有效期内
s.tradeConfirmHandle(t.Context())
if got := getTestOrder(t, order.TradeId); got.Status != model.OrderStatusSuccess {
t.Fatalf("order status = %d after confirm, want success", got.Status)
}
waitOrderNotified(t, order.TradeId)
}
func TestSolanaReconcileSkipsUnmatchedPayments(t *testing.T) {
inWindow := time.Now().Add(-10 * time.Minute).Unix()
tests := []struct {
name string
blockTime int64
signatureErr string
amount string
usedByOtherOrder bool
wantGetTransaction int64
}{
{name: "failed transaction", blockTime: inWindow, signatureErr: `{"InstructionError":[1,{"Custom":6001}]}`, amount: "390.990618"},
{name: "paid before order created", blockTime: time.Now().Add(-30 * time.Minute).Unix(), signatureErr: "null", amount: "390.990618"},
{name: "paid after expiry", blockTime: time.Now().Add(-2 * time.Minute).Unix(), signatureErr: "null", amount: "390.990618"},
{name: "signature used by another order", blockTime: inWindow, signatureErr: "null", amount: "390.990618", usedByOtherOrder: true},
{name: "amount mismatch", blockTime: inWindow, signatureErr: "null", amount: "1.23", wantGetTransaction: 1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rpc := &reconcileTestRPC{blockTime: tt.blockTime, signatureErr: tt.signatureErr}
s := initReconcileTest(t, rpc)
order := createReconcileTestOrder(t, "trade-order-1", tt.amount)
if tt.usedByOtherOrder {
other := createReconcileTestOrder(t, "trade-order-2", "100")
other.Status = model.OrderStatusSuccess
other.RefHash = reconcileTestSignature
model.Db.Save(&other)
}
s.reconcileExpiredOrders(t.Context())
if got := getTestOrder(t, order.TradeId); got.Status != model.OrderStatusExpired || got.RefHash != "" {
t.Fatalf("order = status %d ref %s, want unchanged", got.Status, got.RefHash)
}
if got := rpc.getTransaction.Load(); got != tt.wantGetTransaction {
t.Fatalf("getTransaction calls = %d, want %d", got, tt.wantGetTransaction)
}
if _, done := solanaReconciled.Load(order.ID); !done {
t.Fatalf("order not marked as reconciled")
}
})
}
}
func TestSolanaReconcileRetriesOnRPCError(t *testing.T) {
rpc := &reconcileTestRPC{blockTime: time.Now().Add(-10 * time.Minute).Unix(), signatureErr: "null"}
s := initReconcileTest(t, rpc)
order := createReconcileTestOrder(t, "trade-order-1", "390.990618")
rpc.failSignatures.Store(true)
s.reconcileExpiredOrders(t.Context())
if _, done := solanaReconciled.Load(order.ID); done {
t.Fatalf("order marked as reconciled after RPC error")
}
rpc.failSignatures.Store(false)
s.reconcileExpiredOrders(t.Context())
if got := getTestOrder(t, order.TradeId); got.Status != model.OrderStatusConfirming {
t.Fatalf("order status = %d after retry, want confirming", got.Status)
}
}
func TestSolanaReconcileOnlyRecentlyExpiredOrders(t *testing.T) {
rpc := &reconcileTestRPC{blockTime: time.Now().Add(-10 * time.Minute).Unix(), signatureErr: "null"}
s := initReconcileTest(t, rpc)
order := createReconcileTestOrder(t, "trade-order-1", "390.990618")
order.ExpiredAt = time.Now().Add(-30 * time.Second) // 还没到对账延迟,交易可能尚未 finalized
model.Db.Save(&order)
s.reconcileExpiredOrders(t.Context())
if got := getTestOrder(t, order.TradeId); got.Status != model.OrderStatusExpired {
t.Fatalf("order status = %d, want expired until the reconcile delay passes", got.Status)
}
}
func TestSolanaReconcileChecksOtherTokenAccounts(t *testing.T) {
const other = "ReconcileTestTokenAccount111111111111111111"
rpc := &reconcileTestRPC{blockTime: time.Now().Add(-10 * time.Minute).Unix(), signatureErr: "null", paidAccount: other, extraAccount: other}
s := initReconcileTest(t, rpc)
order := createReconcileTestOrder(t, "trade-order-1", "390.990618")
s.reconcileExpiredOrders(t.Context())
if got := getTestOrder(t, order.TradeId); got.Status != model.OrderStatusConfirming || got.RefHash != reconcileTestSignature {
t.Fatalf("order = status %d ref %s, want the payment to the non-ATA token account", got.Status, got.RefHash)
}
}
func TestSolanaAssociatedTokenAccount(t *testing.T) {
tests := []struct {
owner, mint, want string
}{
// 主网交易中的代币账户(success_legacy_transfer.json、success_legacy_transfer_checked.json)
{owner: "Mdv6q9cauwiPLTn43SXuLtitAsDbNHtT3sFbknNvr6b", mint: "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB", want: "Hwnrd47xhiULAjwLThEnuxnVTCwJyr5phkfwDyB58ns1"},
{owner: "8tjDqRuhYN1PZcZkwLy9sRTUb1hbJNyijJeAESxG5zxv", mint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", want: "9un7p7bo7Y4TBwVdsQZTWtLZtkvW9hAUzdeV7mardWo5"},
}
for _, tt := range tests {
if got, err := solanaAssociatedTokenAccount(tt.owner, tt.mint); err != nil || got != tt.want {
t.Fatalf("ATA(%s, %s) = %s, %v; want %s", tt.owner, tt.mint, got, err, tt.want)
}
}
if _, err := solanaAssociatedTokenAccount("not-an-address", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"); err == nil {
t.Fatalf("invalid owner accepted")
}
}
+60
View File
@@ -0,0 +1,60 @@
package task
import (
"net/http"
"net/http/httptest"
"testing"
"git.viaeon.com/admin/vupay/app/model"
)
// 模拟重试定时器到期并再次扫描失败:取消定时器,下一次 scheduleSlotRetry 计为新的失败
func (s *solana) expireSlotRetryTimer(slot int) {
s.retryMu.Lock()
defer s.retryMu.Unlock()
if timer, ok := s.retryScheduled[slot]; ok {
timer.Stop()
delete(s.retryScheduled, slot)
}
}
func (s *solana) stopSlotRetryTimers() {
s.retryMu.Lock()
defer s.retryMu.Unlock()
for slot, timer := range s.retryScheduled {
timer.Stop()
delete(s.retryScheduled, slot)
}
}
func TestSolanaSlotRetryGivesUpAfterMaxRetries(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(`{"jsonrpc":"2.0","error":{"code":-32004,"message":"Block not available for slot 457000000"},"id":1}`))
}))
defer srv.Close()
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL})
const slot = 457000000
s := newSolana()
t.Cleanup(s.stopSlotRetryTimers)
for i := 1; i <= solanaSlotMaxRetries; i++ {
s.slotParse(slot)
if got := s.pendingSlotRetryCount(); got != 1 {
t.Fatalf("after %d failures pending retries = %d, want 1", i, got)
}
s.expireSlotRetryTimer(slot)
}
s.slotParse(slot)
if got := s.pendingSlotRetryCount(); got != 0 {
t.Fatalf("pending retries = %d after giving up, forward sync stays paused", got)
}
s.retryMu.Lock()
_, scheduled := s.retryScheduled[slot]
s.retryMu.Unlock()
if scheduled {
t.Fatalf("slot still scheduled after giving up")
}
}
+84
View File
@@ -0,0 +1,84 @@
package task
import (
"strings"
"testing"
"time"
"github.com/tidwall/gjson"
)
func TestSolanaGetBlockPayloadSupportsVersionOne(t *testing.T) {
payload := string(solanaGetBlockPayload(456519571))
if !strings.Contains(payload, `"maxSupportedTransactionVersion":1`) {
t.Fatalf("payload does not support Solana v1 transactions: %s", payload)
}
}
func TestValidateSolanaBlockResponse(t *testing.T) {
tests := []struct {
name string
body string
wantErr bool
wantSkipped bool
}{
{name: "valid empty block", body: `{"jsonrpc":"2.0","result":{"blockTime":1760380000,"transactions":[]},"id":1}`},
{name: "null result", body: `{"jsonrpc":"2.0","result":null,"id":1}`, wantSkipped: true},
{name: "slot skipped", body: `{"jsonrpc":"2.0","error":{"code":-32007,"message":"Slot 300000092 was skipped, or missing due to ledger jump to recent snapshot"},"id":1}`, wantSkipped: true},
{name: "long-term storage slot skipped", body: `{"jsonrpc":"2.0","error":{"code":-32009,"message":"Slot 300000092 was skipped, or missing in long-term storage"},"id":1}`, wantSkipped: true},
{name: "block not available", body: `{"jsonrpc":"2.0","error":{"code":-32004,"message":"Block not available for slot 456731994"},"id":1}`, wantErr: true},
{name: "unsupported transaction version", body: `{"jsonrpc":"2.0","error":{"code":-32015,"message":"Transaction version (1) is not supported by the requesting client"},"id":1}`, wantErr: true},
{name: "missing result", body: `{"jsonrpc":"2.0","id":1}`, wantErr: true},
{name: "missing transactions", body: `{"jsonrpc":"2.0","result":{"blockTime":1760380000},"id":1}`, wantErr: true},
{name: "invalid json", body: `<html>rate limited</html>`, wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := validateSolanaBlockResponse([]byte(tt.body))
if (err != nil) != tt.wantErr {
t.Fatalf("error = %v, wantErr %v", err, tt.wantErr)
}
if err == nil && (result.Type == gjson.Null) != tt.wantSkipped {
t.Fatalf("skipped = %v, want %v", result.Type == gjson.Null, tt.wantSkipped)
}
})
}
}
func TestSolanaRetryDelayIsBounded(t *testing.T) {
tests := []struct {
attempt int
want time.Duration
}{
{attempt: 1, want: 2 * time.Second},
{attempt: 2, want: 5 * time.Second},
{attempt: 3, want: 15 * time.Second},
{attempt: 4, want: 30 * time.Second},
{attempt: 5, want: time.Minute},
{attempt: 100, want: time.Minute},
}
for _, tt := range tests {
if got := solanaRetryDelay(tt.attempt); got != tt.want {
t.Fatalf("attempt %d delay = %s, want %s", tt.attempt, got, tt.want)
}
}
}
func TestValidSolanaLookbackRange(t *testing.T) {
tests := []struct {
start int64
end int64
want bool
}{
{start: 458225400, end: 458225500, want: true},
{start: 0, end: 0, want: false},
{start: 0, end: 458225500, want: false},
{start: 458225500, end: 458225400, want: false},
}
for _, tt := range tests {
if got := validSolanaLookbackRange(tt.start, tt.end); got != tt.want {
t.Fatalf("validSolanaLookbackRange(%d, %d) = %v, want %v", tt.start, tt.end, got, tt.want)
}
}
}
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"sync"
"time"
"github.com/v03413/bepusdt/app/model"
"git.viaeon.com/admin/vupay/app/model"
)
// 区块扫描队列最大长度,避免可能因为 Rpc Rate Limit 问题导致消费队列堆积,进而导致OOM,暂时简单限制队列长度
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
{"jsonrpc":"2.0","id":1,"result":{"blockTime":1791453359,"blockHeight":432548102,"parentSlot":454510625,"blockhash":"5z9SXEcj1JJKXtZVyr6qkD9NKuTPivkkypCDUdSMqKkx","transactions":[{"meta":{"computeUnitsConsumed":274,"costUnits":2648,"err":null,"fee":10000,"innerInstructions":[],"loadedAddresses":{"readonly":[],"writable":[]},"logMessages":["Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [1]","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 145 of 400000 compute units","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [1]","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 129 of 399855 compute units","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success"],"postBalances":[378107467,0,0,1488440,200654906],"postTokenBalances":[{"accountIndex":3,"mint":"Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB","owner":"Mdv6q9cauwiPLTn43SXuLtitAsDbNHtT3sFbknNvr6b","programId":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","uiTokenAmount":{"amount":"61535189","decimals":6,"uiAmount":61.535189,"uiAmountString":"61.535189"}}],"preBalances":[376629027,0,1488440,1488440,200654906],"preTokenBalances":[{"accountIndex":2,"mint":"Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB","owner":"218mr4Lpgn5nFX4vBmgSDUSj4uvtTnx5jmwC5cZFHfSn","programId":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","uiTokenAmount":{"amount":"5360000","decimals":6,"uiAmount":5.36,"uiAmountString":"5.36"}},{"accountIndex":3,"mint":"Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB","owner":"Mdv6q9cauwiPLTn43SXuLtitAsDbNHtT3sFbknNvr6b","programId":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","uiTokenAmount":{"amount":"56175189","decimals":6,"uiAmount":56.175189,"uiAmountString":"56.175189"}}],"rewards":null,"status":{"Ok":null}},"transaction":{"message":{"accountKeys":["Mdv6q9cauwiPLTn43SXuLtitAsDbNHtT3sFbknNvr6b","218mr4Lpgn5nFX4vBmgSDUSj4uvtTnx5jmwC5cZFHfSn","DurdksnNzKrvd41SuucDRGipUtHSJUzksubVao47B9Ui","Hwnrd47xhiULAjwLThEnuxnVTCwJyr5phkfwDyB58ns1","TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"],"header":{"numReadonlySignedAccounts":1,"numReadonlyUnsignedAccounts":1,"numRequiredSignatures":2},"instructions":[{"accounts":[2,3,1,1],"data":"3azxBPgCGsJw","programIdIndex":4,"stackHeight":1},{"accounts":[2,0,1,1],"data":"A","programIdIndex":4,"stackHeight":1}],"recentBlockhash":"HKXJmoBsY4nC9RY8aC6MjMph1BcMdq5cCmJuhQ4KwR6X"},"signatures":["5UKT7CpNSESsPw7xg7UHMKHD1M4UqaCDRCLPjTqkTmtXWvi3R6z4codAyYUKJitHRgeVQoyyqhC4iwsmcGvi1b2M","5A4enkfBgsaWB53V45UcQZgedAkTmvsMQ3HBPd8rUFGUyQR32v7CNR4bt9582bv6ZnbLD54BXtQ6FaiJ81qGKrNY"]},"version":"legacy"}]}}
@@ -0,0 +1 @@
{"jsonrpc":"2.0","id":1,"result":{"blockTime":1791803694,"blockHeight":434063612,"parentSlot":456026590,"blockhash":"5dam2f4AiJqFKZmUn9bY6eXaqMRvL6AfnxPDj2aw2dZ1","transactions":[{"meta":{"computeUnitsConsumed":234,"costUnits":2188,"err":null,"fee":5000,"innerInstructions":[],"loadedAddresses":{"readonly":[],"writable":[]},"logMessages":["Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [1]","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 105 of 400000 compute units","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [1]","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 129 of 399895 compute units","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success"],"postBalances":[1565660,89622429437,0,1488440,549535699757,230130698],"postTokenBalances":[{"accountIndex":3,"mint":"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v","owner":"8tjDqRuhYN1PZcZkwLy9sRTUb1hbJNyijJeAESxG5zxv","programId":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","uiTokenAmount":{"amount":"735887428","decimals":6,"uiAmount":735.887428,"uiAmountString":"735.887428"}}],"preBalances":[1570660,89620940997,1488440,1488440,549535699757,230130698],"preTokenBalances":[{"accountIndex":2,"mint":"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v","owner":"8HrXbX3MdyEpgwiA1MkqR5max8gugvpX7ay4DFDd53aH","programId":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","uiTokenAmount":{"amount":"2400","decimals":6,"uiAmount":0.0024,"uiAmountString":"0.0024"}},{"accountIndex":3,"mint":"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v","owner":"8tjDqRuhYN1PZcZkwLy9sRTUb1hbJNyijJeAESxG5zxv","programId":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","uiTokenAmount":{"amount":"735885028","decimals":6,"uiAmount":735.885028,"uiAmountString":"735.885028"}}],"rewards":null,"status":{"Ok":null}},"transaction":{"message":{"accountKeys":["8HrXbX3MdyEpgwiA1MkqR5max8gugvpX7ay4DFDd53aH","8tjDqRuhYN1PZcZkwLy9sRTUb1hbJNyijJeAESxG5zxv","9qo8j8q8RbfrjKrNuYRinwbPPzuRjCPrTuNv8qbqkPzz","9un7p7bo7Y4TBwVdsQZTWtLZtkvW9hAUzdeV7mardWo5","EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v","TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"],"header":{"numReadonlySignedAccounts":0,"numReadonlyUnsignedAccounts":2,"numRequiredSignatures":1},"instructions":[{"accounts":[2,4,3,0],"data":"hKr7pdRPTzpPf","programIdIndex":5,"stackHeight":1},{"accounts":[2,1,0,0],"data":"A","programIdIndex":5,"stackHeight":1}],"recentBlockhash":"9J7owuh66Xrx2ZfZziZhyQ4o7yEcwnQPeWmsyoU3DgK2"},"signatures":["3D3jCbXnRspBEzJZJ7devvJSyN27QbMSpzMkXjtsAfXHvWSw9PhqSvTxrwGeEJCZ7cy9cV6gnY4agr5cNaEjaFLY"]},"version":"legacy"}]}}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+108
View File
@@ -0,0 +1,108 @@
package task
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
applog "git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/model"
"github.com/tidwall/gjson"
)
// 任务测试的公共环境:临时日志目录、临时 SQLite 和主网交易 fixture
func initTaskTestEnv(t *testing.T, kv map[model.ConfKey]string) {
t.Helper()
if err := applog.Init(filepath.Join(t.TempDir(), "logs")); err != nil {
t.Fatalf("init log: %v", err)
}
t.Cleanup(applog.Close)
if err := model.Init(filepath.Join(t.TempDir(), "task-test.db"), "", ""); err != nil {
t.Fatalf("init db: %v", err)
}
t.Cleanup(func() {
if db, err := model.Db.DB(); err == nil {
_ = db.Close()
}
})
for k, v := range kv {
model.Db.Model(&model.Conf{}).Where("k = ?", k).Update("v", v)
}
model.RefreshC()
}
func createTestOrder(t *testing.T, o model.Order, created time.Time) model.Order {
t.Helper()
at := model.Datetime(created)
o.CreatedAt = &at
o.UpdatedAt = &at
if o.ConfirmedAt == nil {
o.ConfirmedAt = &created
}
if err := model.Db.Create(&o).Error; err != nil {
t.Fatalf("create order: %v", err)
}
return o
}
func getTestOrder(t *testing.T, tradeID string) model.Order {
t.Helper()
var o model.Order
if err := model.Db.Where("trade_id = ?", tradeID).First(&o).Error; err != nil {
t.Fatalf("get order: %v", err)
}
return o
}
// 订单成功后回调在协程中执行,等它写完最后一条日志,避免测试清理临时目录时仍有写入
func waitOrderNotified(t *testing.T, tradeID string) {
t.Helper()
file := filepath.Join(applog.GetPath(), "vupay.log")
for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
body, _ := os.ReadFile(file)
if strings.Contains(string(body), "订单回调成功") && strings.Contains(string(body), tradeID) {
return
}
}
t.Fatalf("order %s callback not finished", tradeID)
}
// 主网交易,每个文件是只含这一笔交易的 getBlock 响应
func readSolanaFixture(t *testing.T, name string) []byte {
t.Helper()
body, err := os.ReadFile(filepath.Join("testdata", "solana", name))
if err != nil {
t.Fatalf("read fixture: %v", err)
}
return body
}
// 返回 slotParse 写入 transferQueue 的转账
func drainTransferQueue() []transfer {
var result []transfer
for {
select {
case items := <-transferQueue.Out:
result = append(result, items...)
case <-time.After(200 * time.Millisecond):
return result
}
}
}
func solanaFixtureSlot(block []byte) int {
return int(gjson.GetBytes(block, "result.parentSlot").Int()) + 1
}
+169 -71
View File
@@ -7,15 +7,14 @@ import (
"sync"
"time"
"github.com/panjf2000/ants/v2"
"git.viaeon.com/admin/vupay/app/conf"
blockapi "git.viaeon.com/admin/vupay/app/core"
"git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/shopspring/decimal"
"github.com/smallnest/chanx"
"github.com/spf13/cast"
"github.com/v03413/bepusdt/app/conf"
blockapi "github.com/v03413/bepusdt/app/core"
"github.com/v03413/bepusdt/app/log"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/app/utils"
"github.com/xssnick/tonutils-go/address"
"github.com/xssnick/tonutils-go/tlb"
tgo "github.com/xssnick/tonutils-go/ton"
@@ -24,10 +23,22 @@ import (
const tonMasterChainID = -1
const tonMasterShard = int64(-0x8000000000000000)
const tonOpInternalTransfer = uint32(0x178d4519)
const tonBlockRetryMaxDelay = 15 * time.Second
type tonShardRange struct {
Workchain int32
Shard int64
Start uint32
End uint32
}
type tonShardKey struct {
Workchain int32
Shard int64
}
type ton struct {
lastBlockSeqno uint32
shardTipMap sync.Map // key: "workchain:shard", value: uint32 last processed shard seqno
blockScanQueue *chanx.UnboundedChan[uint32]
clientOnce sync.Once
api tgo.APIClientWrapped
@@ -102,15 +113,6 @@ func (t *ton) syncMBSeqnoForward(ctx context.Context) {
}
func (t *ton) blockDispatch(ctx context.Context) {
p, err := ants.NewPoolWithFunc(5, t.blockParse)
if err != nil {
log.Task.Warn("Error creating pool:", err)
return
}
defer p.Release()
for {
select {
case <-ctx.Done():
@@ -119,62 +121,134 @@ func (t *ton) blockDispatch(ctx context.Context) {
if !ok {
return
}
if err := p.Invoke(n); err != nil {
if err := retryTonBlock(ctx, n, time.Second, func(seqno uint32) error {
err := t.blockParse(ctx, seqno)
if err != nil {
log.Task.Warn(fmt.Sprintf("Ton 区块扫描失败,将重试 seqno=%d: %v", seqno, err))
}
log.Task.Warn("Tron Error invoking process block:", err)
return err
}); err != nil {
return
}
}
}
}
func (t *ton) blockParse(n any) {
var seqno = n.(uint32)
var ctx, cancel = context.WithTimeout(context.Background(), time.Second*60)
func (t *ton) blockParse(parent context.Context, seqno uint32) error {
var ctx, cancel = context.WithTimeout(parent, time.Second*60)
defer cancel()
mb, err := t.client().LookupBlock(ctx, tonMasterChainID, tonMasterShard, seqno)
if err != nil {
conf.RecordFailure(conf.Ton)
log.Task.Warn("Ton LookupBlock ", err)
return
return fmt.Errorf("lookup master block: %w", err)
}
conf.RecordSuccess(conf.Ton, cast.ToString(seqno))
// 目前实际来看,basechain 还未分裂,所以 len(shardsTip) == 1
shardsTip, err := t.client().GetBlockShardsInfo(ctx, mb)
if err != nil {
conf.RecordFailure(conf.Ton)
log.Task.Warn(fmt.Sprintf("get shards info seqno=%d err: %v", seqno, err))
return
return fmt.Errorf("get current shards info: %w", err)
}
for _, tip := range shardsTip {
start := tip.SeqNo
key := fmt.Sprintf("%d:%d", tip.Workchain, tip.Shard)
if old, loaded := t.shardTipMap.Swap(key, tip.SeqNo); loaded {
start = old.(uint32) + 1
var previousShards []*tgo.BlockIDExt
if seqno > 0 {
previousMB, lookupErr := t.client().LookupBlock(ctx, tonMasterChainID, tonMasterShard, seqno-1)
if lookupErr != nil {
conf.RecordFailure(conf.Ton)
return fmt.Errorf("lookup previous master block: %w", lookupErr)
}
for s := start; s <= tip.SeqNo; s++ {
shardBlock, err := t.client().LookupBlock(ctx, tip.Workchain, tip.Shard, s)
previousShards, err = t.client().GetBlockShardsInfo(ctx, previousMB)
if err != nil {
conf.RecordFailure(conf.Ton)
return fmt.Errorf("get previous shards info: %w", err)
}
}
for _, shardRange := range tonShardRanges(previousShards, shardsTip) {
for s := shardRange.Start; s <= shardRange.End; s++ {
shardBlock, err := t.client().LookupBlock(ctx, shardRange.Workchain, shardRange.Shard, s)
if err != nil {
conf.RecordFailure(conf.Ton)
log.Task.Warn(fmt.Sprintf("lookup shard block workchain=%d shard=%d seqno=%d err: %v", tip.Workchain, tip.Shard, s, err))
continue
return fmt.Errorf("lookup shard block workchain=%d shard=%d seqno=%d: %w", shardRange.Workchain, shardRange.Shard, s, err)
}
if err := t.processShard(ctx, shardBlock, seqno); err != nil {
conf.RecordFailure(conf.Ton)
log.Task.Warn(fmt.Sprintf("process shard block workchain=%d shard=%d seqno=%d err: %v", tip.Workchain, tip.Shard, s, err))
return fmt.Errorf("process shard block workchain=%d shard=%d seqno=%d: %w", shardRange.Workchain, shardRange.Shard, s, err)
}
}
}
conf.RecordSuccess(conf.Ton, cast.ToString(seqno))
log.Task.Info(fmt.Sprintf("区块扫描完成(Ton): %d 成功率:%s", seqno, conf.GetSuccessRate(conf.Ton)))
return nil
}
func tonShardRanges(previous, current []*tgo.BlockIDExt) []tonShardRange {
previousTips := make(map[tonShardKey]uint32, len(previous))
for _, tip := range previous {
key := tonShardKey{Workchain: tip.Workchain, Shard: tip.Shard}
previousTips[key] = tip.SeqNo
}
ranges := make([]tonShardRange, 0, len(current))
for _, tip := range current {
start := tip.SeqNo
key := tonShardKey{Workchain: tip.Workchain, Shard: tip.Shard}
if previousSeqno, ok := previousTips[key]; ok {
if previousSeqno >= tip.SeqNo {
continue
}
start = previousSeqno + 1
}
ranges = append(ranges, tonShardRange{
Workchain: tip.Workchain,
Shard: tip.Shard,
Start: start,
End: tip.SeqNo,
})
}
return ranges
}
func retryTonBlock(ctx context.Context, seqno uint32, initialDelay time.Duration, process func(uint32) error) error {
delay := initialDelay
for {
if err := process(seqno); err == nil {
return nil
}
if delay <= 0 {
continue
}
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
}
if delay < tonBlockRetryMaxDelay {
delay *= 2
if delay > tonBlockRetryMaxDelay {
delay = tonBlockRetryMaxDelay
}
}
}
}
func (t *ton) syncBreak() bool {
@@ -188,14 +262,13 @@ func (t *ton) syncBreak() bool {
return false
}
var count int64 = 0
trade := []model.TradeType{model.UsdtTon, model.TonGram}
model.Db.Model(&model.Order{}).Where("status = ? and trade_type in (?)", model.OrderStatusWaiting, trade).Count(&count)
if count > 0 {
if hasLookbackOrders(trade) {
return false
}
var count int64
model.Db.Model(&model.Wallet{}).Where("other_notify = ? and trade_type in (?)", model.WaOtherEnable, trade).Count(&count)
if count > 0 {
@@ -232,14 +305,38 @@ func (t *ton) processShard(ctx context.Context, shard *tgo.BlockIDExt, seqno uin
return nil
}
// https://github.com/ton-blockchain/TEPs/blob/63fc78718dd9930f3e106954ebec743c3ad07993/text/0074-jettons-standard.md?plain=1#L226
// https://github.com/ton-blockchain/token-contract/blob/1182ad99413242f09925d50e70ccb7e0e09f94d4/ft/jetton-wallet.fc#L43
func (t *ton) parseInternalTransfer(shard *tgo.BlockIDExt, tx *tlb.Transaction, blockNum uint32) (transfer, bool) {
// tonInboundMessage 提取交易的入站 internal 消息及其 ordinary 描述,两类转账解析共用
func tonInboundMessage(tx *tlb.Transaction) (*tlb.InternalMessage, tlb.TransactionDescriptionOrdinary, bool) {
var dsc tlb.TransactionDescriptionOrdinary
if tx.IO.In == nil {
return transfer{}, false
return nil, dsc, false
}
in, ok := tx.IO.In.Msg.(*tlb.InternalMessage)
if !ok || in.Bounced || in.Body == nil {
return nil, dsc, false
}
if dsc, ok = tx.Description.(tlb.TransactionDescriptionOrdinary); !ok {
return nil, dsc, false
}
if dsc.BouncePhase != nil {
if _, ok = dsc.BouncePhase.Phase.(tlb.BouncePhaseOk); ok {
return nil, dsc, false
}
}
return in, dsc, true
}
// tonAccountAddr 统一输出为 non-bounceable 格式,与钱包 MatchAddr 保持一致
func tonAccountAddr(addr *address.Address) string {
return addr.Bounce(false).String()
}
// https://github.com/ton-blockchain/TEPs/blob/63fc78718dd9930f3e106954ebec743c3ad07993/text/0074-jettons-standard.md?plain=1#L226
// https://github.com/ton-blockchain/token-contract/blob/1182ad99413242f09925d50e70ccb7e0e09f94d4/ft/jetton-wallet.fc#L43
func (t *ton) parseInternalTransfer(shard *tgo.BlockIDExt, tx *tlb.Transaction, blockNum uint32) (transfer, bool) {
in, dsc, ok := tonInboundMessage(tx)
if !ok {
return transfer{}, false
}
s, err := in.Body.BeginParse()
@@ -251,17 +348,12 @@ func (t *ton) parseInternalTransfer(shard *tgo.BlockIDExt, tx *tlb.Transaction,
return transfer{}, false
}
transOrd, ok := tx.Description.(tlb.TransactionDescriptionOrdinary)
if !ok {
return transfer{}, false
}
compute, ok := transOrd.ComputePhase.Phase.(tlb.ComputePhaseVM)
compute, ok := dsc.ComputePhase.Phase.(tlb.ComputePhaseVM)
if !ok || !compute.Success {
return transfer{}, false
}
if transOrd.ActionPhase == nil || !transOrd.ActionPhase.Success {
if dsc.ActionPhase == nil || !dsc.ActionPhase.Success {
return transfer{}, false
}
@@ -286,8 +378,8 @@ func (t *ton) parseInternalTransfer(shard *tgo.BlockIDExt, tx *tlb.Transaction,
Network: conf.Ton,
TxHash: hex.EncodeToString(tx.Hash),
Amount: decimal.NewFromBigInt(amount, conf.UsdtTonDecimals),
FromAddress: fromOwner.Bounce(false).String(),
RecvAddress: toJetton.Bounce(false).String(),
FromAddress: tonAccountAddr(fromOwner),
RecvAddress: tonAccountAddr(toJetton),
Timestamp: time.Unix(int64(tx.Now), 0),
TradeType: model.UsdtTon,
BlockNum: int(blockNum),
@@ -295,30 +387,19 @@ func (t *ton) parseInternalTransfer(shard *tgo.BlockIDExt, tx *tlb.Transaction,
}
func (t *ton) parseTonTransfer(tx *tlb.Transaction, blockNum uint32) (transfer, bool) {
in := tx.IO.In
if in == nil {
return transfer{}, false
}
msg, ok := in.Msg.(*tlb.InternalMessage)
msg, _, ok := tonInboundMessage(tx)
if !ok {
return transfer{}, false
}
if msg.Bounced {
return transfer{}, false
}
if msg.Amount.Nano().Sign() <= 0 {
return transfer{}, false
}
if msg.Body.BitsSize() != 0 {
if msg.Amount.Nano().Sign() <= 0 || msg.Body.BitsSize() != 0 {
return transfer{}, false
}
return transfer{
Network: conf.Ton,
TxHash: hex.EncodeToString(tx.Hash),
FromAddress: msg.SrcAddr.Bounce(false).String(),
RecvAddress: msg.DstAddr.Bounce(false).String(),
FromAddress: tonAccountAddr(msg.SrcAddr),
RecvAddress: tonAccountAddr(msg.DstAddr),
Timestamp: time.Unix(int64(tx.Now), 0),
Amount: decimal.NewFromBigInt(msg.Amount.Nano(), conf.TonTonDecimals),
TradeType: model.TonGram,
@@ -356,12 +437,18 @@ func (t *ton) lookbackBlocks(ctx context.Context) {
return
}
startAt, endAt, ok := getLookbackUnix(conf.Ton)
startAt, endAt, orderIDs, ok := pendingLookbackUnix(conf.Ton)
if !ok {
return
}
start, end := blockapi.New().GetBoundaryHeights(startAt, endAt, conf.Ton)
if start <= 0 || end < start {
log.Task.Warn(fmt.Sprintf("Ton 回溯高度范围无效: start=%d end=%d", start, end))
return
}
for i := start; i <= end; i++ {
select {
case <-ctx.Done():
@@ -371,7 +458,18 @@ func (t *ton) lookbackBlocks(ctx context.Context) {
if t.syncBreak() {
return
}
t.blockScanQueue.In <- uint32(i)
if err := retryTonBlock(ctx, uint32(i), time.Second, func(seqno uint32) error {
err := t.blockParse(ctx, seqno)
if err != nil {
log.Task.Warn(fmt.Sprintf("Ton 历史区块扫描失败,将重试 seqno=%d: %v", seqno, err))
}
return err
}); err != nil {
return
}
time.Sleep(time.Millisecond * 200) // 速率控制
}
markLookbackDone(orderIDs)
}
+124
View File
@@ -0,0 +1,124 @@
package task
import (
"testing"
"git.viaeon.com/admin/vupay/app/model"
"github.com/xssnick/tonutils-go/address"
"github.com/xssnick/tonutils-go/tlb"
tgo "github.com/xssnick/tonutils-go/ton"
"github.com/xssnick/tonutils-go/tvm/cell"
)
var (
tonTestSrc = address.NewAddress(0, 0, make([]byte, 32))
tonTestDst = address.NewAddress(0, 0, append(make([]byte, 31), 1))
)
func tonTestTx(body *cell.Cell, nano uint64, dsc any) *tlb.Transaction {
tx := &tlb.Transaction{AccountAddr: tonTestDst.Data(), Now: 1700000000, Hash: []byte{0xab}, Description: dsc}
tx.IO.In = &tlb.Message{MsgType: tlb.MsgTypeInternal, Msg: &tlb.InternalMessage{
SrcAddr: tonTestSrc,
DstAddr: tonTestDst,
Amount: tlb.FromNanoTONU(nano),
Body: body,
}}
return tx
}
func tonTestOrdinary(success bool) tlb.TransactionDescriptionOrdinary {
return tlb.TransactionDescriptionOrdinary{
ComputePhase: tlb.ComputePhase{Phase: tlb.ComputePhaseVM{Success: success}},
ActionPhase: &tlb.ActionPhase{Success: success},
}
}
func tonTestJettonBody(op uint32, amount uint64) *cell.Cell {
return cell.BeginCell().
MustStoreUInt(uint64(op), 32).
MustStoreUInt(1, 64).
MustStoreCoins(amount).
MustStoreAddr(tonTestSrc).
EndCell()
}
func TestParseTonTransfer(t *testing.T) {
empty := cell.BeginCell().EndCell()
skipped := tlb.TransactionDescriptionOrdinary{
ComputePhase: tlb.ComputePhase{Phase: tlb.ComputePhaseSkipped{}},
Aborted: true,
}
returned := skipped
returned.BouncePhase = &tlb.BouncePhase{Phase: tlb.BouncePhaseOk{}}
noFunds := skipped
noFunds.BouncePhase = &tlb.BouncePhase{Phase: tlb.BouncePhaseNoFunds{}}
bouncedIn := tonTestTx(empty, 1e9, tonTestOrdinary(true))
bouncedIn.IO.In.Msg.(*tlb.InternalMessage).Bounced = true
external := tonTestTx(empty, 1e9, tonTestOrdinary(true))
external.IO.In.Msg = &tlb.ExternalMessage{}
noIn := tonTestTx(empty, 1e9, tonTestOrdinary(true))
noIn.IO.In = nil
cases := []struct {
name string
tx *tlb.Transaction
ok bool
}{
{"plain", tonTestTx(empty, 1e9, tonTestOrdinary(true)), true},
{"uninit account", tonTestTx(empty, 1e9, skipped), true},
{"uninit account, bounce unpaid", tonTestTx(empty, 1e9, noFunds), true},
{"returned to sender", tonTestTx(empty, 1e9, returned), false},
{"zero amount", tonTestTx(empty, 0, tonTestOrdinary(true)), false},
{"with body", tonTestTx(tonTestJettonBody(tonOpInternalTransfer, 1), 1e9, tonTestOrdinary(true)), false},
{"bounced inbound", bouncedIn, false},
{"external inbound", external, false},
{"no inbound", noIn, false},
{"tick tock", tonTestTx(empty, 1e9, tlb.TransactionDescriptionTickTock{}), false},
}
for _, c := range cases {
got, ok := (&ton{}).parseTonTransfer(c.tx, 100)
if ok != c.ok {
t.Errorf("%s: ok = %v, want %v", c.name, ok, c.ok)
}
if !ok {
continue
}
if got.TradeType != model.TonGram || got.Amount.String() != "1" || got.BlockNum != 100 {
t.Errorf("%s: unexpected transfer %+v", c.name, got)
}
if got.RecvAddress != tonTestDst.Bounce(false).String() || got.FromAddress != tonTestSrc.Bounce(false).String() {
t.Errorf("%s: unexpected address %s <- %s", c.name, got.RecvAddress, got.FromAddress)
}
}
}
func TestParseTonInternalTransfer(t *testing.T) {
shard := &tgo.BlockIDExt{Workchain: 0}
cases := []struct {
name string
tx *tlb.Transaction
ok bool
}{
{"jetton received", tonTestTx(tonTestJettonBody(tonOpInternalTransfer, 2_500_000), 1, tonTestOrdinary(true)), true},
{"other op", tonTestTx(tonTestJettonBody(0x7362d09c, 2_500_000), 1, tonTestOrdinary(true)), false},
{"execution failed", tonTestTx(tonTestJettonBody(tonOpInternalTransfer, 2_500_000), 1, tonTestOrdinary(false)), false},
{"zero amount", tonTestTx(tonTestJettonBody(tonOpInternalTransfer, 0), 1, tonTestOrdinary(true)), false},
{"empty body", tonTestTx(cell.BeginCell().EndCell(), 1, tonTestOrdinary(true)), false},
}
for _, c := range cases {
got, ok := (&ton{}).parseInternalTransfer(shard, c.tx, 100)
if ok != c.ok {
t.Errorf("%s: ok = %v, want %v", c.name, ok, c.ok)
}
if !ok {
continue
}
if got.TradeType != model.UsdtTon || got.Amount.String() != "2.5" || got.RecvAddress != tonTestDst.Bounce(false).String() {
t.Errorf("%s: unexpected transfer %+v", c.name, got)
}
}
}
+63 -24
View File
@@ -3,17 +3,16 @@ package task
import (
"context"
"fmt"
"strings"
"sync"
"time"
"git.viaeon.com/admin/vupay/app/conf"
"git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/app/notifier"
"git.viaeon.com/admin/vupay/app/task/notify"
"github.com/shopspring/decimal"
"github.com/smallnest/chanx"
"github.com/v03413/bepusdt/app/conf"
"github.com/v03413/bepusdt/app/log"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/app/notifier"
"github.com/v03413/bepusdt/app/task/notify"
"github.com/v03413/tronprotocol/core"
)
@@ -260,7 +259,7 @@ func markFinalConfirmed(o model.Order) {
}
func receivableOrderStatuses() []int {
return []int{model.OrderStatusWaiting, model.OrderStatusExpired}
return []int{model.OrderStatusWaiting, model.OrderStatusExpired, model.OrderStatusConfirming}
}
func getReceivableOrders() map[string][]model.Order {
@@ -293,7 +292,32 @@ func hasLookbackOrders(tradeType []model.TradeType) bool {
return count > 0
}
// lookbackOrdersPending 判断这些订单中是否还有需要回溯的,条件与 hasLookbackOrders 相同
func lookbackOrdersPending(orderIDs []int64) (bool, error) {
if len(orderIDs) == 0 {
return false, nil
}
var count int64
err := model.Db.Model(&model.Order{}).
Where("id in (?)", orderIDs).
Where("status in (?)", receivableOrderStatuses()).
Where("expired_at > ?", time.Now().Add(model.GetLookbackHour())).
Count(&count).Error
return count > 0, err
}
func getLookbackUnix(network model.Network) (startAt, endAt int64, ok bool) {
startAt, endAt, orderIDs, ok := pendingLookbackUnix(network)
if ok {
markLookbackDone(orderIDs)
}
return startAt, endAt, ok
}
func pendingLookbackUnix(network model.Network) (startAt, endAt int64, orderIDs []int64, ok bool) {
trade := model.GetNetworkTrades(network)
if len(trade) == 0 {
return
@@ -317,28 +341,38 @@ func getLookbackUnix(network model.Network) (startAt, endAt int64, ok bool) {
if len(pending) == 0 {
return
}
orderIDs = make([]int64, 0, len(pending))
for _, o := range pending {
orderIDs = append(orderIDs, o.ID)
}
// 起点:最早的创建时间(已按 created_at asc 排序)
startAt = pending[0].CreatedAt.Time().Unix()
// 终点:最晚的已过期 expired_at;若全部尚未过期则用当前时间
endAt = time.Now().Unix()
// 终点:覆盖每个订单的有效期,取各订单 min(过期时间, 当前时间) 的最大值
now := time.Now()
endAt = startAt
for _, o := range pending {
if o.ExpiredAt.Before(time.Now()) && o.ExpiredAt.Unix() > startAt {
endAt = o.ExpiredAt.Unix()
end := o.ExpiredAt
if end.After(now) {
end = now
}
if end.Unix() > endAt {
endAt = end.Unix()
}
}
ok = true
// 标记这批订单已回溯,后续不再重复触发
for _, o := range pending {
lookbackDone.Store(o.ID, struct{}{})
}
return
}
func markLookbackDone(orderIDs []int64) {
for _, orderID := range orderIDs {
lookbackDone.Store(orderID, struct{}{})
}
}
func expireWaitingOrders() {
for _, t := range model.GetOrderByStatus(model.OrderStatusWaiting) {
if time.Now().Unix() < t.ExpiredAt.Unix() {
@@ -346,7 +380,7 @@ func expireWaitingOrders() {
}
t.SetExpired()
notify.Bepusdt(t)
notify.Vupay(t)
}
}
@@ -364,7 +398,7 @@ func getConfirmingOrders(tradeType []model.TradeType) []model.Order {
if time.Now().Unix() >= order.ExpiredAt.Unix() {
if order.ConfirmedAt == nil || order.ConfirmedAt.IsZero() || !order.ConfirmedAt.Before(order.ExpiredAt) {
order.SetFailed()
notify.Bepusdt(order)
notify.Vupay(order)
continue
}
@@ -382,16 +416,21 @@ func amountMatch(amount decimal.Decimal, target, tradeType string) bool {
case model.Classic:
return amount.String() == target
case model.HasPrefix:
s := amount.String()
if !strings.HasPrefix(s, target) {
t, err := decimal.NewFromString(target)
if err != nil {
log.Warn(err.Error())
return false
}
rest := s[len(target):]
if rest == "" {
return true
// 订单金额去掉了末尾的 0(1.50 存为 1.5),直接按字符串比前缀会让 1.5 的订单吃掉 1.51 的付款;
// 按原子精度和订单金额小数位中的较大者截断实付金额再精确比较,只容忍精度以下的多付
_, precision := model.GetAtomicity(model.TradeType(tradeType))
if p := abs(t.Exponent()); p > precision {
precision = p
}
return strings.Contains(target, ".") || strings.HasPrefix(rest, ".")
return amount.Truncate(precision).Equal(t)
case model.RoundOff:
t, err := decimal.NewFromString(target)
if err != nil {
+72
View File
@@ -0,0 +1,72 @@
package task
import (
"fmt"
"testing"
"time"
"git.viaeon.com/admin/vupay/app/conf"
"git.viaeon.com/admin/vupay/app/model"
)
func TestPendingLookbackUnixCoversEveryOrderWindow(t *testing.T) {
type window struct {
created, expired time.Duration // 相对当前时间
status int
}
tests := []struct {
name string
orders []window
wantEnd time.Duration
}{
{
name: "expired and waiting",
orders: []window{{-40 * time.Minute, -30 * time.Minute, model.OrderStatusExpired}, {-5 * time.Minute, 5 * time.Minute, model.OrderStatusWaiting}},
wantEnd: 0,
},
{
name: "earlier order expires later",
orders: []window{{-60 * time.Minute, -10 * time.Minute, model.OrderStatusExpired}, {-40 * time.Minute, -30 * time.Minute, model.OrderStatusExpired}},
wantEnd: -10 * time.Minute,
},
{
name: "all waiting",
orders: []window{{-5 * time.Minute, 5 * time.Minute, model.OrderStatusWaiting}},
wantEnd: 0,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
initTaskTestEnv(t, map[model.ConfKey]string{model.PaymentLookbackHour: "3"})
lookbackDone.Clear()
now := time.Now()
for i, w := range tt.orders {
createTestOrder(t, model.Order{
OrderId: fmt.Sprintf("merchant-order-%d", i),
TradeId: fmt.Sprintf("trade-order-%d", i),
TradeType: model.UsdcSolana,
Rate: "7.00",
Amount: fmt.Sprintf("1.%02d", i),
Money: "7.00",
Address: "GpsvqTPP7triXkqH8mVtXEM6at9DJ41UHy5dYPTFe16H",
Status: w.status,
ApiType: model.OrderApiTypeVupay,
ExpiredAt: now.Add(w.expired),
}, now.Add(w.created))
}
startAt, endAt, orderIDs, ok := pendingLookbackUnix(conf.Solana)
if !ok || len(orderIDs) != len(tt.orders) {
t.Fatalf("ok = %v, orders = %d, want %d", ok, len(orderIDs), len(tt.orders))
}
if want := now.Add(tt.orders[0].created).Unix(); startAt != want {
t.Fatalf("startAt = %d, want %d", startAt, want)
}
if want := now.Add(tt.wantEnd).Unix(); endAt < want-1 || endAt > want+1 {
t.Fatalf("endAt is %s before now, want %s", now.Sub(time.Unix(endAt, 0)).Round(time.Second), -tt.wantEnd)
}
})
}
}
+5 -5
View File
@@ -9,17 +9,17 @@ import (
"sync"
"time"
"git.viaeon.com/admin/vupay/app/conf"
blockapi "git.viaeon.com/admin/vupay/app/core"
"git.viaeon.com/admin/vupay/app/log"
"git.viaeon.com/admin/vupay/app/model"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/btcsuite/btcd/btcutil/base58"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/panjf2000/ants/v2"
"github.com/shopspring/decimal"
"github.com/smallnest/chanx"
"github.com/spf13/cast"
"github.com/v03413/bepusdt/app/conf"
blockapi "github.com/v03413/bepusdt/app/core"
"github.com/v03413/bepusdt/app/log"
"github.com/v03413/bepusdt/app/model"
"github.com/v03413/bepusdt/app/utils"
"github.com/v03413/tronprotocol/api"
"github.com/v03413/tronprotocol/core"
"google.golang.org/grpc"
+2 -2
View File
@@ -4,9 +4,9 @@ import (
"context"
"time"
"git.viaeon.com/admin/vupay/app/conf"
"git.viaeon.com/admin/vupay/app/utils"
"github.com/smallnest/chanx"
"github.com/v03413/bepusdt/app/conf"
"github.com/v03413/bepusdt/app/utils"
)
func xlayerInit() {
+11
View File
@@ -2,6 +2,7 @@ package utils
import (
"context"
"strings"
"time"
"github.com/xssnick/tonutils-go/address"
@@ -10,6 +11,16 @@ import (
"github.com/xssnick/tonutils-go/ton/jetton"
)
func IsValidTonAddress(value string) bool {
if !strings.HasPrefix(value, "UQ") {
return false
}
_, err := address.ParseAddr(value)
return err == nil
}
func NewTonClient(configUrl string) tgo.APIClientWrapped {
pool := liteclient.NewConnectionPool()
if err := pool.AddConnectionsFromConfigUrl(context.Background(), configUrl); err != nil {
+30 -1
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"math"
"math/big"
"net"
"net/http"
"net/url"
"os"
@@ -17,6 +18,7 @@ import (
"unicode"
"github.com/btcsuite/btcd/btcutil/base58"
"github.com/gin-gonic/gin"
nid "github.com/matoous/go-nanoid/v2"
)
@@ -36,7 +38,7 @@ func IsExist(path string) bool {
return false
}
func EpusdtSign(data map[string]interface{}, token string) string {
func VupaySign(data map[string]interface{}, token string) string {
keys := make([]string, 0, len(data))
for k := range data {
if k == "signature" {
@@ -253,3 +255,30 @@ func GetRequestHost(r *http.Request) string {
return scheme + "://" + r.Host
}
// ClientFingerprint 客户端指纹
func ClientFingerprint(ctx *gin.Context) string {
ip := ctx.ClientIP()
if parsed := net.ParseIP(ip); parsed != nil {
if v4 := parsed.To4(); v4 != nil {
ip = fmt.Sprintf("%d.%d.%d.0", v4[0], v4[1], v4[2])
} else if v6 := parsed.To16(); v6 != nil {
var masked [16]byte
copy(masked[:8], v6[:8])
ip = net.IP(masked[:]).String()
}
}
parts := []string{
ip,
ctx.GetHeader("User-Agent"),
ctx.GetHeader("Accept-Language"),
ctx.GetHeader("Accept-Encoding"),
ctx.GetHeader("Accept"),
ctx.GetHeader("Sec-CH-UA"),
ctx.GetHeader("Sec-CH-UA-Platform"),
}
return StrSha256(strings.Join(parts, "|"))
}
+35
View File
@@ -0,0 +1,35 @@
# VUPAY(SQLite 版)—— 单机最简部署
#
# 用法:
# 1) docker login git.viaeon.com # 私有镜像仓库,用 Gitea 账号/token
# 2) docker compose up -d
# 3) 浏览器打开 http://服务器IP:8080 走安装向导(记下「安全入口」和后台账号)
#
# 关键点:
# - SQLite 数据库在容器内 /var/lib/vupay/sqlite.db,必须挂出来,否则删容器=丢单
# - 日志在 /var/log/vupay/,也挂出来,排查掉单要靠它
# - 默认 LISTEN 就是 :8080(0.0.0.0),容器内不用改;要只让反代访问就绑 127.0.0.1
services:
vupay:
image: git.viaeon.com/admin/vupay:latest # 想用官方镜像就换成 admin/vupay:latest
container_name: vupay
restart: unless-stopped
ports:
# 前面有 Nginx/Caddy 反代时绑本机,别把后台裸奔在公网
- "127.0.0.1:8080:8080"
# 没有反代、想直接 IP:端口 访问,就用下面这行替换上面那行:
# - "8080:8080"
environment:
TZ: Asia/Shanghai
LISTEN: ":8080"
SQLITE: /var/lib/vupay/sqlite.db
LOG: /var/log/vupay/
volumes:
- ./data:/var/lib/vupay # sqlite.db 就在这里
- ./logs:/var/log/vupay
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
+88
View File
@@ -0,0 +1,88 @@
# VUPAY + MySQL 8 —— 需要 MySQL 的场景
#
# 注意:这是**本仓库(admin/VUPAY)加了 MySQL 支持之后**才能用的写法。
# 上游 admin/vupay 的代码只有 SQLite 和 PostgreSQL,文档里那段 MYSQL_DSN 是过期内容。
# 镜像:git.viaeon.com/admin/vupay:latest(>= e7a8dd9)
#
# 用法:
# echo "DB_ROOT_PASSWORD=$(openssl rand -base64 24 | tr -d '/+=')" > .env
# echo "DB_PASSWORD=$(openssl rand -base64 24 | tr -d '/+=')" >> .env
# docker login git.viaeon.com
# docker compose -f docker-compose.mysql.yml up -d
#
# 关于共享:MySQL 服务名/容器名都叫 `mysql`,挂在 external 网络 `shared-db` 上,
# 这样同机的其它容器也能用 `mysql:3306` 复用它(每个应用给独立库 + 独立账号)。
# 没有这个网络就先建:docker network create shared-db
# 如果你用 AcePanel 面板,把下面的 `shared-db` 换成 `acepanel-network` 即可
# (那是面板自带的共享网络,面板创建的容器都在里面)。
services:
mysql:
image: mysql:8.0
container_name: mysql
restart: unless-stopped
command:
- --character-set-server=utf8mb4
- --collation-server=utf8mb4_unicode_ci
- --default-time-zone=+08:00
# 小机器(1~2G 内存)建议打开下面三行,省内存也省 CPU
# - --innodb-buffer-pool-size=256M
# - --performance-schema=OFF
# - --disable-log-bin
# - --slow-query-log=ON # 慢查询落 ./mysqldata/<host>-slow.log
# - --long-query-time=1
environment:
MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:?先把 DB_ROOT_PASSWORD 写进 .env}
MYSQL_DATABASE: vupay
MYSQL_USER: vupay
MYSQL_PASSWORD: ${DB_PASSWORD:?先把 DB_PASSWORD 写进 .env}
TZ: Asia/Shanghai
volumes:
- ./mysqldata:/var/lib/mysql
ports:
# 只绑本机:宿主机命令行 / SSH 隧道能用,公网访问不到
- "127.0.0.1:3306:3306"
networks:
- shared-db
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-u", "root", "-p$${DB_ROOT_PASSWORD}"]
interval: 10s
timeout: 5s
retries: 12
start_period: 40s
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
vupay:
image: git.viaeon.com/admin/vupay:latest
container_name: vupay
restart: unless-stopped
depends_on:
mysql:
condition: service_healthy
ports:
- "127.0.0.1:8080:8080"
networks:
- shared-db
environment:
TZ: Asia/Shanghai
LISTEN: ":8080"
LOG: /var/log/vupay/
# DSN 三个参数别省:charset=utf8mb4(中文)、parseTime=True(时间列)、loc=Local(时区)
# host 用服务名 mysql(同类容器里写 127.0.0.1 会指向容器自身)
MYSQL_DSN: vupay:${DB_PASSWORD}@tcp(mysql:3306)/vupay?charset=utf8mb4&parseTime=True&loc=Local&timeout=5s&readTimeout=10s&writeTimeout=10s
volumes:
- ./logs:/var/log/vupay
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
networks:
# 用面板(AcePanel)就把名字换成 acepanel-network,同样写 external: true
shared-db:
external: true
+52
View File
@@ -0,0 +1,52 @@
# VUPAY + PostgreSQL —— 生产推荐
#
# 说明:官方文档里那套 MySQL 写法是**过期的**(代码里已经没有任何 MySQL 分支),
# 现在只支持 SQLite 和 PostgreSQL 两种。数据量大/要多实例就看这份。
#
# 用法:
# echo "DB_PASSWORD=$(openssl rand -base64 24 | tr -d '/+=')" > .env
# docker login git.viaeon.com
# docker compose -f docker-compose.postgres.yml up -d
services:
db:
image: postgres:18-alpine
container_name: vupay-db
restart: unless-stopped
environment:
POSTGRES_DB: vupay
POSTGRES_USER: vupay
POSTGRES_PASSWORD: ${DB_PASSWORD:?先把 DB_PASSWORD 写进 .env}
TZ: Asia/Shanghai
volumes:
- ./pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U vupay -d vupay"]
interval: 10s
timeout: 5s
retries: 10
# 数据库不要暴露到公网
expose:
- "5432"
vupay:
image: git.viaeon.com/admin/vupay:latest
container_name: vupay
restart: unless-stopped
depends_on:
db:
condition: service_healthy
ports:
- "127.0.0.1:8080:8080"
environment:
TZ: Asia/Shanghai
LISTEN: ":8080"
LOG: /var/log/vupay/
POSTGRESQL_DSN: postgres://vupay:${DB_PASSWORD}@db:5432/vupay?sslmode=disable&connect_timeout=3&timezone=Asia/Shanghai
volumes:
- ./logs:/var/log/vupay
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"

Some files were not shown because too many files have changed in this diff Show More