/
utils.go
317 lines (270 loc) · 7.43 KB
/
utils.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package alchemysdk
import (
"crypto/ecdsa"
"encoding/hex"
"encoding/json"
"errors"
"strings"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"go.uber.org/zap"
"fmt"
"math/big"
)
func padHex(hex string) string {
// add 24 zeros to the left
return strings.Repeat("0", 24) + strings.TrimPrefix(hex, "0x")
}
func encodeAddress(value string) string {
return padHex(strings.ToLower(string(value)))
}
func encodeAbiParameters(types []string, values []interface{}) ([]byte, error) {
if len(types) != len(values) {
return nil, fmt.Errorf("mismatch between types and values length")
}
var encodedData []byte
for i := 0; i < len(types); i++ {
switch types[i] {
case "address":
encodedStr := encodeAddress(values[i].(string))
addressBytes := hexToBytes(encodedStr)
encodedData = append(encodedData, addressBytes...)
case "uint256":
intBytes := values[i].(*big.Int).Bytes()
// Ensure uint256 is 32 bytes long
padSize := 32 - len(intBytes)
padBytes := make([]byte, padSize)
encodedData = append(encodedData, padBytes...)
encodedData = append(encodedData, intBytes...)
case "bytes32":
bytes32Value := hexToBytes32(values[i].(string))
encodedData = append(encodedData, bytes32Value[:]...)
default:
return nil, fmt.Errorf("unsupported type: %s", types[i])
}
}
return encodedData, nil
}
func keccak256(data string) []byte {
// remove 0x prefix if exists
data = strings.TrimPrefix(data, "0x")
// convert hex string to bytes
dataBytes, err := hex.DecodeString(data)
if err != nil {
log.Error("failed to decode hex string", zap.Error(err))
return []byte{}
}
// calculate hash
hash := crypto.Keccak256Hash(dataBytes).Bytes()
return hash
}
func hexToBytes32(hexStr string) [32]byte {
var bytes32Value [32]byte
copy(bytes32Value[:], hexToBytes(hexStr))
return bytes32Value
}
func hexToBytes(hexStr string) []byte {
data, _ := hex.DecodeString(strings.TrimPrefix(hexStr, "0x"))
return data
}
func hexToBigInt(hex string) *big.Int {
// remove 0x prefix if exists
hex = strings.TrimPrefix(hex, "0x")
value := new(big.Int)
value.SetString(hex, 16)
return value
}
func getUserOperationHash(request UserOperation, chainID int64, entryPointAddress common.Address) ([]byte, error) {
uoBytes, err := packUserOperation(request)
if err != nil {
return nil, err
}
// uoBytes to hex string
uoHex := hex.EncodeToString(uoBytes)
uoHexKeccak := "0x" + hex.EncodeToString(keccak256(uoHex))
eap, err := encodeAbiParameters(
[]string{
"bytes32",
"address",
"uint256",
},
[]interface{}{
uoHexKeccak,
entryPointAddress.String(),
big.NewInt(chainID),
},
)
if err != nil {
return nil, err
}
out := keccak256(hex.EncodeToString(eap))
return out, nil
}
func packUserOperation(request UserOperation) ([]byte, error) {
// byte arrays
hashedInitCode := "0x" + hex.EncodeToString(keccak256(request.InitCode))
hashedCallData := "0x" + hex.EncodeToString(keccak256(request.CallData))
hashedPaymasterAndData := "0x" + hex.EncodeToString(keccak256(request.PaymasterAndData))
return encodeAbiParameters(
[]string{
"address",
"uint256",
"bytes32",
"bytes32",
"uint256",
"uint256",
"uint256",
"uint256",
"uint256",
"bytes32",
},
[]interface{}{
request.Sender,
hexToBigInt(request.Nonce),
hashedInitCode,
hashedCallData,
hexToBigInt(request.CallGasLimit),
hexToBigInt(request.VerificationGasLimit),
hexToBigInt(request.PreVerificationGas),
hexToBigInt(request.MaxFeePerGas),
hexToBigInt(request.MaxPriorityFeePerGas),
hashedPaymasterAndData,
},
)
}
func getCallDataForExecute(dest common.Address, originalCallData []byte) ([]byte, error) {
const executeABI = `
[
{
"inputs": [
{
"internalType": "address",
"name": "dest",
"type": "address"
},
{
"internalType": "uint256",
"name": "value",
"type": "uint256"
},
{
"internalType": "bytes",
"name": "func",
"type": "bytes"
}
],
"name": "execute",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
]
`
parsedABI, err := abi.JSON(strings.NewReader(executeABI))
if err != nil {
return nil, err
}
// TODO: value (Ether) is ZERO here!
inputData, err := parsedABI.Pack("execute", dest, big.NewInt(0), originalCallData)
if err != nil {
return nil, err
}
return inputData, nil
}
func signDataWithEthereumPrivateKey(data []byte, privateKeyHex string) ([]byte, error) {
// Generate a new ECDSA private key.
privateKeyECDSA, err := crypto.HexToECDSA(privateKeyHex)
if err != nil {
return nil, err
}
return signDataHashWithEthereumPrivateKey(data, privateKeyECDSA)
}
func signDataHashWithEthereumPrivateKey(dataToSign []byte, privateKeyECDSA *ecdsa.PrivateKey) ([]byte, error) {
if len(dataToSign) != 32 {
return nil, errors.New("dataToSign must be 32 bytes long")
}
// Prepend the "Ethereum Signed Message" prefix.
prefix := "\x19Ethereum Signed Message:\n32" + string(dataToSign)
// Hash the message using Keccak-256.
hash := crypto.Keccak256([]byte(prefix))
signature, err := crypto.Sign(hash, privateKeyECDSA)
if err != nil {
return nil, err
}
//return CompactSignature(signature)
// TODO: fix +27 please!
// Encode the signature in Ethereum's compact signature format.
out := append(signature[:64], signature[64]+27)
return out, nil
}
func appendEntryPointAddress(jsonData []byte, entryPointAddress common.Address) ([]byte, error) {
// Define a struct to represent the JSON data
var data map[string]interface{}
// Parse the JSON data into the struct
if err := json.Unmarshal([]byte(jsonData), &data); err != nil {
log.Error("failed to unmarshal JSON", zap.Error(err))
return nil, err
}
// Add the custom value to the 'params' array
paramsArray, ok := data["params"].([]interface{})
if !ok {
log.Error("'params' field is not an array")
return nil, errors.New("'params' field is not an array")
}
paramsArray = append(paramsArray, entryPointAddress.String())
data["params"] = paramsArray
// Encode the modified data back to JSON
outputJSON, err := json.Marshal(data)
if err != nil {
log.Error("error encoding JSON:", zap.Error(err))
return nil, err
}
return outputJSON, nil
}
func getAccountInitCode(eoa common.Address, factoryAddr common.Address) ([]byte, error) {
const jsondata = `
[
{
"inputs": [
{
"internalType": "address",
"name": "owner",
"type": "address"
},
{
"internalType": "uint256",
"name": "salt",
"type": "uint256"
}
],
"name": "createAccount",
"outputs": [
{
"internalType": "contract SimpleAccount",
"name": "ret",
"type": "address"
}
],
"stateMutability": "nonpayable",
"type": "function"
}
]
`
factoryABI, err := abi.JSON(strings.NewReader(jsondata))
if err != nil {
log.Error("error parsing ABI:", zap.Error(err))
return nil, err
}
// salt is 0
data, err := factoryABI.Pack("createAccount", eoa, big.NewInt(0))
if err != nil {
log.Error("error encoding function data", zap.Error(err))
return nil, nil
}
// log data
log.Debug("data: ", zap.String("data", hex.EncodeToString(data)))
// prepend factory address
data = append(factoryAddr.Bytes(), data...)
return data, nil
}