Commit cbc54ced authored by 贾浩@五瓣科技's avatar 贾浩@五瓣科技

update 2 methods to login

parent 6bdc2243
......@@ -15,7 +15,7 @@ listen = "0.0.0.0:8080"
[gas_sender]
rpc = "https://sepolia.rpc.aonnet.io"
user_contract = "0x64ea0CC733f9B899545aE454f1890b5eb512560F"
# 0x0000000077024042e797Ae28A163C27E389CC5b2
private_key = "39494cd233573c94d6b4d24847f2f4d5da9d0b384b61f3ad4fae9abd5c48e6fc"
......
......@@ -29,8 +29,9 @@ type ServerConfig struct {
}
type GasSenderConfig struct {
PrivateKey string `toml:"private_key"`
RPC string `toml:"rpc"`
PrivateKey string `toml:"private_key"`
UserContract string `toml:"user_contract"`
RPC string `toml:"rpc"`
}
type TGBotConfig struct {
......
This diff is collapsed.
This diff is collapsed.
......@@ -4,9 +4,11 @@ import (
"context"
"crypto/ecdsa"
"math/big"
"sdk_api/contract/aonUser"
"time"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
......@@ -19,14 +21,19 @@ type GasSender struct {
client *ethclient.Client
taskCh chan *gasTask
chainId *big.Int
aonUser *aonUser.AonUser
}
type gasTask struct {
dest common.Address
value *big.Int
dest common.Address
user common.Address
value *big.Int
userId string
inviterId string
method string
}
func NewGasSender(rpc, privateKey string) (*GasSender, error) {
func NewGasSender(rpc, privateKey, aonUserContract string) (*GasSender, error) {
ecdsaKey, err := crypto.HexToECDSA(common.Bytes2Hex(common.FromHex(privateKey)))
if err != nil {
return nil, err
......@@ -44,11 +51,22 @@ func NewGasSender(rpc, privateKey string) (*GasSender, error) {
return nil, err
}
ca, err := aonUser.NewAonUser(common.HexToAddress(aonUserContract), client)
if err != nil {
return nil, err
}
log.WithFields(log.Fields{
"caller": crypto.PubkeyToAddress(ecdsaKey.PublicKey),
"userContract": common.HexToAddress(aonUserContract),
}).Info("init gas sender")
return &GasSender{
privateKey: ecdsaKey,
client: client,
taskCh: make(chan *gasTask, 32),
chainId: chainId,
aonUser: ca,
}, nil
}
......@@ -58,7 +76,12 @@ func (gs *GasSender) Run() {
for {
select {
case task := <-gs.taskCh:
gs.sendTx(task)
switch task.method {
case "sendGas":
gs.sendGas(task)
case "aonLogin":
gs.login(task)
}
}
}
}()
......@@ -68,12 +91,23 @@ func (gs *GasSender) SendAONGas(dest string, amount int) {
addr := common.HexToAddress(dest)
value := new(big.Int).Mul(big.NewInt(int64(amount)), big.NewInt(1000000000000000000))
gs.taskCh <- &gasTask{
dest: addr,
value: value,
dest: addr,
value: value,
method: "sendGas",
}
}
func (gs *GasSender) sendTx(task *gasTask) {
func (gs *GasSender) AonLogin(address common.Address, userId, inviter string) {
gs.taskCh <- &gasTask{
user: address,
value: big.NewInt(0),
userId: userId,
inviterId: inviter,
method: "aonLogin",
}
}
func (gs *GasSender) sendGas(task *gasTask) {
log.WithFields(log.Fields{
"address": task.dest,
"value": task.value,
......@@ -128,3 +162,48 @@ func (gs *GasSender) sendTx(task *gasTask) {
}
txLog.Error("tx receipt not found, timeout")
}
func (gs *GasSender) login(task *gasTask) {
log.WithFields(log.Fields{
"address": task.user.Hex(),
"userId": task.userId,
"inviterId": task.inviterId,
}).Info("new login task")
opts, err := bind.NewKeyedTransactorWithChainID(gs.privateKey, gs.chainId)
if err != nil {
log.WithError(err).Error("create transactor failed")
return
}
opts.GasPrice = big.NewInt(1000000000)
opts.GasLimit = 2000000
signedTx, err := gs.aonUser.LoginByServer(opts, task.user, task.userId, task.inviterId)
if err != nil {
log.WithError(err).Error("send tx failed")
return
}
txLog := log.WithField("txHash", signedTx.Hash().Hex())
txLog.Info("tx broadcasted")
for i := 0; i < 5; i++ {
time.Sleep(time.Second * 2)
receipt, err := gs.client.TransactionReceipt(context.Background(), signedTx.Hash())
if err != nil && err == ethereum.NotFound {
txLog.Info("tx receipt not found, retrying...")
continue
}
if err != nil {
txLog.WithError(err).Error("send gas tx failed")
return
}
if receipt.Status != 1 {
txLog.Error("send gas tx failed")
return
}
txLog.Info("send gas tx confirmed")
return
}
txLog.Error("tx receipt not found, timeout")
}
......@@ -31,6 +31,7 @@ require (
github.com/deckarep/golang-set/v2 v2.1.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0 // indirect
github.com/ethereum/c-kzg-4844/bindings/go v0.0.0-20230126171313-363c7d7593b4 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
......
......@@ -20,6 +20,8 @@ github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/cespare/cp v0.1.0 h1:SE+dxFebS7Iik5LK0tsi1k9ZCxEaFX4AjQmoyA+1dJk=
github.com/cespare/cp v0.1.0/go.mod h1:SOGHArjBr4JWaSDEVpWpo/hNg6RoKrls6Oh40hiwW+s=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
......@@ -107,6 +109,8 @@ github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb/go.mod h1:/XxbfmMg
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/subcommands v1.2.0/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
......@@ -247,6 +251,7 @@ golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
......
......@@ -19,3 +19,13 @@ type CreateUserRequest struct {
type CreateUserResponse struct {
}
type LoginRequest struct {
InitData string `json:"initData"`
Platform string `json:"platform"`
VisitorID string `json:"visitorId"`
Keystore string `json:"keystore"`
Signature string `json:"signature"`
UserId string `json:"userId"`
InviterId string `json:"inviter_id"`
}
......@@ -6,8 +6,7 @@ import (
"github.com/gin-gonic/gin"
)
func initRouter(e *gin.Engine) {
func initRouter(e *gin.Engine) {
e.Use(middleware.PrintRequestResponseBodyMiddleware())
v1 := e.Group("/api/v1")
......@@ -15,8 +14,8 @@ func initRouter(e *gin.Engine) {
{
user := v1.Group("/user")
user.POST("/check", checkUser)
user.POST("/serverLogin", login)
user.POST("/create", middleware.JWTMiddleware, createUser)
}
}
......@@ -17,7 +17,7 @@ import (
func checkUser(c *gin.Context) {
req := &apiModel.CheckUserRequest{}
if err := c.ShouldBindJSON(req); err != nil {
withError(constant.InvalidParam)
c.JSON(200, withError(constant.InvalidParam))
return
}
switch req.Platform {
......@@ -116,3 +116,83 @@ func createUser(c *gin.Context) {
}
c.JSON(200, withSuccess(""))
}
func login(c *gin.Context) {
req := &apiModel.LoginRequest{}
if err := c.ShouldBindJSON(req); err != nil {
c.JSON(200, withError(constant.InvalidParam))
return
}
var platformId string
switch req.Platform {
case constant.PlatformTelegram:
var ok bool
var userId string
var botId string
for _, token := range conf.TGBot.Tokens {
ok, botId, userId = util.VerifyInitData(req.InitData, token)
if ok {
break
}
}
if !ok {
c.JSON(200, withError("invalid initData"))
return
}
platformId = fmt.Sprintf("%s:%s", botId, userId)
case constant.PlatformFingerprint:
if len(req.VisitorID) <= 10 {
c.JSON(200, withError(constant.InvalidParam))
return
}
platformId = req.VisitorID
default:
c.JSON(200, withError(constant.UnsupportedPlatform))
return
}
// 检查签名是否为keystore中的地址
address := gjson.Get(req.Keystore, "address").String()
binSignature, err := hexutil.Decode(req.Signature)
if err != nil || len(binSignature) < 65 {
c.JSON(200, withError("invalid signature"))
return
}
binSignature[64] -= 27
ecdsaPub, err := crypto.SigToPub(accounts.TextHash([]byte(req.Keystore)), binSignature)
if err != nil {
c.JSON(200, withError("invalid signature"))
return
}
addr := crypto.PubkeyToAddress(*ecdsaPub)
if strings.ToLower(addr.Hex()[2:]) != address {
c.JSON(200, withError("invalid signature"))
return
}
isExistKeystore, uid, keystore, err := srv.CheckUser(req.Platform, platformId)
if err != nil {
c.JSON(200, withError(constant.InternalError))
return
}
token := util.GenerateJWT(uid, req.Platform, platformId)
resp := &apiModel.CheckUserResponse{
IsNewUser: !isExistKeystore,
Keystore: keystore,
Token: token,
}
if !isExistKeystore {
_, err = srv.SetKeystore(uid, address, req.Keystore)
if err != nil {
c.JSON(200, withError(constant.InternalError))
return
}
resp.Keystore = req.Keystore
}
srv.AONServerLogin(address, req.UserId, req.InviterId)
c.JSON(200, withSuccess(resp))
return
}
......@@ -3,6 +3,7 @@ package service
import (
dbModel "sdk_api/model/db"
"github.com/ethereum/go-ethereum/common"
"github.com/google/uuid"
log "github.com/sirupsen/logrus"
)
......@@ -49,3 +50,7 @@ func (s *Service) SetKeystore(uid, address, keystore string) (ok bool, err error
return true, nil
}
func (s *Service) AONServerLogin(address, userId, inviter string) {
s.gs.AonLogin(common.HexToAddress(address), userId, inviter)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment