Compare commits

...

2 Commits

Author SHA1 Message Date
753bd4a4d6 增加主动查询 api 2026-02-03 15:05:06 +08:00
922f6df4e8 fix bugs 2026-02-03 13:07:29 +08:00
6 changed files with 489 additions and 109 deletions

109
README.md
View File

@@ -1,75 +1,94 @@
# USDTMan
TRON USDT TRC20 收款监听服务 - 基于交易记录扫描 + 区块确认数验证
TRON USDT TRC20 收款监听服务
## 功能
## 特性
- 实时监听多个 TRON 地址的 USDT 收款
- 区块确认数验证默认6个确认
- WebSocket 实时推送收款通知
- HTTP API 管理监听地址
- 扫描交易记录 + 区块确认数验证(默认 >= 6
- 支持 `big.Int` 处理任意金额
- WebSocket 实时推送
- 主动查询历史交易(时间/金额/确认数过滤)
- 代理支持
## API 使用方式
## 使用
```go
// 创建监听器(配置对象方式)
uman := usdtman.NewUSDTMan(usdtman.Config{
Addresses: []string{"地址1", "地址2"},
Addresses: []string{"TN8nJ...", "TXYZo..."},
APIKey: "YOUR_API_KEY",
QueryInterval: 5 * time.Second, // 查询间隔(可选,默认 5 秒)
MinConfirmations: 6, // 最小确认数(可选,默认 6
MaxHistoryTxns: 20, // 查询历史交易数(可选,默认 20
ProxyURL: "http://127.0.0.1:7890", // HTTP/SOCKS5 代理(可选
QueryInterval: 5 * time.Second, // 查询间隔
MinConfirmations: 6, // 最小确认数
MaxHistoryTxns: 20, // 监听查询数量
ProxyURL: "http://127.0.0.1:7890", // 可选
})
// 或者使用自定义 Transport
uman := usdtman.NewUSDTMan(usdtman.Config{
Addresses: []string{"地址1"},
APIKey: "YOUR_API_KEY",
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
// 其他自定义配置...
},
})
// 设置收款回调
uman.OnPaymentComplete(func(payment *usdtman.USDTPayment) {
fmt.Printf("收到 %.6f USDT确认: %d\n", payment.Amount, payment.Confirmations)
fmt.Printf("收到 %s USDT (确认: %d)\n",
payment.GetAmountString(), payment.Confirmations)
})
// 启动监听
uman.Start()
defer uman.Stop()
// 停止监听
uman.Stop()
// 动态添加/移除地址
uman.AddAddress("新地址")
uman.RemoveAddress("旧地址")
// 主动查询历史
payments, _ := uman.QueryTransactions(usdtman.QueryFilter{
Address: "TN8nJ...",
StartTime: startTimestamp, // 毫秒
EndTime: endTimestamp, // 毫秒
MinAmount: big.NewInt(10000000), // >= 10 USDT
MinConfirmations: 6,
Limit: 50,
})
```
## 运行
## 运行 HTTP Server
```bash
cd cmd/server
go run main.go
PROXY_URL=http://127.0.0.1:7890 go run main.go
```
访问 http://localhost:8084
## 接口
## HTTP API
- `POST /start` - 启动监听
- `POST /stop` - 停止监听
- `POST /add-address` - 添加监听地址
- `POST /stop` - 停止监听
- `POST /add-address` - 添加地址
- `POST /remove-address` - 移除地址
- `GET /list-addresses` - 列出所有地址
- `GET /payments` - 获取收款历史
- `WS /ws` - WebSocket 连接
- `GET /list-addresses` - 地址列表
- `GET /payments` - 监听缓存记录最多100条
- `POST /query` - 主动查询历史
- `WS /ws` - WebSocket 推送
## 确认机制
### 主动查询示例
- 扫描地址的最近交易记录
- 计算区块确认数(当前区块 - 交易区块)
- 仅在确认数 >= 6 时触发回调
- 自动去重,避免重复处理
```bash
curl -X POST http://localhost:8084/query \
-H "Content-Type: application/json" \
-d '{
"address": "TN8nJ...",
"startTime": 1770000000000,
"endTime": 1770100000000,
"minAmount": "10000000",
"minConfirmations": 6,
"limit": 50
}'
```
## 配置项
| 参数 | 类型 | 默认 | 说明 |
|------|------|------|------|
| `Addresses` | []string | [] | 监听地址 |
| `APIKey` | string | - | TronGrid API Key |
| `QueryInterval` | time.Duration | 5s | 查询间隔 |
| `MinConfirmations` | int64 | 6 | 最小确认数 |
| `MaxHistoryTxns` | int | 20 | 监听查询数量 |
| `ProxyURL` | string | - | HTTP/SOCKS5 代理 |
| `Transport` | http.RoundTripper | nil | 自定义 Transport |
## 监听 vs 查询
- **监听** (`/payments`): 自动轮询最近交易,达到确认数后触发回调,缓存最多 100 条
- **查询** (`/query`): 主动查询链上历史,支持条件过滤,不触发回调

View File

@@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"log"
"math/big"
"net/http"
"os"
"sync"
@@ -56,8 +57,8 @@ func main() {
// 设置收款回调
uman.OnPaymentComplete(func(payment *usdtman.USDTPayment) {
log.Printf("💰 收到 USDT: %s -> %.6f USDT (确认数: %d, TxID: %s)",
payment.From, payment.Amount, payment.Confirmations, payment.TxID)
log.Printf("💰 收到 USDT: %s -> %s USDT (确认数: %d, TxID: %s)",
payment.From, payment.GetAmountString(), payment.Confirmations, payment.TxID)
paymentLock.Lock()
paymentEvents = append(paymentEvents, *payment)
@@ -69,12 +70,17 @@ func main() {
broadcastPayment(payment)
})
// test code
uman.AddAddress("TWwGSYwpSzT6GTBr4AQw9QF6m4VVui3UGc") // tronlink trc20 gasfree 地址
uman.Start()
http.HandleFunc("/start", startMonitor)
http.HandleFunc("/stop", stopMonitor)
http.HandleFunc("/add-address", addAddress)
http.HandleFunc("/remove-address", removeAddress)
http.HandleFunc("/list-addresses", listAddresses)
http.HandleFunc("/payments", getPayments)
http.HandleFunc("/query", queryTransactions)
http.HandleFunc("/ws", handleWebSocket)
http.HandleFunc("/", serveIndex)
@@ -192,6 +198,59 @@ func getPayments(w http.ResponseWriter, r *http.Request) {
})
}
func queryTransactions(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
jsonResponse(w, false, "Method not allowed", nil)
return
}
var req struct {
Address string `json:"address"`
StartTime int64 `json:"startTime"` // 毫秒时间戳
EndTime int64 `json:"endTime"` // 毫秒时间戳
MinAmount string `json:"minAmount"` // 字符串格式的金额
MinConfirmations int64 `json:"minConfirmations"` // 最小确认数
Limit int `json:"limit"` // 查询数量
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonResponse(w, false, "invalid request", nil)
return
}
if req.Address == "" {
jsonResponse(w, false, "address is required", nil)
return
}
filter := usdtman.QueryFilter{
Address: req.Address,
StartTime: req.StartTime,
EndTime: req.EndTime,
MinConfirmations: req.MinConfirmations,
Limit: req.Limit,
}
// 解析最小金额
if req.MinAmount != "" {
minAmount := new(big.Int)
if _, ok := minAmount.SetString(req.MinAmount, 10); ok {
filter.MinAmount = minAmount
}
}
payments, err := uman.QueryTransactions(filter)
if err != nil {
jsonResponse(w, false, fmt.Sprintf("查询失败: %v", err), nil)
return
}
jsonResponse(w, true, "success", map[string]interface{}{
"payments": payments,
"count": len(payments),
})
}
func handleWebSocket(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
@@ -222,7 +281,8 @@ func broadcastPayment(payment *usdtman.USDTPayment) {
message := map[string]interface{}{
"type": "usdt_payment",
"address": payment.Address,
"amount": payment.Amount,
"amount": payment.GetAmountFloat(),
"amountRaw": payment.Amount.String(),
"from": payment.From,
"txId": payment.TxID,
"block": payment.BlockNumber,

View File

@@ -34,11 +34,23 @@
</div>
<div class="section">
<h3>收款记录</h3>
<h3>收款记录(监听缓存)</h3>
<button onclick="getPayments()">刷新</button>
<div id="payments"></div>
</div>
<div class="section">
<h3>主动查询交易记录</h3>
<input type="text" id="queryAddress" placeholder="TRON 地址">
<input type="datetime-local" id="startTime" placeholder="开始时间">
<input type="datetime-local" id="endTime" placeholder="结束时间">
<input type="number" id="minAmount" placeholder="最小金额 (USDT)" step="0.01">
<input type="number" id="minConfirmations" placeholder="最小确认数" value="6">
<input type="number" id="queryLimit" placeholder="查询数量" value="50">
<button onclick="queryTransactions()">查询</button>
<div id="queryResults"></div>
</div>
<div class="section">
<h3>实时日志 (WebSocket)</h3>
<div id="log"></div>
@@ -125,6 +137,52 @@
}
}
async function queryTransactions() {
const address = document.getElementById('queryAddress').value.trim();
if (!address) {
alert('请输入地址');
return;
}
const startTime = document.getElementById('startTime').value;
const endTime = document.getElementById('endTime').value;
const minAmount = document.getElementById('minAmount').value;
const minConfirmations = document.getElementById('minConfirmations').value;
const limit = document.getElementById('queryLimit').value;
const body = {
address: address,
startTime: startTime ? new Date(startTime).getTime() : 0,
endTime: endTime ? new Date(endTime).getTime() : 0,
minAmount: minAmount ? (parseFloat(minAmount) * 1000000).toString() : '',
minConfirmations: parseInt(minConfirmations) || 0,
limit: parseInt(limit) || 50,
};
const res = await fetch('/query', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
const data = await res.json();
if (data.success && data.data.payments && data.data.payments.length > 0) {
const html = '<div class="success">找到 ' + data.data.count + ' 条记录</div>' +
'<table><tr><th>时间</th><th>金额</th><th>来源</th><th>确认数</th><th>TxID</th></tr>' +
data.data.payments.map(p =>
'<tr><td>' + new Date(p.Timestamp).toLocaleString() + '</td>' +
'<td>' + p.Amount.toFixed(6) + ' USDT</td>' +
'<td>' + p.From.substring(0, 10) + '...</td>' +
'<td>' + p.Confirmations + '</td>' +
'<td><a href="https://tronscan.org/#/transaction/' + p.TxID + '" target="_blank">' +
p.TxID.substring(0, 10) + '...</a></td></tr>'
).join('') + '</table>';
document.getElementById('queryResults').innerHTML = html;
} else {
document.getElementById('queryResults').innerHTML = '<div class="error">' + (data.message || '未找到记录') + '</div>';
}
}
listAddresses();
getPayments();
</script>

27
log/blocks.json Normal file
View File

@@ -0,0 +1,27 @@
{
"id": "2bf9c73deb56166ad38906e732a898646cfc3db15e0daab0e33a6c4e3bf0509e",
"blockNumber": 79809798,
"blockTimeStamp": 1770093843000,
"contractResult": [
"0000000000000000000000000000000000000000000000000000000000000000"
],
"contract_address": "41a614f803b6fd780986a42c78ec9c7f77e6ded13c",
"receipt": {
"energy_usage": 130285,
"energy_usage_total": 130285,
"net_usage": 345,
"result": "SUCCESS",
"energy_penalty_total": 100635
},
"log": [
{
"address": "a614f803b6fd780986a42c78ec9c7f77e6ded13c",
"topics": [
"ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
"0000000000000000000000006158fe96b950111b8f1f31249fedda484e941312",
"000000000000000000000000e5fcae42ed4ecf7e23e4a561aded72c69aeeabc0"
],
"data": "0000000000000000000000000000000000000000000000000000000000ca54e0"
}
]
}

23
log/transactions.json Normal file
View File

@@ -0,0 +1,23 @@
{
"data": [
{
"transaction_id": "2bf9c73deb56166ad38906e732a898646cfc3db15e0daab0e33a6c4e3bf0509e",
"token_info": {
"symbol": "USDT",
"address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"decimals": 6,
"name": "Tether USD"
},
"block_timestamp": 1770093843000,
"from": "TJqwA7SoZnERE4zW5uDEiPkbz4B66h9TFj",
"to": "TWwGSYwpSzT6GTBr4AQw9QF6m4VVui3UGc",
"type": "Transfer",
"value": "13260000"
}
],
"success": true,
"meta": {
"at": 1770094054104,
"page_size": 1
}
}

View File

@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"io"
"math/big"
"net/http"
"net/url"
"strings"
@@ -40,10 +41,20 @@ type USDTMan struct {
httpClient *http.Client // HTTP 客户端
}
// QueryFilter 查询过滤条件
type QueryFilter struct {
Address string // 地址(必填)
StartTime int64 // 开始时间戳毫秒0 表示不限制
EndTime int64 // 结束时间戳毫秒0 表示不限制
MinAmount *big.Int // 最小金额micro USDTnil 表示不限制
MinConfirmations int64 // 最小确认数0 表示不限制
Limit int // 查询数量限制0 使用默认值
}
// USDTPayment USDT 收款信息
type USDTPayment struct {
Address string
Amount float64
Amount *big.Int // 原始金额micro USDT10^-6例如 13260000 = 13.26 USDT
TxID string
BlockNumber int64
Timestamp int64
@@ -51,23 +62,57 @@ type USDTPayment struct {
Confirmations int64
}
// TronGridTransaction 交易信息
// GetAmountFloat 获取浮点数金额USDT
func (p *USDTPayment) GetAmountFloat() float64 {
divisor := new(big.Float).SetInt64(1000000)
amount := new(big.Float).SetInt(p.Amount)
result := new(big.Float).Quo(amount, divisor)
f, _ := result.Float64()
return f
}
// GetAmountString 获取字符串金额USDT保留6位小数
func (p *USDTPayment) GetAmountString() string {
return fmt.Sprintf("%.6f", p.GetAmountFloat())
}
// MarshalJSON 自定义 JSON 序列化
func (p *USDTPayment) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Address string `json:"Address"`
Amount float64 `json:"Amount"`
AmountRaw string `json:"AmountRaw"`
TxID string `json:"TxID"`
BlockNumber int64 `json:"BlockNumber"`
Timestamp int64 `json:"Timestamp"`
From string `json:"From"`
Confirmations int64 `json:"Confirmations"`
}{
Address: p.Address,
Amount: p.GetAmountFloat(),
AmountRaw: p.Amount.String(),
TxID: p.TxID,
BlockNumber: p.BlockNumber,
Timestamp: p.Timestamp,
From: p.From,
Confirmations: p.Confirmations,
})
}
// TronGridTransaction TRC20 交易信息
type TronGridTransaction struct {
Ret []map[string]interface{} `json:"ret"`
TxID string `json:"txID"`
BlockNumber int64 `json:"blockNumber"`
BlockTimeStamp int64 `json:"block_timestamp"`
RawData struct {
Contract []struct {
Parameter struct {
Value struct {
Amount int64 `json:"amount"`
To string `json:"to_address"`
From string `json:"owner_address"`
} `json:"value"`
} `json:"parameter"`
} `json:"contract"`
} `json:"raw_data"`
TransactionID string `json:"transaction_id"`
BlockTimestamp int64 `json:"block_timestamp"`
From string `json:"from"`
To string `json:"to"`
Type string `json:"type"`
Value string `json:"value"`
TokenInfo struct {
Symbol string `json:"symbol"`
Address string `json:"address"`
Decimals int `json:"decimals"`
Name string `json:"name"`
} `json:"token_info"`
}
// TronGridAccountTransactions 账户交易列表
@@ -75,8 +120,8 @@ type TronGridAccountTransactions struct {
Success bool `json:"success"`
Data []TronGridTransaction `json:"data"`
Meta struct {
PageSize int `json:"page_size"`
Fingerprint string `json:"fingerprint"`
At int64 `json:"at"`
PageSize int `json:"page_size"`
} `json:"meta"`
}
@@ -221,28 +266,51 @@ func (m *USDTMan) checkAddress(address string) {
for _, txn := range transactions {
// 检查是否已处理
m.txnMutex.RLock()
processed := m.processedTxns[txn.TxID]
processed := m.processedTxns[txn.TransactionID]
m.txnMutex.RUnlock()
if processed {
continue
}
// 获取交易的区块号(需要通过 transaction_id 查询)
blockNumber, err := m.getTransactionBlock(txn.TransactionID)
if err != nil {
fmt.Printf("Error getting transaction block: %v\n", err)
continue
}
// 计算确认数
confirmations := currentBlock - txn.BlockNumber
confirmations := currentBlock - blockNumber
if confirmations < m.minConfirmations {
continue
}
// 解析交易数据
payment := m.parseTransaction(&txn, address, confirmations)
if payment == nil {
// 检查是否是转入该地址
if !strings.EqualFold(txn.To, address) {
continue
}
// 解析金额(使用 big.Int
amount := new(big.Int)
amount, ok := amount.SetString(txn.Value, 10)
if !ok || amount.Sign() <= 0 {
continue
}
payment := &USDTPayment{
Address: address,
Amount: amount,
TxID: txn.TransactionID,
BlockNumber: blockNumber,
Timestamp: txn.BlockTimestamp,
From: txn.From,
Confirmations: confirmations,
}
// 标记为已处理
m.txnMutex.Lock()
m.processedTxns[txn.TxID] = true
m.processedTxns[txn.TransactionID] = true
m.txnMutex.Unlock()
// 触发回调
@@ -293,6 +361,83 @@ func (m *USDTMan) getUSDTTransactions(address string) ([]TronGridTransaction, er
return result.Data, nil
}
// getUSDTTransactionsWithLimit 获取指定数量的交易
func (m *USDTMan) getUSDTTransactionsWithLimit(address string, limit int) ([]TronGridTransaction, error) {
url := fmt.Sprintf("%s/v1/accounts/%s/transactions/trc20?limit=%d&contract_address=%s&only_to=true",
TronGridAPI, address, limit, USDTContractAddress)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
if m.apiKey != "" {
req.Header.Set("TRON-PRO-API-KEY", m.apiKey)
}
resp, err := m.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("TronGrid API error: %d %s", resp.StatusCode, string(body))
}
var result TronGridAccountTransactions
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// getTransactionBlock 获取交易的区块号
func (m *USDTMan) getTransactionBlock(txID string) (int64, error) {
url := fmt.Sprintf("%s/wallet/gettransactioninfobyid?value=%s", TronGridAPI, txID)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return 0, err
}
if m.apiKey != "" {
req.Header.Set("TRON-PRO-API-KEY", m.apiKey)
}
resp, err := m.httpClient.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return 0, err
}
if resp.StatusCode != 200 {
return 0, fmt.Errorf("TronGrid API error: %d", resp.StatusCode)
}
var result struct {
BlockNumber int64 `json:"blockNumber"`
}
fmt.Println("body", string(body))
if err := json.Unmarshal(body, &result); err != nil {
return 0, err
}
return result.BlockNumber, nil
}
// getCurrentBlock 获取当前区块高度
func (m *USDTMan) getCurrentBlock() (int64, error) {
url := fmt.Sprintf("%s/wallet/getnowblock", TronGridAPI)
@@ -329,41 +474,7 @@ func (m *USDTMan) getCurrentBlock() (int64, error) {
return blockInfo.BlockHeader.RawData.Number, nil
}
// parseTransaction 解析交易
func (m *USDTMan) parseTransaction(txn *TronGridTransaction, targetAddress string, confirmations int64) *USDTPayment {
if len(txn.Ret) == 0 || txn.Ret[0]["contractRet"] != "SUCCESS" {
return nil
}
if len(txn.RawData.Contract) == 0 {
return nil
}
contract := txn.RawData.Contract[0]
value := contract.Parameter.Value
// 转换地址格式
to := value.To
from := value.From
// 检查是否是目标地址
if !strings.EqualFold(to, targetAddress) {
return nil
}
// USDT 是 6 位小数
amount := float64(value.Amount) / 1000000.0
return &USDTPayment{
Address: targetAddress,
Amount: amount,
TxID: txn.TxID,
BlockNumber: txn.BlockNumber,
Timestamp: txn.BlockTimeStamp,
From: from,
Confirmations: confirmations,
}
}
// parseTransaction 解析交易(已废弃,直接在 checkAddress 中处理)
// GetAddresses 获取所有监听地址
func (m *USDTMan) GetAddresses() []string {
@@ -402,3 +513,85 @@ func (m *USDTMan) RemoveAddress(address string) {
}
}
}
// QueryTransactions 主动查询交易记录(带过滤条件)
func (m *USDTMan) QueryTransactions(filter QueryFilter) ([]*USDTPayment, error) {
if filter.Address == "" {
return nil, fmt.Errorf("address is required")
}
// 设置默认 limit
limit := filter.Limit
if limit == 0 {
limit = m.maxHistoryTxns
}
// 获取交易列表
transactions, err := m.getUSDTTransactionsWithLimit(filter.Address, limit)
if err != nil {
return nil, err
}
// 获取当前区块(用于计算确认数)
currentBlock, err := m.getCurrentBlock()
if err != nil {
return nil, err
}
var results []*USDTPayment
for _, txn := range transactions {
// 时间过滤
if filter.StartTime > 0 && txn.BlockTimestamp < filter.StartTime {
continue
}
if filter.EndTime > 0 && txn.BlockTimestamp > filter.EndTime {
continue
}
// 只处理转入该地址的交易
if !strings.EqualFold(txn.To, filter.Address) {
continue
}
// 解析金额
amount := new(big.Int)
amount, ok := amount.SetString(txn.Value, 10)
if !ok || amount.Sign() <= 0 {
continue
}
// 金额过滤
if filter.MinAmount != nil && amount.Cmp(filter.MinAmount) < 0 {
continue
}
// 获取区块号
blockNumber, err := m.getTransactionBlock(txn.TransactionID)
if err != nil {
continue
}
// 计算确认数
confirmations := currentBlock - blockNumber
// 确认数过滤
if filter.MinConfirmations > 0 && confirmations < filter.MinConfirmations {
continue
}
payment := &USDTPayment{
Address: filter.Address,
Amount: amount,
TxID: txn.TransactionID,
BlockNumber: blockNumber,
Timestamp: txn.BlockTimestamp,
From: txn.From,
Confirmations: confirmations,
}
results = append(results, payment)
}
return results, nil
}