forked from TP-Lab/etherquery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransaction_exporter.go
414 lines (394 loc) · 13.5 KB
/
transaction_exporter.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
package main
import (
"container/list"
"context"
"encoding/json"
"fmt"
"github.com/Jeffail/gabs"
log "github.com/cihub/seelog"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/params"
"math"
"math/big"
"strings"
"sync"
"time"
)
type TransactionExporter struct {
appConfig *AppConfig
chainConfig *params.ChainConfig
ethereum *eth.Ethereum
traceConfig *eth.TraceConfig
privateDebugAPI *eth.PrivateDebugAPI
saver Saver
}
func NewTransactionExporter(appConfig *AppConfig, ethereum *eth.Ethereum) *TransactionExporter {
var saver Saver = &MongoSaver{}
if appConfig.Saver == "mongo" {
saver = &MongoSaver{
appConfig: appConfig,
}
} else if appConfig.Saver == "http" {
saver = &HttpSaver{
appConfig: appConfig,
}
} else {
saver = &DummySaver{
appConfig: appConfig,
}
}
tracerType := "callTracer"
traceConfig := ð.TraceConfig{
Tracer: &tracerType,
LogConfig: &vm.LogConfig{
DisableMemory: false,
DisableStack: false,
DisableStorage: false,
},
Timeout: &appConfig.Timeout,
Reexec: &appConfig.Reexec,
}
privateDebugAPI := eth.NewPrivateDebugAPI(ethereum)
return &TransactionExporter{
appConfig: appConfig,
chainConfig: ethereum.BlockChain().Config(),
ethereum: ethereum,
traceConfig: traceConfig,
privateDebugAPI: privateDebugAPI,
saver: saver,
}
}
func (s *TransactionExporter) ExportGenesisBlocks(block *types.Block, stateDump state.Dump) (int64, error) {
var transactionList []Transaction
i := 0
for address, account := range stateDump.Accounts {
balance, ok := new(big.Int).SetString(account.Balance, 10)
if !ok {
log.Errorf("could not decode balance %v of genesis account", account.Balance)
}
transaction := Transaction{}
transaction.Timestamp = *big.NewInt(int64(block.Time()))
transaction.BlockNumber = *block.Number()
transaction.TokenValue = *big.NewInt(0)
transaction.Gas = *big.NewInt(0)
transaction.GasPrice = *big.NewInt(0)
transaction.UsedGas = *big.NewInt(0)
transaction.Value = *balance
transaction.Hash = common.Hash{}.String()
transaction.Nonce = account.Nonce
transaction.BlockHash = block.Hash().String()
transaction.TransactionIndex = *big.NewInt(int64(i))
transaction.LogIndex = *LogIndexDefault
transaction.From = common.Address{}.String()
transaction.To = address.String()
transaction.ContractAddress = ""
transaction.TokenType = TokenTypeDefault
transaction.Data = nil
transaction.Status = TransactionStatusSuccess
transactionList = append(transactionList, transaction)
i += 1
}
return s.saver.SaveTransactionList(transactionList)
}
//todo 完善逻辑
func (s *TransactionExporter) ExportRemovedLogs(log1 *types.Log) (int64, error) {
marshal, _ := json.Marshal(log1)
log.Warnf("%v", string(marshal))
return 0, nil
}
func (s *TransactionExporter) ExportPendingTx(tx *types.Transaction) (int64, error) {
signer := types.MakeSigner(s.chainConfig, big.NewInt(math.MaxInt64))
fromAddress, err := types.Sender(signer, tx)
if err != nil {
log.Errorf("sender %v error %v", tx.Hash().String(), err)
return -1, err
}
toAddress := tx.To()
var to string
if toAddress != nil {
to = toAddress.String()
}
transaction := Transaction{
Timestamp: *big.NewInt(time.Now().Unix()), //pending状态还没有这个值
BlockNumber: *big.NewInt(0), //pending状态还没有这个值
TokenValue: *big.NewInt(0),
Value: *tx.Value(),
Hash: tx.Hash().String(),
Nonce: tx.Nonce(),
BlockHash: "", //pending状态还没有这个值
TransactionIndex: *big.NewInt(int64(0)),
LogIndex: *LogIndexDefault,
InternalIndex: InternalIndexDefault,
From: fromAddress.String(),
To: to,
ContractAddress: "",
TokenType: TokenTypeDefault,
Data: []byte(hexutil.Encode(tx.Data())),
Gas: *big.NewInt(int64(tx.Gas())),
GasPrice: *tx.GasPrice(),
UsedGas: *big.NewInt(int64(tx.Gas())),
Status: TransactionStatusPending,
}
s.parseTransactionTokenInfo(&transaction, nil)
return s.saver.SaveTransactionList([]Transaction{transaction})
}
func (s *TransactionExporter) parseTransactionTokenInfo(transaction *Transaction, receipt *types.Receipts) *Transaction {
if transaction.Data == nil {
return transaction
}
data := transaction.Data
// Function: transfer(address _to, uint256 _value)
// MethodID: 0xa9059cbb
// 0xa9059cbb000000000000000000000000
// [0]:00000000000000000000000075186ece18d7051afb9c1aee85170c0deda23d82
// [1]:0000000000000000000000000000000000000000000000364db9fbe6a7902000
if len(data) > 74 && string(data[:10]) == "0xa9059cbb" {
//tx.MethodId = string(data[:10])
transaction.ContractAddress = transaction.To
if receipt != nil {
if len(*receipt) > 0 {
contractAddress := (*receipt)[0].ContractAddress.String()
if contractAddress != transaction.ContractAddress {
transaction.ContractAddress = contractAddress
log.Warnf("transaction %v to %v not equal contract address of receipt %v", transaction.Hash, transaction.To, contractAddress)
}
}
}
transaction.To = string(append([]byte{'0', 'x'}, data[34:74]...))
transaction.TokenValue.UnmarshalJSON(append([]byte{'0', 'x'}, data[74:]...))
transaction.TokenType = TokenTypeToken
}
return transaction
}
func (s *TransactionExporter) ExportBlock(block *types.Block) (int64, error) {
if block == nil || len(block.Transactions()) == 0 {
return 0, nil
}
signer := types.MakeSigner(s.chainConfig, block.Number())
lock := &sync.Mutex{}
wg := &sync.WaitGroup{}
var result []Transaction
for index, _ := range block.Transactions() {
wg.Add(1)
go func(index int) {
defer wg.Done()
transactionList, _ := s.processTx(signer, block, index)
if len(transactionList) > 0 {
func() {
lock.Lock()
defer lock.Unlock()
result = append(result, transactionList...)
}()
}
}(index)
}
wg.Wait()
return s.saver.SaveTransactionList(result)
}
func (s *TransactionExporter) processTx(signer types.Signer, block *types.Block, index int) ([]Transaction, error) {
var transactionList []Transaction
tx := block.Transactions()[index]
fromAddress, err := types.Sender(signer, tx)
if err != nil {
log.Errorf("sender %v error %v", tx.Hash().String(), err)
return nil, err
}
toAddress := tx.To()
var to string
if toAddress != nil {
to = toAddress.String()
}
transaction := Transaction{
Timestamp: *big.NewInt(int64(block.Time())),
BlockNumber: *block.Number(),
TokenValue: *big.NewInt(0),
Value: *tx.Value(),
Hash: tx.Hash().String(),
Nonce: tx.Nonce(),
BlockHash: block.Hash().String(),
TransactionIndex: *big.NewInt(int64(index)),
LogIndex: *LogIndexDefault,
InternalIndex: InternalIndexDefault,
From: fromAddress.String(),
To: to,
ContractAddress: "",
TokenType: TokenTypeDefault,
Data: []byte(hexutil.Encode(tx.Data())),
Gas: *big.NewInt(int64(tx.Gas())),
GasPrice: *tx.GasPrice(),
UsedGas: *big.NewInt(int64(tx.Gas())),
Status: TransactionStatusSuccess,
}
receiptsList, err := s.ethereum.APIBackend.GetReceipts(context.Background(), tx.Hash())
if err != nil {
log.Errorf("get receipts by %v error %v", tx.Hash().String(), err)
}
if receiptsList == nil {
s.parseTransactionTokenInfo(&transaction, nil)
} else {
s.parseTransactionTokenInfo(&transaction, &receiptsList)
}
if len(receiptsList) > 0 {
marshal1, _ := json.Marshal(receiptsList)
log.Infof("receiptsList %v %v", tx.Hash().String(), string(marshal1))
for _, receipt := range receiptsList {
transaction.Status = receipt.Status
for _, log1 := range receipt.Logs {
if len(log1.Topics) <= 0 {
continue
}
eventFunSign := log1.Topics[0].String()
//keccak256("Transfer(address,address,uint256)")
if !(eventFunSign == "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef" &&
len(log1.Topics) == 3) {
// 跳过不是transfer转账类型
continue
}
transaction1 := &Transaction{
Timestamp: *big.NewInt(int64(block.Time())),
Gas: *big.NewInt(int64(receipt.CumulativeGasUsed)),
GasPrice: *tx.GasPrice(),
UsedGas: *big.NewInt(int64(receipt.GasUsed)),
Hash: tx.Hash().String(),
Nonce: tx.Nonce(),
From: fromAddress.String(),
To: to,
Status: receipt.Status,
}
topic1 := log1.Topics[1].Bytes()
transaction1.From = string(topic1[len(topic1)-40 : len(topic1)])
if !strings.HasPrefix(transaction1.From, "0x") {
transaction1.From = "0x" + transaction1.From
}
topic2 := log1.Topics[2].Bytes()
transaction1.To = string(topic2[len(topic2)-40 : len(topic2)])
if !strings.HasPrefix(transaction1.To, "0x") {
transaction1.To = "0x" + transaction1.To
}
transaction1.ContractAddress = log1.Address.String()
transaction1.TokenType = TokenTypeToken
transaction1.BlockHash = log1.BlockHash.String()
transaction1.BlockNumber = *big.NewInt(int64(log1.BlockNumber))
transaction1.TransactionIndex = *big.NewInt(int64(log1.TxIndex))
transaction1.LogIndex = *big.NewInt(int64(log1.Index))
transaction1.InternalIndex = InternalIndexDefault
transaction1.TokenValue.UnmarshalJSON(log1.Data)
transactionList = append(transactionList, *transaction1)
}
}
}
var rawMessageInterface interface{}
func() {
startTime := time.Now().UnixNano()
defer func() {
elapse := (time.Now().UnixNano() - startTime) / 10e6
if elapse > 500 {
log.Infof("trace transaction %v elapse time %vms", tx.Hash().String(), elapse)
}
}()
rawMessageInterface, err = s.privateDebugAPI.TraceTransaction(context.Background(), tx.Hash(), s.traceConfig)
}()
if err != nil {
log.Errorf("trace transaction %v error %v", tx.Hash().String(), err)
//设置超时状态
if strings.Contains(err.Error(), "execution timeout") {
transaction.Status = TransactionStatusTimeout
}
} else {
if rawMessageInterface != nil {
rawMessage := rawMessageInterface.(json.RawMessage)
jsonParsed, err := gabs.ParseJSON(rawMessage)
if err != nil {
log.Errorf("parse json %v error %v", string(rawMessage), err)
} else {
//标记当前交易是什么op code
if jsonParsed.ExistsP("type") {
typeData := jsonParsed.Path("type").Data()
if typeData != nil {
transaction.OpCode = typeData.(string)
}
}
if jsonParsed.ExistsP("calls") {
log.Debugf("rawMessage %v %v", tx.Hash().String(), jsonParsed.String())
internalIndex := transaction.InternalIndex
children, _ := jsonParsed.S("calls").Children()
var internalTransactionList = list.New()
for i, child := range children {
newInternalIndex := fmt.Sprintf("%v_%v", internalIndex, i)
s.parseRawMessage(newInternalIndex, transaction, block, tx, child, internalTransactionList)
}
for element := internalTransactionList.Front(); element != nil; element = element.Next() {
transactionList = append(transactionList, element.Value.(Transaction))
}
}
}
}
}
transactionList = append(transactionList, transaction)
return transactionList, nil
}
func (s *TransactionExporter) parseRawMessage(internalIndex string, parentTransaction Transaction, block *types.Block, tx *types.Transaction, jsonParsed *gabs.Container, internalTransactionList *list.List) {
transaction := Transaction{
Timestamp: *big.NewInt(int64(block.Time())),
BlockNumber: *block.Number(),
Hash: tx.Hash().String(),
Nonce: tx.Nonce(),
BlockHash: block.Hash().String(),
TransactionIndex: parentTransaction.TransactionIndex,
LogIndex: parentTransaction.LogIndex,
TokenType: TokenTypeDefault,
GasPrice: *tx.GasPrice(),
Status: parentTransaction.Status,
}
valueData := jsonParsed.Path("value").Data()
if valueData != nil {
transaction.Value.UnmarshalJSON([]byte(valueData.(string)))
}
//丢弃value=0的合约调用
if transaction.Value.Uint64() > 0 {
fromData := jsonParsed.Path("from").Data()
if fromData != nil {
transaction.From = fromData.(string)
}
toData := jsonParsed.Path("to").Data()
if toData != nil {
transaction.To = toData.(string)
}
typeData := jsonParsed.Path("type").Data()
if typeData != nil {
transaction.OpCode = typeData.(string)
}
gasData := jsonParsed.Path("gas").Data()
if gasData != nil {
transaction.Gas.UnmarshalJSON([]byte(gasData.(string)))
}
gasUsedData := jsonParsed.Path("gasUsed").Data()
if gasUsedData != nil {
transaction.UsedGas.UnmarshalJSON([]byte(gasUsedData.(string)))
}
inputData := jsonParsed.Path("input").Data()
if inputData != nil {
transaction.Data = []byte(inputData.(string))
}
if jsonParsed.Exists("error") {
transaction.Err = jsonParsed.Path("error").Data().(string)
if transaction.Err != "" {
transaction.Status = TransactionStatusFailed
}
}
transaction.InternalIndex = internalIndex
internalTransactionList.PushBack(transaction)
}
if jsonParsed.ExistsP("calls") {
children, _ := jsonParsed.S("calls").Children()
for index, child := range children {
newInternalIndex := fmt.Sprintf("%v_%v", internalIndex, index)
s.parseRawMessage(newInternalIndex, transaction, block, tx, child, internalTransactionList)
}
}
}