476 lines
12 KiB
Go
476 lines
12 KiB
Go
package task
|
|
|
|
import (
|
|
"context"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"sync"
|
|
"time"
|
|
|
|
"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"
|
|
)
|
|
|
|
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
|
|
blockScanQueue *chanx.UnboundedChan[uint32]
|
|
clientOnce sync.Once
|
|
api tgo.APIClientWrapped
|
|
}
|
|
|
|
var tn ton
|
|
|
|
func init() {
|
|
tn = ton{
|
|
blockScanQueue: chanx.NewUnboundedChan[uint32](context.Background(), 30),
|
|
}
|
|
|
|
Register(Task{Callback: tn.syncMBSeqnoForward})
|
|
Register(Task{Duration: time.Second, Callback: tn.blockDispatch})
|
|
Register(Task{Duration: time.Second * 3, Callback: tn.tradeConfirmHandle})
|
|
Register(Task{Duration: time.Second * 15, Callback: tn.lookbackBlocks})
|
|
}
|
|
|
|
func (t *ton) syncMBSeqnoForward(ctx context.Context) {
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
default:
|
|
}
|
|
|
|
if t.syncBreak() {
|
|
time.Sleep(time.Second * 3)
|
|
continue
|
|
}
|
|
|
|
// 初始化:首次获取当前最新高度作为起点
|
|
if t.lastBlockSeqno == 0 {
|
|
mb, err := t.client().CurrentMasterchainInfo(ctx)
|
|
if err != nil {
|
|
log.Task.Warn(fmt.Sprintf("get current masterchain info: %v", err))
|
|
time.Sleep(time.Second)
|
|
continue
|
|
}
|
|
|
|
t.lastBlockSeqno = mb.SeqNo - 1
|
|
}
|
|
|
|
nextSeqno := t.lastBlockSeqno + 1
|
|
|
|
// 阻塞直到 nextSeqno 在节点上可用,无需轮询
|
|
mb, err := t.client().WaitForBlock(nextSeqno).GetMasterchainInfo(ctx)
|
|
if err != nil {
|
|
if ctx.Err() != nil {
|
|
return
|
|
}
|
|
|
|
log.Task.Warn(fmt.Sprintf("WaitForBlock GetMasterchainInfo err: %v", err))
|
|
time.Sleep(time.Second)
|
|
continue
|
|
}
|
|
|
|
now := mb.SeqNo
|
|
|
|
// 区块高度变化过大,强制丢块重扫
|
|
if now-t.lastBlockSeqno > cast.ToUint32(model.GetC(model.BlockHeightMaxDiff)) {
|
|
t.lastBlockSeqno = now - 1
|
|
}
|
|
|
|
// 待扫描区块入列
|
|
for n := t.lastBlockSeqno + 1; n <= now; n++ {
|
|
t.blockScanQueue.In <- n
|
|
}
|
|
|
|
t.lastBlockSeqno = now
|
|
}
|
|
}
|
|
|
|
func (t *ton) blockDispatch(ctx context.Context) {
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case n, ok := <-t.blockScanQueue.Out:
|
|
if !ok {
|
|
return
|
|
}
|
|
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))
|
|
}
|
|
|
|
return err
|
|
}); err != nil {
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
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)
|
|
|
|
return fmt.Errorf("lookup master block: %w", err)
|
|
}
|
|
|
|
shardsTip, err := t.client().GetBlockShardsInfo(ctx, mb)
|
|
if err != nil {
|
|
conf.RecordFailure(conf.Ton)
|
|
|
|
return fmt.Errorf("get current shards info: %w", err)
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
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)
|
|
|
|
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)
|
|
|
|
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 {
|
|
if t.blockScanQueue.Len() >= blockQueueLimit {
|
|
log.Task.Warn("ton 同步阻塞,当前区块消费堆积数量:", t.blockScanQueue.Len())
|
|
|
|
return true
|
|
}
|
|
|
|
if mqttSubscribed(conf.Ton) {
|
|
return false
|
|
}
|
|
|
|
trade := []model.TradeType{model.UsdtTon, model.TonGram}
|
|
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 {
|
|
|
|
return false
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
func (t *ton) processShard(ctx context.Context, shard *tgo.BlockIDExt, seqno uint32) error {
|
|
data, err := t.client().GetBlockData(ctx, shard)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
txs, err := data.ListTransactions()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
var transfers = make([]transfer, 0)
|
|
for _, tx := range txs {
|
|
if tonTrans, ok := t.parseTonTransfer(tx, seqno); ok {
|
|
transfers = append(transfers, tonTrans)
|
|
}
|
|
if jettonTrans, ok := t.parseInternalTransfer(shard, tx, seqno); ok {
|
|
transfers = append(transfers, jettonTrans)
|
|
}
|
|
}
|
|
|
|
if len(transfers) > 0 {
|
|
transferQueue.In <- transfers
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// tonInboundMessage 提取交易的入站 internal 消息及其 ordinary 描述,两类转账解析共用
|
|
func tonInboundMessage(tx *tlb.Transaction) (*tlb.InternalMessage, tlb.TransactionDescriptionOrdinary, bool) {
|
|
var dsc tlb.TransactionDescriptionOrdinary
|
|
if tx.IO.In == nil {
|
|
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()
|
|
if err != nil || s.BitsLeft() < 32 {
|
|
return transfer{}, false
|
|
}
|
|
v, err := s.LoadUInt(32)
|
|
if err != nil || uint32(v) != tonOpInternalTransfer {
|
|
return transfer{}, false
|
|
}
|
|
|
|
compute, ok := dsc.ComputePhase.Phase.(tlb.ComputePhaseVM)
|
|
if !ok || !compute.Success {
|
|
return transfer{}, false
|
|
}
|
|
|
|
if dsc.ActionPhase == nil || !dsc.ActionPhase.Success {
|
|
return transfer{}, false
|
|
}
|
|
|
|
if err = s.SkipBits(64); err != nil {
|
|
return transfer{}, false
|
|
}
|
|
amount, err := s.LoadBigCoins()
|
|
if err != nil || amount.Sign() <= 0 {
|
|
return transfer{}, false
|
|
}
|
|
fromOwner, err := s.LoadAddr()
|
|
if err != nil {
|
|
return transfer{}, false
|
|
}
|
|
if fromOwner.Type() != address.StdAddress {
|
|
fromOwner = address.NewAddress(0, byte(fromOwner.Workchain()), fromOwner.Data())
|
|
}
|
|
|
|
toJetton := address.NewAddress(0, byte(shard.Workchain), tx.AccountAddr)
|
|
|
|
return transfer{
|
|
Network: conf.Ton,
|
|
TxHash: hex.EncodeToString(tx.Hash),
|
|
Amount: decimal.NewFromBigInt(amount, conf.UsdtTonDecimals),
|
|
FromAddress: tonAccountAddr(fromOwner),
|
|
RecvAddress: tonAccountAddr(toJetton),
|
|
Timestamp: time.Unix(int64(tx.Now), 0),
|
|
TradeType: model.UsdtTon,
|
|
BlockNum: int(blockNum),
|
|
}, true
|
|
}
|
|
|
|
func (t *ton) parseTonTransfer(tx *tlb.Transaction, blockNum uint32) (transfer, bool) {
|
|
msg, _, ok := tonInboundMessage(tx)
|
|
if !ok {
|
|
return transfer{}, false
|
|
}
|
|
if msg.Amount.Nano().Sign() <= 0 || msg.Body.BitsSize() != 0 {
|
|
return transfer{}, false
|
|
}
|
|
|
|
return transfer{
|
|
Network: conf.Ton,
|
|
TxHash: hex.EncodeToString(tx.Hash),
|
|
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,
|
|
BlockNum: int(blockNum),
|
|
}, true
|
|
}
|
|
|
|
func (t *ton) tradeConfirmHandle(context.Context) {
|
|
var orders = getConfirmingOrders([]model.TradeType{model.UsdtTon, model.TonGram})
|
|
var wg sync.WaitGroup
|
|
|
|
for _, order := range orders {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
|
|
// 一旦某笔交易所在的 shard block 被 MasterChain block 引用(commit),则该交易获得最终性(finality)。
|
|
markFinalConfirmed(order)
|
|
}()
|
|
}
|
|
|
|
wg.Wait()
|
|
}
|
|
|
|
func (t *ton) client() tgo.APIClientWrapped {
|
|
t.clientOnce.Do(func() {
|
|
t.api = utils.NewTonClient(model.GetC(model.RpcGlobalConfigUrlTon))
|
|
})
|
|
|
|
return t.api
|
|
}
|
|
|
|
func (t *ton) lookbackBlocks(ctx context.Context) {
|
|
if t.syncBreak() {
|
|
return
|
|
}
|
|
|
|
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():
|
|
return
|
|
default:
|
|
}
|
|
if t.syncBreak() {
|
|
return
|
|
}
|
|
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)
|
|
}
|