Compare commits

..
Author SHA1 Message Date
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
16 changed files with 700 additions and 62 deletions
+82
View File
@@ -0,0 +1,82 @@
name: Docker Build (Gitea)
on:
push:
branches:
- main
- 'ci/**'
tags:
- 'v*'
workflow_dispatch:
env:
REGISTRY: git.viaeon.com
IMAGE: git.viaeon.com/admin/bepusdt
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: |
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 }}" \
-t "${{ env.IMAGE }}:${{ steps.ver.outputs.short_sha }}" \
-t "${{ env.IMAGE }}:${{ steps.ver.outputs.ref_slug }}" \
-t "${{ env.IMAGE }}:latest" .
- 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
docker push "${{ env.IMAGE }}:latest" 2>&1
- name: Summary
run: |
echo "镜像已推送:"
echo " ${{ env.IMAGE }}:${{ steps.ver.outputs.short_sha }}"
echo " ${{ env.IMAGE }}:${{ steps.ver.outputs.ref_slug }}"
echo " ${{ env.IMAGE }}:latest"
+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 -1
View File
@@ -9,4 +9,5 @@ dist/
static/web
static/secure
*.log
AGENTS.md
AGENTS.md
CLAUDE.md
+1
View File
@@ -82,6 +82,7 @@ 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)
- **安全问题反馈/联系作者**:[contact@bepusdt.online](mailto:contact@bepusdt.online)
## 🙏 致谢
+1 -1
View File
@@ -108,7 +108,7 @@ const (
)
const (
Classic MatchMode = "classic" // 经典模式,精确匹配
HasPrefix MatchMode = "has_prefix" // 前缀匹配,允许多付
HasPrefix MatchMode = "has_prefix" // 前缀匹配,按原子精度截断后比较,只容忍精度以下的多付
RoundOff MatchMode = "round_off" // 数值修约,四舍五入,允许容错
)
+60
View File
@@ -0,0 +1,60 @@
package task
import (
"testing"
"github.com/shopspring/decimal"
"github.com/v03413/bepusdt/app/model"
)
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)
}
}
}
+69 -7
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"math/big"
@@ -37,6 +38,7 @@ type solana struct {
retryMu sync.Mutex
retryAttempts map[int]int
retryScheduled map[int]*time.Timer
retryStopped map[int]struct{}
lookbackMu sync.Mutex
lookbackNext int
lookbackEnd int
@@ -67,6 +69,7 @@ func newSolana() solana {
client: utils.NewHttpClient(),
retryAttempts: make(map[int]int),
retryScheduled: make(map[int]*time.Timer),
retryStopped: make(map[int]struct{}),
}
}
@@ -82,7 +85,7 @@ func (s *solana) syncSlotForward(ctx context.Context) {
return
}
if s.pendingSlotRetryCount() > 0 {
if s.pendingSlotRetryCount() >= solanaForwardPauseRetries {
return
}
@@ -199,6 +202,13 @@ func (s *solana) slotParse(n any) {
}
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))
return
}
if err != nil {
conf.RecordFailure(network)
s.scheduleSlotRetry(slot)
@@ -334,10 +344,14 @@ func solanaSignatureFinalized(status gjson.Result) bool {
// 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")
@@ -348,6 +362,8 @@ func validateSolanaBlockResponse(body []byte) (gjson.Result, error) {
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)
@@ -366,6 +382,11 @@ func validateSolanaBlockResponse(body []byte) (gjson.Result, error) {
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()
@@ -400,6 +421,24 @@ func (s *solana) scheduleSlotRetry(slot int) {
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()
@@ -421,6 +460,10 @@ func (s *solana) pendingSlotRetryCount() int {
// 单个 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 {
@@ -544,13 +587,28 @@ 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
}
s.lookbackMu.Lock()
defer s.lookbackMu.Unlock()
if s.lookbackNext == 0 {
startAt, endAt, orderIDs, ok := pendingLookbackUnix(conf.Solana)
if !ok {
@@ -581,12 +639,16 @@ func (s *solana) lookbackSlots(ctx context.Context) {
if s.lookbackNext > s.lookbackEnd {
markLookbackDone(s.lookbackOrderIDs)
s.lookbackNext = 0
s.lookbackEnd = 0
s.lookbackOrderIDs = nil
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
}
+72
View File
@@ -0,0 +1,72 @@
package task
import (
"fmt"
"sync/atomic"
"testing"
"time"
"github.com/v03413/bepusdt/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)
}
}
+101
View File
@@ -0,0 +1,101 @@
package task
import (
"testing"
"time"
"github.com/v03413/bepusdt/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.OrderApiTypeEpusdt,
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)
}
}
+98
View File
@@ -0,0 +1,98 @@
package task
import (
"errors"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"github.com/v03413/bepusdt/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")
}
}
+1 -1
View File
@@ -31,7 +31,7 @@ func (s *solana) stopSlotRetryTimers() {
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":-32001,"message":"Block 457000000 cleaned up, does not exist on node. First available block: 457100000"},"id":1}`))
_, _ = 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})
+36 -28
View File
@@ -305,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()
@@ -324,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
}
@@ -359,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),
@@ -368,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,
+124
View File
@@ -0,0 +1,124 @@
package task
import (
"testing"
"github.com/v03413/bepusdt/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)
}
}
}
+27 -7
View File
@@ -3,7 +3,6 @@ package task
import (
"context"
"fmt"
"strings"
"sync"
"time"
@@ -293,6 +292,22 @@ 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 {
@@ -401,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 {
+2 -1
View File
@@ -212,7 +212,8 @@ key := t.Address + string(t.TradeType)
┌──────────────────────────────────────────────────────────────────┐
│ 模式二:HasPrefix(前缀匹配 / 允许多付) │
│ │
│ 规则:实际到账金额以订单金额为前缀,允许多付小数 │
│ 规则:订单金额按原子精度补齐小数位后,作为实际到账金额的前缀 │
│ (1.5 补成 1.50),只容忍原子精度以下的多付 │
│ │
│ 订单金额:10.01 │
│ 到账金额:10.01 ✅ 匹配(完全等于) │
+23 -15
View File
@@ -25,25 +25,33 @@
## 前缀匹配
如同名字一般,前缀匹配模式会将两个交易金额转换成字符串,然后从左到右逐位进行对比。
如果订单金额字符串是实际交易金额字符串的前缀,则认为是匹配成功。
订单金额按原子精度补齐小数位(如 `atom_usdt = 0.01` 时 1.5 写成 1.50),如果它是实际交易金额的前缀,则认为是匹配成功。
实现上等价于:把实际交易金额按原子精度直接截断(不四舍五入),再与订单金额精确比较。
只容忍原子精度以下的多付;少付、或多付达到一个原子精度,都会匹配失败。
**适用场景:**
- 某些支付渠道可能会在金额末尾添加额外的小数位
- 用户可能因为汇率波动或手续费问题支付了稍多的金额
- 需要更灵活的金额匹配策略
- 用户转账时在原子精度以下多带了几位小数(如应付 1.50,实付 1.50123)
- 同一地址同时有多笔等待支付的订单:系统按原子精度递增订单金额(1.50、1.51 …),
每笔付款只会匹配其中一笔,不会把 1.51 的付款匹配给 1.50 的订单
**举例:**
**举例(原子精度 0.01):**
| 订单金额 | 实际交易金额 | 匹配结果 | 说明 |
|--------|------------|--------|-----------------------------|
| 100 | 100.5 | ✅ 匹配成功 | "100" 是 "100.5" 的前缀 |
| 100.5 | 100.56 | ✅ 匹配成功 | "100.5" 是 "100.56" 的前缀 |
| 99.9 | 99.99 | ✅ 匹配成功 | "99.9" 是 "99.99" 的前缀 |
| 100 | 99.99 | ❌ 匹配失败 | "100" 不是 "99.99" 的前缀 |
| 100.5 | 100.4 | ❌ 匹配失败 | "100.5" 不是 "100.4" 的前缀 |
| 123.45 | 123.456789 | ✅ 匹配成功 | "123.45" 是 "123.456789" 的前缀 |
| 订单金额 | 实际交易金额 | 匹配结果 | 说明 |
|--------|------------|--------|-------------------------------|
| 1.50 | 1.50 | ✅ 匹配成功 | 金额一致 |
| 1.50 | 1.50123 | ✅ 匹配成功 | "1.50" 是 "1.50123" 的前缀 |
| 1.50 | 1.509 | ✅ 匹配成功 | 截断不进位,第三位起的多付被忽略 |
| 1.50 | 1.51 | ❌ 匹配失败 | 属于 1.51 的订单 |
| 1.50 | 1.4999 | ❌ 匹配失败 | 少付 |
| 100.00 | 100.5 | ❌ 匹配失败 | 多付达到原子精度,"100.00" 不是 "100.50" 的前缀 |
| 123.45 | 123.456789 | ✅ 匹配成功 | "123.45" 是 "123.456789" 的前缀 |
订单金额小数位多于当前原子精度时(例如修改原子精度前创建的订单),按订单金额自己的小数位补齐和截断。
> 早期版本直接拿订单金额字符串做前缀比较。订单金额保存时会去掉末尾的 0(1.50 存为 `"1.5"`,2.00 存为 `"2"`),
> 而 `"1.5"` 是 `"1.51"` 的前缀、`"2"` 是 `"2.01"` 的前缀,同一地址有多笔订单时,后建订单的付款会被先建的订单匹配走。
> 现在改为按原子精度补齐后比较,多付达到一个原子精度(如订单 100,实付 100.5)不再匹配。
---
@@ -81,7 +89,7 @@
## 选择建议
- **传统模式**:适合金额固定、对准确性要求高的场景
- **前缀匹配**:适合仅允许用户多付、可能添加额外精度的场景
- **前缀匹配**:适合只容忍原子精度以下多付、同一地址可能同时有多笔订单的场景
- **修约匹配**:适合允许用户多付或者少付,容忍度更高的场景
根据实际业务需求选择合适的匹配模式,可以在保证安全性的同时提升用户体验。