-
Notifications
You must be signed in to change notification settings - Fork 102
/
indexer.go
355 lines (312 loc) · 10.5 KB
/
indexer.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
package types
import (
"bytes"
"context"
"encoding/hex"
"fmt"
"math"
"github.com/jordanorelli/lexnum"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/libs/pubsub/query"
"github.com/tendermint/tendermint/state/txindex"
"github.com/tendermint/tendermint/types"
dbm "github.com/tendermint/tm-db"
)
var (
_ txindex.TxIndexer = &TransactionIndexer{}
// Since LevelDB comparators order lexicongraphically, the implementation uses ELEN to encode numbers to ensure alphanumerical
// ordering at insertion time. https://www.zanopha.com/docs/elen.pdf
// Since the keys are sorted alphanumerically from the start, we don't have to:
// (a) load all results to memory (b) paginate and sort transactions after
// This indexer inserts in sorted order so it can paginate and return based on the db iterator
elenEncoder = lexnum.NewEncoder('=', '-')
)
const (
// Transaction(tx) Block height index key.
//
// Note: Block height is cast as int when querying using the tx height index due to the lexicographic encoder library,
// this is safe because v0 block height should never exceed 2^63-1 on 64-bit systems or 2^31-1 on 32-bit systems.
TxHeightKey = "tx.height"
TxSignerKey = "tx.signer"
TxRecipientKey = "tx.recipient"
TxHashKey = "tx.hash"
SortAscending = "asc"
SortDescending = "desc"
AuthCodespace = "auth"
sep = "/"
maxPerPage = 10000
AnteHandlerMaxError = 10
)
type TransactionIndexer struct {
store dbm.DB
}
func NewTransactionIndexer(store dbm.DB) *TransactionIndexer {
return &TransactionIndexer{store: store}
}
func (t *TransactionIndexer) AddBatch(b *txindex.Batch) error {
storeBatch := t.store.NewBatch()
defer storeBatch.Close()
for _, result := range b.Ops { // iterate through all the transaction results
if result.Result.Codespace == AuthCodespace && result.Result.Code < AnteHandlerMaxError {
continue // don't index any ante handler level errors
}
hash := result.Tx.Hash()
// index tx by sender
if result.Result.Signer != nil {
storeBatch.Set(keyForSigner(result), hash)
}
// index tx by recipient
if result.Result.Recipient != nil {
storeBatch.Set(keyForRecipient(result), hash)
}
// index tx by height
storeBatch.Set(keyForHeight(result), hash)
// index tx by hash
rawBytes, err := cdc.MarshalBinaryBare(result, 0) // TODO make protobuf compatible
if err != nil {
return err
}
storeBatch.Set(hash, rawBytes)
}
return storeBatch.WriteSync()
}
func (t *TransactionIndexer) Index(result *types.TxResult) error {
storeBatch := t.store.NewBatch()
defer storeBatch.Close()
if result.Result.Codespace == AuthCodespace && result.Result.Code < AnteHandlerMaxError {
return nil // no indexing for ante handler level errors
}
hash := result.Tx.Hash()
// index tx by sender
if result.Result.Signer != nil {
storeBatch.Set(keyForSigner(result), hash)
}
// index tx by recipient
if result.Result.Recipient != nil {
storeBatch.Set(keyForRecipient(result), hash)
}
// index tx by height
storeBatch.Set(keyForHeight(result), hash)
// index tx by hash
rawBytes, err := cdc.MarshalBinaryBare(result, 0) // TODO make protobuf compatible
if err != nil {
return err
}
storeBatch.Set(hash, rawBytes)
return storeBatch.WriteSync()
}
func (t *TransactionIndexer) Get(hash []byte) (*types.TxResult, error) {
if len(hash) == 0 {
return nil, txindex.ErrorEmptyHash
}
rawBytes, _ := t.store.Get(hash)
if rawBytes == nil {
return nil, nil
}
txResult := new(types.TxResult)
err := cdc.UnmarshalBinaryBare(rawBytes, &txResult, 0)
if err != nil {
return nil, fmt.Errorf("error reading TxResult: %v", err)
}
return txResult, nil
}
// NOTE: Only supports op.Equal for hash, height, signer, or recipient, we only support op.Equal for simplicity and
// optimization of our use case
func (t *TransactionIndexer) Search(ctx context.Context, q *query.Query) (res []*types.TxResult, total int, err error) {
conditions, err := q.Conditions()
if err != nil {
return nil, 0, errors.Wrap(err, "error during parsing conditions from query")
}
if q.Pagination.Size > maxPerPage {
q.Pagination.Size = maxPerPage
}
for _, condition := range conditions {
if condition.Op != query.OpEqual {
return nil, 0, fmt.Errorf("transaction indexer only supports op.Equal not %v", condition.Op)
}
}
primaryCondition := conditions[0]
secondaryCondition := query.Condition{}
if len(conditions) > 1 {
secondaryCondition = conditions[1]
if secondaryCondition.CompositeKey != TxHeightKey {
return nil, 0, fmt.Errorf("transaction indexer only supports secondary condition on tx.height not %v", secondaryCondition.CompositeKey)
}
}
switch primaryCondition.CompositeKey {
case TxHeightKey:
return t.heightQuery(primaryCondition, q.Pagination)
case TxSignerKey:
return t.signerQuery(primaryCondition, secondaryCondition, q.Pagination)
case TxRecipientKey:
return t.recipientQuery(primaryCondition, secondaryCondition, q.Pagination)
case TxHashKey:
return t.hashQuery(primaryCondition)
default:
return nil, 0, fmt.Errorf("Condition.CompositeKey: %v not supported on this indexer", primaryCondition.CompositeKey)
}
}
func (t *TransactionIndexer) DeleteFromHeight(ctx context.Context, height int64) error {
startKey := []byte(fmt.Sprintf("%s/%s",
TxHeightKey,
elenEncoder.EncodeInt(int(height)),
))
endKey := []byte(fmt.Sprintf("%s/%s",
TxHeightKey,
elenEncoder.EncodeInt(math.MaxInt64),
))
it, err := t.store.ReverseIterator(startKey, endKey)
if err != nil {
return errors.Wrap(err, "error creating the reverse iterator for deleteFromHeight")
}
defer it.Close()
b := t.store.NewBatch()
defer b.Close()
for ; it.Valid(); it.Next() {
b.Delete(it.Value())
}
return b.WriteSync()
}
func (t *TransactionIndexer) hashQuery(condition query.Condition) (res []*types.TxResult, total int, err error) {
hash, err := hex.DecodeString(condition.Operand.(string))
if err != nil {
return nil, 0, errors.Wrap(err, "error during searching for a hash in the query")
}
result, err := t.Get(hash)
if err == nil {
total = 1
}
return []*types.TxResult{result}, total, err
}
func (t *TransactionIndexer) heightQuery(condition query.Condition, pagination *query.Page) (res []*types.TxResult, total int, err error) {
height, ok := condition.Operand.(int64)
if !ok {
return nil, 0, errors.New("error during searching for a height in the query, c.Operand not type int64")
}
return t.getByPrefix(prefixKeyForHeight(height), pagination)
}
func (t *TransactionIndexer) signerQuery(primaryCondition query.Condition, secondaryCondition query.Condition, pagination *query.Page) (res []*types.TxResult, total int, err error) {
signer, err := hex.DecodeString(primaryCondition.Operand.(string))
if err != nil {
return nil, 0, errors.Wrap(err, "error during searching for a address in the query")
}
if secondaryCondition.CompositeKey == TxHeightKey {
height, ok := secondaryCondition.Operand.(int64)
if !ok {
return nil, 0, errors.New("error during searching for a height in the query, c.Operand not type int64")
}
return t.getByPrefix(prefixKeyForSignerAndHeight(signer, height), pagination)
}
return t.getByPrefix(prefixKeyForSigner(signer), pagination)
}
func (t *TransactionIndexer) recipientQuery(primaryCondition query.Condition, secondaryCondition query.Condition, pagination *query.Page) (res []*types.TxResult, total int, err error) {
recipient, err := hex.DecodeString(primaryCondition.Operand.(string))
if err != nil {
return nil, 0, errors.Wrap(err, "error during searching for a address in the query")
}
if secondaryCondition.CompositeKey == TxHeightKey {
height, ok := secondaryCondition.Operand.(int64)
if !ok {
return nil, 0, errors.New("error during searching for a height in the query, c.Operand not type int64")
}
return t.getByPrefix(prefixKeyForRecipientAndHeight(recipient, height), pagination)
}
return t.getByPrefix(prefixKeyForRecipient(recipient), pagination)
}
func (t *TransactionIndexer) getByPrefix(prefix []byte, pagination *query.Page) (res []*types.TxResult, total int, err error) {
it, err := PrefixIterator(t.store, prefix, pagination.Sort)
if err != nil {
return nil, 0, errors.Wrap(err, "error creating prefix iterator")
}
defer it.Close()
for i, skipCount := 0, 0; it.Valid(); it.Next() {
if skipCount < pagination.Skip {
skipCount++
total++
continue
}
val, err := t.Get(it.Value())
if err != nil {
return nil, 0, errors.Wrap(err, "error during query iteration get()")
}
if i < pagination.Size {
res = append(res, val)
}
total++
i++
}
return
}
func keyForHeight(result *types.TxResult) []byte {
return []byte(fmt.Sprintf("%s/%s/%s",
TxHeightKey,
elenEncoder.EncodeInt(int(result.Height)),
elenEncoder.EncodeInt(int(result.Index)),
))
}
func prefixKeyForHeight(height int64) []byte {
return []byte(fmt.Sprintf("%s/%s/",
TxHeightKey,
elenEncoder.EncodeInt(int(height)),
))
}
func keyForSigner(result *types.TxResult) []byte {
return []byte(fmt.Sprintf("%s/%s/%s/%s",
TxSignerKey,
Address(result.Result.Signer),
elenEncoder.EncodeInt(int(result.Height)),
elenEncoder.EncodeInt(int(result.Index)),
))
}
func prefixKeyForSigner(signer Address) []byte {
return []byte(fmt.Sprintf("%s/%s/%s",
TxSignerKey,
signer,
elenEncoder.EncodeInt(0),
))
}
func prefixKeyForSignerAndHeight(signer Address, height int64) []byte {
return []byte(fmt.Sprintf("%s/%s/%s",
TxSignerKey,
signer,
elenEncoder.EncodeInt(int(height)),
))
}
func keyForRecipient(result *types.TxResult) []byte {
return []byte(fmt.Sprintf("%s/%s/%s/%s",
TxRecipientKey,
Address(result.Result.Recipient),
elenEncoder.EncodeInt(int(result.Height)),
elenEncoder.EncodeInt(int(result.Index)),
))
}
func prefixKeyForRecipient(recipient Address) []byte {
return []byte(fmt.Sprintf("%s/%s/%s",
TxRecipientKey,
recipient,
elenEncoder.EncodeInt(0),
))
}
func prefixKeyForRecipientAndHeight(recipient Address, height int64) []byte {
return []byte(fmt.Sprintf("%s/%s/%s",
TxRecipientKey,
recipient,
elenEncoder.EncodeInt(int(height)),
))
}
// contract: caller must close iterator
func PrefixIterator(db dbm.DB, prefix []byte, order string) (dbm.Iterator, error) {
switch order {
case SortAscending:
return db.ReverseIterator(prefix, endKey(prefix))
case SortDescending:
return db.Iterator(prefix, endKey(prefix))
default:
return nil, fmt.Errorf("sorting order: %v not supported", order)
}
}
func endKey(prefix []byte) []byte {
bz := bytes.Split(prefix, []byte(sep))
bz = append(bz[:len(bz)-1], []byte(elenEncoder.EncodeInt(math.MaxInt64)))
return bytes.Join(bz[:], []byte(sep))
}