| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376 |
- package main
- import (
- "bytes"
- "database/sql"
- "encoding/json"
- "errors"
- "flag"
- "fmt"
- "io"
- "io/ioutil"
- "log"
- "net/http"
- "net/url"
- "os"
- "os/signal"
- "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 size, timeout, expired, executionTime, 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(&size, "size", 1, "批处理数量")
- flag.IntVar(&timeout, "timeout", 3, "请求超时时间")
- flag.IntVar(&expired, "expired", 6000, "token有效时间,单位秒")
- flag.IntVar(&executionTime, "execution_time", 60, "mysql execution_time")
- 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 || size > 100 {
- log2.Error("size must be between 1 and 100")
- 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&loc=Local&time_zone=%s&max_execution_time=%d", dsn, url.QueryEscape("'UTC'"), executionTime)
- 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
- }
- 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", 2).Scan(&total).Error
- if err != nil {
- log2.WithError(err).Error("query classes total number failed")
- return
- }
- if !total.Valid {
- log2.Error("there is no unverified data left")
- return
- }
- token, err = getToken()
- if err != nil {
- log2.WithError(err).Error("update token failed")
- return
- }
- var id int64
- for id < total.Int64 {
- time.Sleep(time.Millisecond * time.Duration(sleepTime))
- var list []DnaClasse
- err = db.Model(&DnaClasse{}).Where("status", 2).Where("id > ?", id).Limit(size).Order("id asc").Find(&list).Error
- if err != nil {
- log2.WithError(err).Error("query not active classes failed")
- continue
- }
- if len(list) == 0 {
- log2.Info("there is no unverified data left")
- break
- }
- sid := list[0].Id
- eid := list[len(list)-1].Id
- err = db.Transaction(func(tx *gorm.DB) error {
- var classReq []ClassReq
- // 更新本批类别状态为已激活
- result := tx.Model(&DnaClasse{}).Where("status", 2).Where("id > ?", id).Limit(size).Order("id asc").Update("status", 1)
- if result.Error != nil {
- log2.WithField("start", sid).WithField("end", eid).WithError(result.Error).Error("update classes status failed")
- return err
- }
- logger := log2.WithField("start", sid).WithField("end", eid)
- // 生成批量数据
- for j := 0; j < len(list); j++ {
- // 查询类别下nft总数
- var nftNumber int64
- err = tx.Model(&DnaNft{}).Where("class_id", list[j].ClassId).Where("status in (1,2,3)").Count(&nftNumber).Error
- if err != nil {
- log2.WithField("id", list[j].Id).WithError(err).Error("query classes total nft number failed")
- result := tx.Model(&DnaClasse{}).Where("id", list[j].Id).Updates(map[string]interface{}{
- "status": 2, // 更新状态为未认证
- "err_msg": fmt.Sprintf("query classes total nft number failed: %s", err.Error()),
- })
- if result.Error != nil {
- log2.WithField("id", list[j].Id).WithError(result.Error).Error("update classes status failed")
- return result.Error
- }
- continue
- }
- if list[j].Name == "" || list[j].CollectIssuer == "" || list[j].Url == "" {
- log2.WithField("id", list[j].Id).Error("classes name/collect_issuer/url is required")
- result = tx.Model(&DnaClasse{}).Where("id", list[j].Id).Updates(map[string]interface{}{
- "status": 3, // 更新状态为认证失败
- "err_msg": "classes name/collect_issuer/url is required",
- })
- if result.Error != nil {
- log2.WithField("id", list[j].Id).WithError(result.Error).Error("update classes status failed")
- return result.Error // 数据库错误 回滚
- }
- continue
- }
- if len([]rune(list[j].Name)) > 50 {
- log2.WithField("id", list[j].Id).Error("class name length illegal")
- result := tx.Model(&DnaClasse{}).Where("id", list[j].Id).Updates(map[string]interface{}{
- "status": 3, // 更新状态为未认证
- "err_msg": "class name length illegal",
- })
- if result.Error != nil {
- log2.WithField("id", list[j].Id).WithError(result.Error).Error("update classes status failed")
- return result.Error // 数据库错误 回滚
- }
- continue
- }
- classReq = append(classReq, ClassReq{
- SeriesName: list[j].Name,
- SeriesIssuer: list[j].CollectIssuer,
- ExternalUrl: list[j].Url,
- SeriesDes: list[j].Description,
- SeriesId: []string{list[j].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()
- var resp Resp
- 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" {
- logger.Error("active class failed: ", resp.RetMsg)
- return errors.New(resp.RetMsg)
- }
- return nil
- })
- if err != nil {
- // 更新状态
- result := db.Model(&DnaClasse{}).Where("status", 2).Where("id > ?", id).Limit(size).Order("id asc").Updates(map[string]interface{}{
- "status": 3, // 更新状态为认证失败
- "err_msg": err.Error(),
- })
- id = list[len(list)-1].Id
- if result.Error != nil {
- log2.WithField("start", sid).WithField("end", eid).WithError(result.Error).Error("update classes status failed")
- continue
- }
- log2.WithField("start", sid).WithField("end", eid).Info("本次处理区间")
- continue
- }
- id = list[len(list)-1].Id
- log2.WithField("start", sid).WithField("end", eid).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 := ioutil.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"`
- }
|