| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387 |
- package main
- import (
- "bytes"
- "database/sql"
- "encoding/json"
- "errors"
- "flag"
- "fmt"
- "io"
- "log"
- "net/http"
- "os"
- "os/signal"
- "regexp"
- "strings"
- "time"
- log2 "github.com/sirupsen/logrus"
- "gorm.io/driver/mysql"
- "gorm.io/gorm"
- "gorm.io/gorm/logger"
- "gorm.io/gorm/schema"
- )
- var apiUrl, dsn, contracts, apiKey, apiSecret, token string
- var timeout, expired, executionTime, size, sleepTime int
- func main() {
- flag.StringVar(&apiUrl, "url", "https://test-dna.bitfactory.cn", "激活接口地址")
- flag.StringVar(&dsn, "dsn", "root:rootPassword@tcp(192.168.150.40:23306)/dna_test", "mysql连接地址")
- flag.StringVar(&contracts, "contract", "", "合约地址")
- flag.StringVar(&apiKey, "apiKey", "", "apiKey")
- flag.StringVar(&apiSecret, "apiSecret", "", "apiSecret")
- flag.IntVar(&timeout, "timeout", 3, "请求超时时间")
- flag.IntVar(&expired, "expired", 6000, "token有效时间,单位秒")
- flag.IntVar(&executionTime, "execution_time", 10000, "mysql execution_time")
- flag.IntVar(&size, "size", 10000, "批处理数量")
- flag.IntVar(&sleepTime, "sleep_time", 0, "sleep time")
- flag.Parse()
- if apiUrl == "" {
- log2.Error("apiUrl is required")
- return
- }
- if dsn == "" {
- log2.Error("dsn is required")
- return
- }
- if contracts == "" {
- log2.Error("contract is required")
- return
- }
- if apiKey == "" {
- log2.Error("apiKey is required")
- return
- }
- if apiSecret == "" {
- log2.Error("apiSecret is required")
- return
- }
- if size < 1 {
- log2.Error("size must be greater than 1")
- return
- }
- if sleepTime < 0 {
- log2.Error("sleep_time must be greater than 0 ")
- return
- }
- utcZone := time.FixedZone("UTC", 0)
- time.Local = utcZone
- // 连接mysql
- newLogger := logger.New(
- log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
- logger.Config{
- SlowThreshold: time.Second, // 慢 SQL 阈值
- LogLevel: logger.Silent, // Log level
- Colorful: false, // 禁用彩色打印
- },
- )
- dsn := fmt.Sprintf("%s?charset=utf8&parseTime=True", dsn)
- db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: newLogger,
- NamingStrategy: schema.NamingStrategy{
- TablePrefix: "t_",
- SingularTable: false,
- },
- })
- if err != nil {
- log2.WithError(err).Error("init db failed")
- return
- }
- pattern := `^集合id.*已存在$`
- // 编译正则表达式
- regex, err := regexp.Compile(pattern)
- if err != nil {
- log2.WithError(err).Error("build regex failed")
- return
- }
- ticker := time.NewTicker(time.Duration(expired) * time.Second)
- quit := make(chan os.Signal, 1)
- signal.Notify(quit, os.Interrupt)
- go func() {
- for {
- select {
- case <-ticker.C:
- // 更新token
- var err error
- token, err = getToken()
- if err != nil {
- log2.WithError(err).Error("update token failed")
- return
- }
- case <-quit:
- // 接收到退出通知 停止定时器和退出 Goroutine
- ticker.Stop()
- close(quit)
- return
- }
- }
- }()
- // 查询要处理的数据的最大主键id
- var total sql.NullInt64
- err = db.Model(&DnaClasse{}).Select("Max(id)").Where("status", 3).Scan(&total).Error
- if err != nil {
- log2.WithError(err).Error("query classes total number failed")
- return
- }
- if !total.Valid {
- log2.Info("there is no unverified data left")
- return
- }
- token, err = getToken()
- if err != nil {
- log2.WithError(err).Error("update token failed")
- return
- }
- var min, id int64
- for id < total.Int64 {
- var list []DnaClasse
- err = db.Model(&DnaClasse{}).Where("status", 3).Where("id > ?", id).Limit(size).Order("id asc").Find(&list).Error
- if err != nil {
- log2.WithField("start", list[0].Id).WithField("end", list[len(list)-1].Id).WithError(err).Error("query not active classes failed")
- continue
- }
- if len(list) == 0 {
- log2.Info("there is no unverified data left")
- break
- }
- for _, item := range list {
- time.Sleep(time.Millisecond * time.Duration(sleepTime))
- logger := log2.WithField("id", item.Id).WithField("class_id", item.ClassId)
- var resp Resp
- err = db.Transaction(func(tx *gorm.DB) error {
- // 查类别下nft总数
- var nftNumber int64
- err = tx.Model(&DnaNft{}).Where("class_id", item.ClassId).Where("status in (1,2,3)").Count(&nftNumber).Error
- if err != nil {
- logger.WithError(err).Error("query classes total nft number failed")
- return err
- }
- if item.Name == "" || item.CollectIssuer == "" || item.Url == "" {
- logger.Error("classes name/collect_issuer/url is required")
- return errors.New("classes name/collect_issuer/url is required")
- }
- if len([]rune(item.Name)) > 50 {
- logger.Error("class name length illegal")
- return errors.New("class name length illegal")
- }
- //更新类别状态
- result := tx.Model(&DnaClasse{}).Where("status", 3).Where("id", item.Id).Updates(map[string]interface{}{
- "status": 1, // 更新状态为已认证
- "err_msg": "",
- })
- if result.Error != nil {
- logger.WithError(err).Error("update classes status failed")
- return err
- }
- // 认证类别
- classReq := []ClassReq{
- {
- SeriesName: item.Name,
- SeriesIssuer: item.CollectIssuer,
- ExternalUrl: item.Url,
- SeriesDes: item.Description,
- SeriesId: []string{item.ClassId},
- TotalDNA: nftNumber,
- AssetContracts: contracts,
- },
- }
- // 认证
- objJson, err := json.Marshal(&Req{
- Data: classReq,
- })
- if err != nil {
- logger.WithError(err).Error("marshal request body failed")
- return err
- }
- payload := bytes.NewReader(objJson)
- url := fmt.Sprintf("%s/auth/api/v1/series", apiUrl)
- req, err := http.NewRequest("POST", url, payload)
- if err != nil {
- logger.WithError(err).Error("build request failed")
- return err
- }
- req.Header.Add("Content-Type", "application/json")
- req.Header.Add("accessToken", token)
- client := &http.Client{Timeout: time.Duration(timeout) * time.Second}
- res, err := client.Do(req)
- if err != nil {
- logger.WithError(err).Error("request failed")
- return err
- }
- body, err := io.ReadAll(res.Body)
- if err != nil {
- logger.WithError(err).Error("read body failed")
- res.Body.Close()
- return err
- }
- res.Body.Close()
- err = json.Unmarshal(body, &resp)
- if err != nil {
- logger.WithError(err).Error("unmarshal response failed")
- return err
- }
- if resp.RetCode != http.StatusOK || resp.RetMsg != "ok" {
- return errors.New(resp.RetMsg)
- }
- return nil
- })
- if err != nil {
- result := db.Model(&DnaClasse{}).Where("id", item.Id).Updates(map[string]interface{}{
- "err_msg": err.Error(),
- })
- if result.Error != nil {
- logger.WithError(result.Error).Error("update classes err_msg failed")
- continue
- }
- if strings.Contains(resp.RetMsg, "accessToken过期") {
- logger.Error("active class failed: ", resp.RetMsg)
- token, err = getToken()
- if err != nil {
- logger.WithError(err).Error("update token failed")
- log2.Fatal("请检查token获取")
- }
- continue
- }
- if strings.Contains(resp.RetMsg, "accessToken必填") || strings.Contains(resp.RetMsg, "accessToken不正确") || strings.Contains(resp.RetMsg, "请检查请求体") {
- logger.Error("active class failed: ", resp.RetMsg)
- log2.Fatal("请检查token获取") // 结束代码进行检查
- }
- if regex.MatchString(resp.RetMsg) {
- logger.Error("class_id repeatd: ", resp.RetMsg)
- // 重复 已经认证成功
- result := db.Model(&DnaClasse{}).Where("id", item.Id).Updates(map[string]interface{}{
- "status": 1,
- "err_msg": resp.RetMsg,
- })
- if result.Error != nil {
- logger.WithError(result.Error).Error("update classes status failed")
- }
- continue
- }
- logger.Error("active class failed: ", resp.RetMsg)
- }
- }
- min = list[0].Id
- id = list[len(list)-1].Id
- log2.WithField("start", min).WithField("end", id).Info("本次处理区间")
- }
- fmt.Println()
- log2.Info("========= finish ============")
- fmt.Println()
- quit <- os.Interrupt
- <-quit
- }
- func getToken() (string, error) {
- url := fmt.Sprintf("%s/registration/api/v2/getToken?apiKey=%s&apiSecret=%s", apiUrl, apiKey, apiSecret)
- req, err := http.NewRequest("GET", url, nil)
- if err != nil {
- log2.WithError(err).Error("build request failed")
- return "", err
- }
- req.Header.Add("Content-Type", "application/json")
- client := &http.Client{Timeout: time.Duration(timeout) * time.Second}
- res, err := client.Do(req)
- if err != nil {
- log2.WithError(err).Error("request failed")
- return "", err
- }
- body, err := io.ReadAll(res.Body)
- if err != nil {
- log2.WithError(err).Error("read body failed")
- return "", err
- }
- var resp Resp
- err = json.Unmarshal(body, &resp)
- if err != nil {
- log2.WithError(err).Error("unmarshal response failed")
- return "", err
- }
- if resp.RetCode != http.StatusOK || resp.RetMsg != "ok" {
- log2.Error(resp.RetMsg)
- return "", err
- }
- return resp.AccessToken, nil
- }
- type TokenResp struct {
- Data []ClassReq `json:"data"`
- }
- type Req struct {
- Data []ClassReq `json:"data"`
- }
- type ClassReq struct {
- SeriesName string `json:"seriesName"`
- SeriesIssuer string `json:"seriesIssuer"`
- ExternalUrl string `json:"externalUrl"`
- SeriesDes string `json:"seriesDes"`
- SeriesId []string `json:"seriesId"`
- TotalDNA int64 `json:"totalDNA"`
- AssetContracts string `json:"asset_contracts"`
- }
- type Resp struct {
- RetCode int `json:"retCode"`
- RetMsg string `json:"retMsg"`
- AccessToken string `json:"accessToken"`
- }
- // DNA类别认证表
- type DnaClasse struct {
- Id int64 `gorm:"column:id;type:bigint(20) unsigned;primary_key;AUTO_INCREMENT;comment:主键id" json:"id"`
- ClassId string `gorm:"column:class_id;type:char(42);comment:类别ID;NOT NULL" json:"class_id"`
- Name string `gorm:"column:name;type:varchar(100);comment:类别名称;NOT NULL" json:"name"`
- Url string `gorm:"column:url;type:varchar(100);comment:类别url;NOT NULL" json:"url"`
- Description string `gorm:"column:description;type:varchar(200);comment:类别描述;NOT NULL" json:"description"`
- Status int `gorm:"column:status;type:tinyint(4);default:2;comment:dna认证状态 1:已认证 2:未认证;NOT NULL" json:"status"`
- CollectIssuer string `gorm:"column:collect_issuer;type:varchar(50);comment:集合发行方;NOT NULL" json:"collect_issuer"`
- CreatedAt time.Time `gorm:"<-:false"`
- UpdatedAt time.Time `gorm:"<-:false"`
- }
- // DNA NFT认证表
- type DnaNft struct {
- Id uint64 `gorm:"column:id;type:bigint(20) unsigned;primary_key;AUTO_INCREMENT" json:"id"`
- ClassId string `gorm:"column:class_id;type:char(42);comment:类别ID;NOT NULL" json:"class_id"`
- TokenId int64 `gorm:"column:token_id;type:bigint(20);default:0;comment:NFT ID;NOT NULL" json:"token_id"`
- Owner string `gorm:"column:owner;type:char(42);comment:资产拥有者;NOT NULL" json:"owner"`
- Name string `gorm:"column:name;type:varchar(100);comment:资产名称;NOT NULL" json:"name"`
- Url string `gorm:"column:url;type:varchar(200);comment:图片url;NOT NULL" json:"url"`
- DisplayUrl string `gorm:"column:display_url;type:varchar(200);comment:缩略图url;NOT NULL" json:"display_url"`
- Hash string `gorm:"column:hash;type:varchar(100);comment:图片哈希;NOT NULL" json:"hash"`
- Price float64 `gorm:"column:price;type:decimal(10,2);default:0.00;comment:发行加价格;NOT NULL" json:"price"`
- Description string `gorm:"column:description;type:varchar(255);comment:资产描述;NOT NULL" json:"description"`
- Status int `gorm:"column:status;type:tinyint(4);default:2;comment:dna认证状态 1:已认证 2:未认证;NOT NULL" json:"status"`
- Timestamp time.Time `gorm:"column:timestamp;type:datetime;comment:交易上链时间" json:"timestamp"`
- TxId int64 `gorm:"column:tx_id;type:bigint(20);default:0;comment:交易表主键id;NOT NULL" json:"tx_id"`
- CreatedAt time.Time `gorm:"<-:false"`
- UpdatedAt time.Time `gorm:"<-:false"`
- }
|