forked from chenzhijie/go-web3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flashbots.go
293 lines (243 loc) · 6.87 KB
/
flashbots.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
package flashbots
import (
"crypto/ecdsa"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math/big"
"os"
"strconv"
"strings"
"github.com/ethereum/go-ethereum/common/hexutil"
eTypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/laziercoder/go-web3/rpc/transport"
"github.com/valyala/fasthttp"
)
type FlashBot struct {
httpClient *transport.HTTP
providerURL string
signerPrivateKey *ecdsa.PrivateKey
}
// NewFlashBot, init flashbot instance
// providerURL: flashbot provider http url
// rpcRequestSigner: private key for signing request message
// proxyAddr: http proxy or socks5 proxy addr
func NewFlashBot(providerURL, rpcRequestSigner string) (*FlashBot, error) {
signerKeyData, err := hex.DecodeString(strings.TrimPrefix(rpcRequestSigner, "0x"))
if err != nil {
return nil, err
}
signerPrivateKey, err := crypto.ToECDSA(signerKeyData)
if err != nil {
return nil, err
}
httpClient := transport.NewHTTP(providerURL, os.Getenv("http_proxy"))
fb := &FlashBot{
httpClient: httpClient,
providerURL: providerURL,
signerPrivateKey: signerPrivateKey,
}
return fb, nil
}
func (fb *FlashBot) SendBundle(txs []*eTypes.Transaction, targetBlockNumber *big.Int) (*BundleResult, error) {
bundles := make([]string, 0)
for _, tx := range txs {
txData, err := tx.MarshalBinary()
if err != nil {
return nil, err
}
bundles = append(bundles, hexutil.Encode(txData))
}
return fb.SendRawBundle(bundles, targetBlockNumber)
}
func (fb *FlashBot) SendRawBundle(transactions []string, targetBlockNumber *big.Int) (*BundleResult, error) {
type SendBundleParams struct {
Transactions []string `json:"txs"`
BlockNumber string `json:"blockNumber"`
MinTimestamp int64 `json:"minTimestamp,omitempty"`
MaxTimestamp int64 `json:"maxTimestamp,omitempty"`
RevertingTxHashes []string `json:"revertingTxHashes,omitempty"`
}
params := SendBundleParams{
Transactions: transactions,
BlockNumber: fmt.Sprintf("0x%x", targetBlockNumber),
}
httpResp, err := fb.sendRequest(
fb.providerURL,
"eth_sendBundle",
[]interface{}{params},
)
if err != nil {
return nil, err
}
var resp struct {
ID uint64 `json:"id"`
Error interface{} `json:"error,omitempty"`
Result BundleResult `json:"result"`
}
err = json.Unmarshal(httpResp, &resp)
if err != nil {
return nil, err
}
if resp.Error != nil {
errMsg, ok := resp.Error.(string)
if ok {
return nil, errors.New(errMsg)
}
return nil, fmt.Errorf("send request err %v", resp.Error)
}
return &resp.Result, nil
}
func (fb *FlashBot) CallRawBundle(transactions []string, blockNumber *big.Int, stateBlockNumber string) (*CallResult, error) {
type CallBundleParams struct {
Transactions []string `json:"txs"`
BlockNumber string `json:"blockNumber"`
StateBlockNumber string `json:"stateBlockNumber"`
}
params := CallBundleParams{
Transactions: transactions,
BlockNumber: fmt.Sprintf("0x%x", blockNumber.Uint64()),
StateBlockNumber: stateBlockNumber,
}
httpResp, err := fb.sendRequest(fb.providerURL, "eth_callBundle", []interface{}{params})
if err != nil {
return nil, err
}
var resp struct {
ID uint64 `json:"id"`
Error interface{} `json:"error,omitempty"`
Result CallResult `json:"result"`
}
err = json.Unmarshal(httpResp, &resp)
if err != nil {
return nil, err
}
if resp.Error != nil {
errMsg, ok := resp.Error.(string)
if ok {
return nil, errors.New(errMsg)
}
return nil, fmt.Errorf("send request err %v", resp.Error)
}
return &resp.Result, nil
}
func (fb *FlashBot) GetUserStats(blockNumber *big.Int) (*UserStats, error) {
httpResp, err := fb.sendRequest(fb.providerURL, "flashbots_getUserStats", []interface{}{fmt.Sprintf("0x%x", blockNumber.Uint64())})
if err != nil {
return nil, err
}
var resp struct {
ID uint64 `json:"id"`
Error interface{} `json:"error,omitempty"`
Result UserStats `json:"result"`
}
err = json.Unmarshal(httpResp, &resp)
if err != nil {
return nil, err
}
if resp.Error != nil {
errMsg, ok := resp.Error.(string)
if ok {
return nil, errors.New(errMsg)
}
return nil, fmt.Errorf("send request err %v", resp.Error)
}
return &resp.Result, nil
}
func (fb *FlashBot) GetBunderStats(bundleHash string, blockNumber *big.Int) (*BundleStats, error) {
type reqParam struct {
BundleHash string `json:"bundleHash"`
BlockNumber string `json:"blockNumber"`
}
param := &reqParam{
BundleHash: bundleHash,
BlockNumber: fmt.Sprintf("0x%x", blockNumber.Uint64()),
}
httpResp, err := fb.sendRequest(fb.providerURL,
"flashbots_getBundleStats",
[]interface{}{
param,
})
if err != nil {
return nil, err
}
fmt.Printf("httpResp %s\n", httpResp)
var resp struct {
ID uint64 `json:"id"`
Error interface{} `json:"error,omitempty"`
Result BundleStats `json:"result"`
}
err = json.Unmarshal(httpResp, &resp)
if err != nil {
return nil, err
}
if resp.Error != nil {
errMsg, ok := resp.Error.(string)
if ok {
return nil, errors.New(errMsg)
}
return nil, fmt.Errorf("send request err %v", resp.Error)
}
return &resp.Result, nil
}
func (fb *FlashBot) Simulate(
txs []*eTypes.Transaction,
blockNumber *big.Int,
stateBlockNumber string,
) (*CallResult, error) {
transactions := make([]string, 0)
for _, tx := range txs {
txData, err := tx.MarshalBinary()
if err != nil {
return nil, err
}
transactions = append(transactions, hexutil.Encode(txData))
}
return fb.CallRawBundle(transactions, blockNumber, stateBlockNumber)
}
func (fb *FlashBot) SimulateRaw(
transactions []string,
blockNumber *big.Int,
stateBlockNumber string,
) (*CallResult, error) {
return fb.CallRawBundle(transactions, blockNumber, stateBlockNumber)
}
func (fb *FlashBot) sendRequest(relay string, method string, params []interface{}) ([]byte, error) {
payload, err := json.Marshal(map[string]interface{}{
"jsonrpc": "2.0",
"id": 1,
"method": method,
"params": params,
})
if err != nil {
return nil, err
}
req := fasthttp.AcquireRequest()
res := fasthttp.AcquireResponse()
defer fasthttp.ReleaseRequest(req)
defer fasthttp.ReleaseResponse(res)
req.SetRequestURI(relay)
req.Header.SetMethod("POST")
req.Header.SetContentType("application/json")
req.SetBody(payload)
fbHeader, err := fb.flashbotHeader(payload)
if err != nil {
return nil, err
}
req.Header.Add("X-Flashbots-Signature", fbHeader)
return fb.httpClient.Do(req, res)
}
func (fb *FlashBot) flashbotHeader(payload []byte) (string, error) {
hashedPayload := crypto.Keccak256Hash(payload).Hex()
signature, err := crypto.Sign(
crypto.Keccak256([]byte("\x19Ethereum Signed Message:\n"+strconv.Itoa(len(hashedPayload))+hashedPayload)),
fb.signerPrivateKey,
)
if err != nil {
return "", err
}
return crypto.PubkeyToAddress(fb.signerPrivateKey.PublicKey).Hex() +
":" + hexutil.Encode(signature), nil
}