-
Notifications
You must be signed in to change notification settings - Fork 17
/
fnsignatures.go
344 lines (294 loc) · 8.88 KB
/
fnsignatures.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
package services
import (
"bytes"
"encoding/json"
"fmt"
"io"
"strings"
"sync"
"time"
nethttp "net/http"
"github.com/pk910/dora/db"
"github.com/pk910/dora/dbtypes"
"github.com/pk910/dora/types"
"github.com/pk910/dora/utils"
"github.com/sirupsen/logrus"
)
type TxSignaturesService struct {
}
var GlobalTxSignaturesService *TxSignaturesService
var logger_tss = logrus.StandardLogger().WithField("module", "txsig")
type TxSignaturesLookup struct {
Bytes types.TxSignatureBytes
Signature string
Name string
Status types.TxSignatureLookupStatus
}
// StartTxSignaturesService is used to start the global transaction signatures service
func StartTxSignaturesService() error {
if GlobalTxSignaturesService != nil {
return nil
}
concurrencyLimit := utils.Config.TxSignature.ConcurrencyLimit
if concurrencyLimit == 0 {
concurrencyLimit = 10
}
GlobalTxSignaturesService = &TxSignaturesService{}
if !utils.Config.TxSignature.DisableLookupLoop {
go GlobalTxSignaturesService.runLookupLoop()
}
return nil
}
func (tss *TxSignaturesService) LookupSignatures(sigBytes []types.TxSignatureBytes) map[types.TxSignatureBytes]*TxSignaturesLookup {
lookups := map[types.TxSignatureBytes]*TxSignaturesLookup{}
unresolvedLookups := make([]*TxSignaturesLookup, 0)
unresolvedLookupBytes := make([]types.TxSignatureBytes, 0)
for i, bytes := range sigBytes {
if lookups[bytes] != nil {
continue
}
lookup := &TxSignaturesLookup{
Bytes: bytes,
}
unresolvedLookups = append(unresolvedLookups, lookup)
unresolvedLookupBytes = append(unresolvedLookupBytes, sigBytes[i])
lookups[bytes] = lookup
}
// check known signatures in DB
if len(unresolvedLookups) > 0 {
for _, dbSigEntry := range db.GetTxFunctionSignaturesByBytes(unresolvedLookupBytes) {
var lookup *TxSignaturesLookup
for i, l := range unresolvedLookups {
if l == nil {
continue
}
if bytes.Equal(l.Bytes[:], dbSigEntry.Bytes) {
lookup = l
unresolvedLookups[i] = nil
break
}
}
if lookup == nil {
break
}
lookup.Status = types.TxSigStatusFound
lookup.Signature = dbSigEntry.Signature
lookup.Name = dbSigEntry.Name
}
nonfoundLookups := make([]*TxSignaturesLookup, 0)
nonfoundLookupBytes := make([]types.TxSignatureBytes, 0)
for i, l := range unresolvedLookups {
if l != nil {
nonfoundLookups = append(nonfoundLookups, unresolvedLookups[i])
nonfoundLookupBytes = append(nonfoundLookupBytes, unresolvedLookups[i].Bytes)
}
}
unresolvedLookups = nonfoundLookups
unresolvedLookupBytes = nonfoundLookupBytes
}
// check unknown signatures in DB (previous failed sig lookups)
if len(unresolvedLookups) > 0 {
recheckTime := int64(utils.Config.TxSignature.RecheckTimeout.Seconds())
if recheckTime == 0 {
recheckTime = 86400
}
checkTimeout := time.Now().Unix() - recheckTime
for _, unknownSigEntry := range db.GetUnknownFunctionSignatures(unresolvedLookupBytes) {
if unknownSigEntry.LastCheck < uint64(checkTimeout) {
break
}
var lookup *TxSignaturesLookup
for i, l := range unresolvedLookups {
if l == nil {
continue
}
if bytes.Equal(l.Bytes[:], unknownSigEntry.Bytes) {
lookup = l
unresolvedLookups[i] = nil
break
}
}
if lookup == nil {
break
}
lookup.Status = types.TxSigStatusUnknown
}
nonfoundLookups := make([]*TxSignaturesLookup, 0)
for _, l := range unresolvedLookups {
if l == nil {
break
}
nonfoundLookups = append(nonfoundLookups, l)
}
unresolvedLookups = nonfoundLookups
}
// add pending signature lookups
if len(unresolvedLookups) > 0 && !utils.Config.TxSignature.DisableLookupLoop {
pendingLookups := make([]*dbtypes.TxPendingFunctionSignature, 0)
for _, l := range unresolvedLookups {
pendingLookups = append(pendingLookups, &dbtypes.TxPendingFunctionSignature{
Bytes: l.Bytes[:],
QueueTime: uint64(time.Now().Unix()),
})
}
//logger_tss.Infof("starting db transaction (pending sig)")
tx, err := db.WriterDb.Beginx()
if err != nil {
logger_tss.Warnf("error starting db transaction: %v", err)
} else {
defer tx.Rollback()
err := db.InsertPendingFunctionSignatures(pendingLookups, tx)
if err != nil {
logger_tss.Warnf("error saving pending signature: %v", err)
}
//logger_tss.Infof("stopping db transaction (pending sig)")
if err := tx.Commit(); err != nil {
logger_tss.Warnf("error committing db transaction: %v", err)
}
}
}
return lookups
}
func (tss *TxSignaturesService) runLookupLoop() {
defer utils.HandleSubroutinePanic("txsig.loop")
loopInterval := utils.Config.TxSignature.LookupInterval
if loopInterval == 0 {
loopInterval = 10 * time.Second
}
for {
//logger_tss.Infof("tx signatures processing loop")
startTime := time.Now()
tss.processPendingSignatures()
loopDelay := time.Since(startTime)
if loopDelay < loopInterval {
time.Sleep(loopInterval - loopDelay)
}
}
}
func (tss *TxSignaturesService) processPendingSignatures() {
batchLimit := utils.Config.TxSignature.LookupBatchSize
if batchLimit == 0 {
batchLimit = 10
}
pendingSigs := db.GetPendingFunctionSignatures(batchLimit)
wg := sync.WaitGroup{}
lookups := make([]*TxSignaturesLookup, 0)
for _, pendingSig := range pendingSigs {
lookup := &TxSignaturesLookup{
Bytes: types.TxSignatureBytes(pendingSig.Bytes),
}
lookups = append(lookups, lookup)
wg.Add(1)
go func(lookup *TxSignaturesLookup) {
defer utils.HandleSubroutinePanic("txsig.lookup")
err := tss.lookupSignature(lookup)
if err != nil {
logger_tss.Warnf("tx signatures lookup failed: %v", err)
}
wg.Done()
}(lookup)
}
wg.Wait()
// store new lookup results to db
pendingSigBytes := []types.TxSignatureBytes{}
unknownSigs := []*dbtypes.TxUnknownFunctionSignature{}
resolvedSigs := []*dbtypes.TxFunctionSignature{}
for _, lookup := range lookups {
if lookup.Status == types.TxSigStatusPending {
continue
}
pendingSigBytes = append(pendingSigBytes, lookup.Bytes)
if lookup.Status == types.TxSigStatusUnknown {
unknownSigs = append(unknownSigs, &dbtypes.TxUnknownFunctionSignature{
Bytes: lookup.Bytes[:],
LastCheck: uint64(time.Now().Unix()),
})
} else if lookup.Status == types.TxSigStatusFound {
resolvedSigs = append(resolvedSigs, &dbtypes.TxFunctionSignature{
Bytes: lookup.Bytes[:],
Signature: lookup.Signature,
Name: lookup.Name,
})
}
}
if len(pendingSigBytes) > 0 {
tx, err := db.WriterDb.Beginx()
if err != nil {
logger_tss.Warnf("error starting db transaction: %v", err)
} else {
defer tx.Rollback()
err := db.DeletePendingFunctionSignatures(pendingSigBytes, tx)
if err != nil {
logger_tss.Warnf("error deleting pending signature: %v", err)
}
if len(unknownSigs) > 0 {
err := db.InsertUnknownFunctionSignatures(unknownSigs, tx)
if err != nil {
logger_tss.Warnf("error saving unknown signature: %v", err)
}
}
for _, fnsig := range resolvedSigs {
err := db.InsertTxFunctionSignature(fnsig, tx)
if err != nil {
logger_tss.Warnf("error saving resolved signature: %v", err)
}
}
if err := tx.Commit(); err != nil {
logger_tss.Warnf("error committing db transaction: %v", err)
}
}
}
}
func (tss *TxSignaturesService) lookupSignature(lookup *TxSignaturesLookup) error {
var resErr error
if !utils.Config.TxSignature.Disable4Bytes {
err := tss.lookup4Bytes(lookup)
if err != nil {
resErr = fmt.Errorf("4bytes lookup failed: %w", err)
} else if lookup.Status == types.TxSigStatusFound {
return nil
}
}
logger_tss.Debugf("lookup fn signature 0x%x (%v): %v", lookup.Bytes[:], lookup.Status, lookup.Signature)
return resErr
}
type txSigLookup_4bytesResponse struct {
Count int `json:"count"`
Results []struct {
Id int `json:"id"`
Signature string `json:"text_signature"`
} `json:"results"`
}
func (tss *TxSignaturesService) lookup4Bytes(lookup *TxSignaturesLookup) error {
// lookup signature via https://www.4byte.directory/
url := fmt.Sprintf("https://www.4byte.directory/api/v1/signatures/?format=json&hex_signature=0x%x", lookup.Bytes)
req, err := nethttp.NewRequest("GET", url, nil)
if err != nil {
return err
}
client := &nethttp.Client{Timeout: time.Second * 10}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != nethttp.StatusOK {
data, _ := io.ReadAll(resp.Body)
return fmt.Errorf("url: %v, code: %v, error-response: %s", url, resp.StatusCode, data)
}
returnValue := txSigLookup_4bytesResponse{}
dec := json.NewDecoder(resp.Body)
err = dec.Decode(&returnValue)
if err != nil {
return fmt.Errorf("error parsing 4bytes json response: %v", err)
}
if returnValue.Count == 0 {
lookup.Status = types.TxSigStatusUnknown
} else {
lookup.Status = types.TxSigStatusFound
lookup.Signature = returnValue.Results[0].Signature
sigparts := strings.Split(lookup.Signature, "(")
lookup.Name = sigparts[0]
}
return nil
}