class_check.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. package main
  2. import (
  3. "bytes"
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "flag"
  8. "fmt"
  9. "io"
  10. "log"
  11. "net/http"
  12. "os"
  13. "os/signal"
  14. "regexp"
  15. "strings"
  16. "time"
  17. log2 "github.com/sirupsen/logrus"
  18. "gorm.io/driver/mysql"
  19. "gorm.io/gorm"
  20. "gorm.io/gorm/logger"
  21. "gorm.io/gorm/schema"
  22. )
  23. var apiUrl, dsn, contracts, apiKey, apiSecret, token string
  24. var timeout, expired, executionTime, size, sleepTime int
  25. func main() {
  26. flag.StringVar(&apiUrl, "url", "https://test-dna.bitfactory.cn", "激活接口地址")
  27. flag.StringVar(&dsn, "dsn", "root:rootPassword@tcp(192.168.150.40:23306)/dna_test", "mysql连接地址")
  28. flag.StringVar(&contracts, "contract", "", "合约地址")
  29. flag.StringVar(&apiKey, "apiKey", "", "apiKey")
  30. flag.StringVar(&apiSecret, "apiSecret", "", "apiSecret")
  31. flag.IntVar(&timeout, "timeout", 3, "请求超时时间")
  32. flag.IntVar(&expired, "expired", 6000, "token有效时间,单位秒")
  33. flag.IntVar(&executionTime, "execution_time", 10000, "mysql execution_time")
  34. flag.IntVar(&size, "size", 10000, "批处理数量")
  35. flag.IntVar(&sleepTime, "sleep_time", 0, "sleep time")
  36. flag.Parse()
  37. if apiUrl == "" {
  38. log2.Error("apiUrl is required")
  39. return
  40. }
  41. if dsn == "" {
  42. log2.Error("dsn is required")
  43. return
  44. }
  45. if contracts == "" {
  46. log2.Error("contract is required")
  47. return
  48. }
  49. if apiKey == "" {
  50. log2.Error("apiKey is required")
  51. return
  52. }
  53. if apiSecret == "" {
  54. log2.Error("apiSecret is required")
  55. return
  56. }
  57. if size < 1 {
  58. log2.Error("size must be greater than 1")
  59. return
  60. }
  61. if sleepTime < 0 {
  62. log2.Error("sleep_time must be greater than 0 ")
  63. return
  64. }
  65. utcZone := time.FixedZone("UTC", 0)
  66. time.Local = utcZone
  67. // 连接mysql
  68. newLogger := logger.New(
  69. log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
  70. logger.Config{
  71. SlowThreshold: time.Second, // 慢 SQL 阈值
  72. LogLevel: logger.Silent, // Log level
  73. Colorful: false, // 禁用彩色打印
  74. },
  75. )
  76. dsn := fmt.Sprintf("%s?charset=utf8&parseTime=True", dsn)
  77. db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: newLogger,
  78. NamingStrategy: schema.NamingStrategy{
  79. TablePrefix: "t_",
  80. SingularTable: false,
  81. },
  82. })
  83. if err != nil {
  84. log2.WithError(err).Error("init db failed")
  85. return
  86. }
  87. pattern := `^集合id.*已存在$`
  88. // 编译正则表达式
  89. regex, err := regexp.Compile(pattern)
  90. if err != nil {
  91. log2.WithError(err).Error("build regex failed")
  92. return
  93. }
  94. ticker := time.NewTicker(time.Duration(expired) * time.Second)
  95. quit := make(chan os.Signal, 1)
  96. signal.Notify(quit, os.Interrupt)
  97. go func() {
  98. for {
  99. select {
  100. case <-ticker.C:
  101. // 更新token
  102. var err error
  103. token, err = getToken()
  104. if err != nil {
  105. log2.WithError(err).Error("update token failed")
  106. return
  107. }
  108. case <-quit:
  109. // 接收到退出通知 停止定时器和退出 Goroutine
  110. ticker.Stop()
  111. close(quit)
  112. return
  113. }
  114. }
  115. }()
  116. // 查询要处理的数据的最大主键id
  117. var total sql.NullInt64
  118. err = db.Model(&DnaClasse{}).Select("Max(id)").Where("status", 3).Scan(&total).Error
  119. if err != nil {
  120. log2.WithError(err).Error("query classes total number failed")
  121. return
  122. }
  123. if !total.Valid {
  124. log2.Info("there is no unverified data left")
  125. return
  126. }
  127. token, err = getToken()
  128. if err != nil {
  129. log2.WithError(err).Error("update token failed")
  130. return
  131. }
  132. var min, id int64
  133. for id < total.Int64 {
  134. var list []DnaClasse
  135. err = db.Model(&DnaClasse{}).Where("status", 3).Where("id > ?", id).Limit(size).Order("id asc").Find(&list).Error
  136. if err != nil {
  137. log2.WithField("start", list[0].Id).WithField("end", list[len(list)-1].Id).WithError(err).Error("query not active classes failed")
  138. continue
  139. }
  140. if len(list) == 0 {
  141. log2.Info("there is no unverified data left")
  142. break
  143. }
  144. for _, item := range list {
  145. time.Sleep(time.Millisecond * time.Duration(sleepTime))
  146. logger := log2.WithField("id", item.Id).WithField("class_id", item.ClassId)
  147. var resp Resp
  148. err = db.Transaction(func(tx *gorm.DB) error {
  149. // 查类别下nft总数
  150. var nftNumber int64
  151. err = tx.Model(&DnaNft{}).Where("class_id", item.ClassId).Where("status in (1,2,3)").Count(&nftNumber).Error
  152. if err != nil {
  153. logger.WithError(err).Error("query classes total nft number failed")
  154. return err
  155. }
  156. if item.Name == "" || item.CollectIssuer == "" || item.Url == "" {
  157. logger.Error("classes name/collect_issuer/url is required")
  158. return errors.New("classes name/collect_issuer/url is required")
  159. }
  160. if len([]rune(item.Name)) > 50 {
  161. logger.Error("class name length illegal")
  162. return errors.New("class name length illegal")
  163. }
  164. //更新类别状态
  165. result := tx.Model(&DnaClasse{}).Where("status", 3).Where("id", item.Id).Updates(map[string]interface{}{
  166. "status": 1, // 更新状态为已认证
  167. "err_msg": "",
  168. })
  169. if result.Error != nil {
  170. logger.WithError(err).Error("update classes status failed")
  171. return err
  172. }
  173. // 认证类别
  174. classReq := []ClassReq{
  175. {
  176. SeriesName: item.Name,
  177. SeriesIssuer: item.CollectIssuer,
  178. ExternalUrl: item.Url,
  179. SeriesDes: item.Description,
  180. SeriesId: []string{item.ClassId},
  181. TotalDNA: nftNumber,
  182. AssetContracts: contracts,
  183. },
  184. }
  185. // 认证
  186. objJson, err := json.Marshal(&Req{
  187. Data: classReq,
  188. })
  189. if err != nil {
  190. logger.WithError(err).Error("marshal request body failed")
  191. return err
  192. }
  193. payload := bytes.NewReader(objJson)
  194. url := fmt.Sprintf("%s/auth/api/v1/series", apiUrl)
  195. req, err := http.NewRequest("POST", url, payload)
  196. if err != nil {
  197. logger.WithError(err).Error("build request failed")
  198. return err
  199. }
  200. req.Header.Add("Content-Type", "application/json")
  201. req.Header.Add("accessToken", token)
  202. client := &http.Client{Timeout: time.Duration(timeout) * time.Second}
  203. res, err := client.Do(req)
  204. if err != nil {
  205. logger.WithError(err).Error("request failed")
  206. return err
  207. }
  208. body, err := io.ReadAll(res.Body)
  209. if err != nil {
  210. logger.WithError(err).Error("read body failed")
  211. res.Body.Close()
  212. return err
  213. }
  214. res.Body.Close()
  215. err = json.Unmarshal(body, &resp)
  216. if err != nil {
  217. logger.WithError(err).Error("unmarshal response failed")
  218. return err
  219. }
  220. if resp.RetCode != http.StatusOK || resp.RetMsg != "ok" {
  221. return errors.New(resp.RetMsg)
  222. }
  223. return nil
  224. })
  225. if err != nil {
  226. result := db.Model(&DnaClasse{}).Where("id", item.Id).Updates(map[string]interface{}{
  227. "err_msg": err.Error(),
  228. })
  229. if result.Error != nil {
  230. logger.WithError(result.Error).Error("update classes err_msg failed")
  231. continue
  232. }
  233. if strings.Contains(resp.RetMsg, "accessToken过期") {
  234. logger.Error("active class failed: ", resp.RetMsg)
  235. token, err = getToken()
  236. if err != nil {
  237. logger.WithError(err).Error("update token failed")
  238. log2.Fatal("请检查token获取")
  239. }
  240. continue
  241. }
  242. if strings.Contains(resp.RetMsg, "accessToken必填") || strings.Contains(resp.RetMsg, "accessToken不正确") || strings.Contains(resp.RetMsg, "请检查请求体") {
  243. logger.Error("active class failed: ", resp.RetMsg)
  244. log2.Fatal("请检查token获取") // 结束代码进行检查
  245. }
  246. if regex.MatchString(resp.RetMsg) {
  247. logger.Error("class_id repeatd: ", resp.RetMsg)
  248. // 重复 已经认证成功
  249. result := db.Model(&DnaClasse{}).Where("id", item.Id).Updates(map[string]interface{}{
  250. "status": 1,
  251. "err_msg": resp.RetMsg,
  252. })
  253. if result.Error != nil {
  254. logger.WithError(result.Error).Error("update classes status failed")
  255. }
  256. continue
  257. }
  258. logger.Error("active class failed: ", resp.RetMsg)
  259. }
  260. }
  261. min = list[0].Id
  262. id = list[len(list)-1].Id
  263. log2.WithField("start", min).WithField("end", id).Info("本次处理区间")
  264. }
  265. fmt.Println()
  266. log2.Info("========= finish ============")
  267. fmt.Println()
  268. quit <- os.Interrupt
  269. <-quit
  270. }
  271. func getToken() (string, error) {
  272. url := fmt.Sprintf("%s/registration/api/v2/getToken?apiKey=%s&apiSecret=%s", apiUrl, apiKey, apiSecret)
  273. req, err := http.NewRequest("GET", url, nil)
  274. if err != nil {
  275. log2.WithError(err).Error("build request failed")
  276. return "", err
  277. }
  278. req.Header.Add("Content-Type", "application/json")
  279. client := &http.Client{Timeout: time.Duration(timeout) * time.Second}
  280. res, err := client.Do(req)
  281. if err != nil {
  282. log2.WithError(err).Error("request failed")
  283. return "", err
  284. }
  285. body, err := io.ReadAll(res.Body)
  286. if err != nil {
  287. log2.WithError(err).Error("read body failed")
  288. return "", err
  289. }
  290. var resp Resp
  291. err = json.Unmarshal(body, &resp)
  292. if err != nil {
  293. log2.WithError(err).Error("unmarshal response failed")
  294. return "", err
  295. }
  296. if resp.RetCode != http.StatusOK || resp.RetMsg != "ok" {
  297. log2.Error(resp.RetMsg)
  298. return "", err
  299. }
  300. return resp.AccessToken, nil
  301. }
  302. type TokenResp struct {
  303. Data []ClassReq `json:"data"`
  304. }
  305. type Req struct {
  306. Data []ClassReq `json:"data"`
  307. }
  308. type ClassReq struct {
  309. SeriesName string `json:"seriesName"`
  310. SeriesIssuer string `json:"seriesIssuer"`
  311. ExternalUrl string `json:"externalUrl"`
  312. SeriesDes string `json:"seriesDes"`
  313. SeriesId []string `json:"seriesId"`
  314. TotalDNA int64 `json:"totalDNA"`
  315. AssetContracts string `json:"asset_contracts"`
  316. }
  317. type Resp struct {
  318. RetCode int `json:"retCode"`
  319. RetMsg string `json:"retMsg"`
  320. AccessToken string `json:"accessToken"`
  321. }
  322. // DNA类别认证表
  323. type DnaClasse struct {
  324. Id int64 `gorm:"column:id;type:bigint(20) unsigned;primary_key;AUTO_INCREMENT;comment:主键id" json:"id"`
  325. ClassId string `gorm:"column:class_id;type:char(42);comment:类别ID;NOT NULL" json:"class_id"`
  326. Name string `gorm:"column:name;type:varchar(100);comment:类别名称;NOT NULL" json:"name"`
  327. Url string `gorm:"column:url;type:varchar(100);comment:类别url;NOT NULL" json:"url"`
  328. Description string `gorm:"column:description;type:varchar(200);comment:类别描述;NOT NULL" json:"description"`
  329. Status int `gorm:"column:status;type:tinyint(4);default:2;comment:dna认证状态 1:已认证 2:未认证;NOT NULL" json:"status"`
  330. CollectIssuer string `gorm:"column:collect_issuer;type:varchar(50);comment:集合发行方;NOT NULL" json:"collect_issuer"`
  331. CreatedAt time.Time `gorm:"<-:false"`
  332. UpdatedAt time.Time `gorm:"<-:false"`
  333. }
  334. // DNA NFT认证表
  335. type DnaNft struct {
  336. Id uint64 `gorm:"column:id;type:bigint(20) unsigned;primary_key;AUTO_INCREMENT" json:"id"`
  337. ClassId string `gorm:"column:class_id;type:char(42);comment:类别ID;NOT NULL" json:"class_id"`
  338. TokenId int64 `gorm:"column:token_id;type:bigint(20);default:0;comment:NFT ID;NOT NULL" json:"token_id"`
  339. Owner string `gorm:"column:owner;type:char(42);comment:资产拥有者;NOT NULL" json:"owner"`
  340. Name string `gorm:"column:name;type:varchar(100);comment:资产名称;NOT NULL" json:"name"`
  341. Url string `gorm:"column:url;type:varchar(200);comment:图片url;NOT NULL" json:"url"`
  342. DisplayUrl string `gorm:"column:display_url;type:varchar(200);comment:缩略图url;NOT NULL" json:"display_url"`
  343. Hash string `gorm:"column:hash;type:varchar(100);comment:图片哈希;NOT NULL" json:"hash"`
  344. Price float64 `gorm:"column:price;type:decimal(10,2);default:0.00;comment:发行加价格;NOT NULL" json:"price"`
  345. Description string `gorm:"column:description;type:varchar(255);comment:资产描述;NOT NULL" json:"description"`
  346. Status int `gorm:"column:status;type:tinyint(4);default:2;comment:dna认证状态 1:已认证 2:未认证;NOT NULL" json:"status"`
  347. Timestamp time.Time `gorm:"column:timestamp;type:datetime;comment:交易上链时间" json:"timestamp"`
  348. TxId int64 `gorm:"column:tx_id;type:bigint(20);default:0;comment:交易表主键id;NOT NULL" json:"tx_id"`
  349. CreatedAt time.Time `gorm:"<-:false"`
  350. UpdatedAt time.Time `gorm:"<-:false"`
  351. }