-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
295 lines (266 loc) · 7.73 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package main
import (
"context"
"fmt"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"math/big"
"os"
"strconv"
"sync"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
"go.uber.org/zap"
"net/http"
)
var (
logger *zap.Logger
cfg *viper.Viper
)
type RequestBody struct {
Network string `json:"network"`
Address string `json:"address"`
Amount string `json:"amount"`
}
type ApiResponse struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
TxId string `json:"tx_id,omitempty"`
ExplorerUrl string `json:"explorer_url,omitempty"`
}
type RateLimiter struct {
lastRequestTime map[string]time.Time // 存储每个用户的最后一次请求时间
mu sync.Mutex // 互斥锁,用于保护并发访问
requestInterval time.Duration // 请求时间间隔
}
// NewRateLimiter 创建一个新的 RateLimiter 实例
func NewRateLimiter(interval time.Duration) *RateLimiter {
return &RateLimiter{
lastRequestTime: make(map[string]time.Time),
requestInterval: interval,
}
}
// Limit 中间件函数,用于限制每个用户每24小时只能请求一次
func (rl *RateLimiter) Limit() gin.HandlerFunc {
return func(c *gin.Context) {
var requestBody RequestBody
if err := c.ShouldBindBodyWithJSON(&requestBody); err != nil {
c.JSON(http.StatusBadRequest, ApiResponse{
Success: false,
Message: err.Error(),
})
return
}
Address := requestBody.Address
fmt.Println(Address)
rl.mu.Lock()
defer rl.mu.Unlock()
lastTime, ok := rl.lastRequestTime[Address]
if ok && time.Since(lastTime) < rl.requestInterval {
c.JSON(http.StatusTooManyRequests, gin.H{"error": "Only one request allowed per specified interval"})
c.Abort()
return
}
// 更新用户的最后一次请求时间
rl.lastRequestTime[Address] = time.Now()
c.Next()
}
}
func main() {
var err error
// 初始化日志记录器
initLogger()
defer func(logger *zap.Logger) {
err := logger.Sync()
if err != nil {
fmt.Println("Failed to sync logger:", err)
}
}(logger)
logger, err = zap.NewProduction()
// 初始化配置管理器
cfg, err = initConfig()
if err != nil {
logger.Error("Failed to initialize config", zap.Error(err))
os.Exit(1)
}
// 创建 Gin 引擎
r := gin.Default()
rateLimiterStr := cfg.GetString("rate_limiter")
rateLimiter, err := strconv.Atoi(rateLimiterStr)
if err != nil {
panic(err)
}
limiter := NewRateLimiter(time.Duration(rateLimiter) * time.Hour)
r.Use(limiter.Limit())
// 设置路由
r.POST("/ether/request", handleWithdraw)
// 启动 HTTP 服务器
port := cfg.GetInt("port")
err = r.Run(":" + strconv.Itoa(port))
if err != nil {
logger.Fatal("Failed to start server", zap.Error(err))
}
}
// handleWithdraw 处理领水请求
func handleWithdraw(c *gin.Context) {
var requestBody RequestBody
if err := c.ShouldBindBodyWithJSON(&requestBody); err != nil {
c.JSON(http.StatusBadRequest, ApiResponse{
Success: false,
Message: err.Error(),
})
return
}
Address := requestBody.Address
if !common.IsHexAddress(Address) {
c.JSON(http.StatusBadRequest, ApiResponse{
Success: false,
Message: "The Ethereum wallet address you entered does not meet the standard format. Please check and enter a valid wallet address.",
})
return
}
float, err := strconv.ParseFloat(requestBody.Amount, 64)
if err != nil {
fmt.Println("Error converting string to float64:", err)
return
}
amount := big.NewFloat(float) //big.NewInt(cfg.GetInt64("amount"))
amount.Mul(amount, big.NewFloat(1e18))
amountInt := new(big.Int)
amount.Int(amountInt)
fmt.Println(amount)
network := requestBody.Network
nodeURL := cfg.GetString(network + ".node_url")
senderAddress := cfg.GetString(network + ".sender_address")
client, err := ethclient.Dial(nodeURL)
if err != nil {
logger.Error("Failed to connect to Ethereum client", zap.Error(err))
c.JSON(http.StatusInternalServerError, ApiResponse{
Success: false,
Message: "Failed to connect to Ethereum client",
})
return
}
defer client.Close()
privateKeyString := cfg.GetString(network + ".private_key")
// 将私钥字符串转换为ECDSA私钥
privateKey, err := crypto.HexToECDSA(privateKeyString)
if err != nil {
logger.Error("Failed to decode private key", zap.Error(err))
c.JSON(http.StatusInternalServerError, ApiResponse{
Success: false,
Message: "Failed to decode private key",
})
return
}
toAddress := common.HexToAddress(Address)
// 初始化发送地址
fromAddress := common.HexToAddress(senderAddress)
// 获取nonce值,即从该发送地址出的交易数量
nonce, err := client.PendingNonceAt(context.Background(), fromAddress)
if err != nil {
logger.Error("Failed to get nonce", zap.Error(err))
c.JSON(http.StatusInternalServerError, ApiResponse{
Success: false,
Message: "Internal error",
})
return
}
// 获取当前的燃气价格
gasPrice, err := client.SuggestGasPrice(context.Background())
if err != nil {
logger.Error("Failed to suggest gas price", zap.Error(err))
c.JSON(http.StatusInternalServerError, ApiResponse{
Success: false,
Message: "Internal error",
})
return
}
gasLimit := uint64(21000)
gasTinCap, err := client.SuggestGasTipCap(context.Background())
if err != nil {
logger.Error("Failed to suggest gas price", zap.Error(err))
c.JSON(http.StatusInternalServerError, ApiResponse{
Success: false,
Message: "Internal error",
})
return
}
chainID, err := client.NetworkID(context.Background())
if err != nil {
logger.Error("Failed to get network ID", zap.Error(err))
c.JSON(http.StatusInternalServerError, ApiResponse{
Success: false,
Message: "Failed to get network ID",
})
return
}
// 创建交易对象
tx := types.NewTx(&types.DynamicFeeTx{
ChainID: chainID,
Nonce: nonce,
GasTipCap: gasTinCap,
GasFeeCap: gasPrice,
Gas: gasLimit,
To: &toAddress,
Value: amountInt,
Data: nil,
})
signedTx, err := types.SignTx(tx, types.NewLondonSigner(chainID), privateKey)
if err != nil {
logger.Error("Failed to sign transaction", zap.Error(err))
c.JSON(http.StatusInternalServerError, ApiResponse{
Success: false,
Message: "Failed to sign transaction",
})
return
}
err = client.SendTransaction(context.Background(), signedTx)
if err != nil {
logger.Error("Failed to send transaction", zap.Error(err))
c.JSON(http.StatusInternalServerError, ApiResponse{
Success: false,
Message: fmt.Sprintf("Failed to withdraw: %s", err.Error()),
})
return
}
explorerUrl := fmt.Sprintf("https://%s.etherscan.io/", network)
c.JSON(http.StatusOK, ApiResponse{
Success: true,
TxId: signedTx.Hash().Hex(),
ExplorerUrl: fmt.Sprintf("%s/tx/%s", explorerUrl, signedTx.Hash().Hex()),
})
}
// initLogger 初始化日志记录器
func initLogger() {
var err error
logger, err = zap.NewProduction()
if err != nil {
fmt.Println("Failed to initialize logger:", err)
os.Exit(1)
}
}
// initConfig 初始化配置管理器
func initConfig() (*viper.Viper, error) {
v := viper.New()
v.SetConfigName("config")
v.AddConfigPath("./configs")
v.SetConfigType("yaml")
err := v.ReadInConfig()
if err != nil {
return nil, err
}
logger.Info("Config initialized successfully")
// 设置默认值
v.SetDefault("amount", "1")
v.SetDefault("port", "8080")
v.SetDefault("rate_limiter", "24")
v.SetDefault("holesky.node_url", "https://holesky.infura.io/v3/YOUR_INFURA_PROJECT_ID")
v.SetDefault("holesky.sender_address", "YOUR_HOLESKY_SENDER_ADDRESS")
v.SetDefault("sepolia.node_url", "https://sepolia.infura.io/v3/YOUR_INFURA_PROJECT_ID")
v.SetDefault("sepolia.sender_address", "YOUR_SEPOLIA_SENDER_ADDRESS")
return v, nil
}