You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

590 lines
15 KiB

abci: Refactor tagging events using list of lists (#3643) ## PR This PR introduces a fundamental breaking change to the structure of ABCI response and tx tags and the way they're processed. Namely, the SDK can support more complex and aggregated events for distribution and slashing. In addition, block responses can include duplicate keys in events. Implement new Event type. An event has a type and a list of KV pairs (ie. list-of-lists). Typical events may look like: "rewards": [{"amount": "5000uatom", "validator": "...", "recipient": "..."}] "sender": [{"address": "...", "balance": "100uatom"}] The events are indexed by {even.type}.{even.attribute[i].key}/.... In this case a client would subscribe or query for rewards.recipient='...' ABCI response types and related types now include Events []Event instead of Tags []cmn.KVPair. PubSub logic now publishes/matches against map[string][]string instead of map[string]string to support duplicate keys in response events (from #1385). A match is successful if the value is found in the slice of strings. closes: #1859 closes: #2905 ## Commits: * Implement Event ABCI type and updates responses to use events * Update messages_test.go * Update kvstore.go * Update event_bus.go * Update subscription.go * Update pubsub.go * Update kvstore.go * Update query logic to handle slice of strings in events * Update Empty#Matches and unit tests * Update pubsub logic * Update EventBus#Publish * Update kv tx indexer * Update godocs * Update ResultEvent to use slice of strings; update RPC * Update more tests * Update abci.md * Check for key in validateAndStringifyEvents * Fix KV indexer to skip empty keys * Fix linting errors * Update CHANGELOG_PENDING.md * Update docs/spec/abci/abci.md Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update abci/types/types.proto Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update docs/spec/abci/abci.md Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update libs/pubsub/query/query.go Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update match function to match if ANY value matches * Implement TestSubscribeDuplicateKeys * Update TestMatches to include multi-key test cases * Update events.go * Update Query interface godoc * Update match godoc * Add godoc for matchValue * DRY-up tx indexing * Return error from PublishWithEvents in EventBus#Publish * Update PublishEventNewBlockHeader to return an error * Fix build * Update events doc in ABCI * Update ABCI events godoc * Implement TestEventBusPublishEventTxDuplicateKeys * Update TestSubscribeDuplicateKeys to be table-driven * Remove mod file * Remove markdown from events godoc * Implement TestTxSearchDeprecatedIndexing test
6 years ago
abci: Refactor tagging events using list of lists (#3643) ## PR This PR introduces a fundamental breaking change to the structure of ABCI response and tx tags and the way they're processed. Namely, the SDK can support more complex and aggregated events for distribution and slashing. In addition, block responses can include duplicate keys in events. Implement new Event type. An event has a type and a list of KV pairs (ie. list-of-lists). Typical events may look like: "rewards": [{"amount": "5000uatom", "validator": "...", "recipient": "..."}] "sender": [{"address": "...", "balance": "100uatom"}] The events are indexed by {even.type}.{even.attribute[i].key}/.... In this case a client would subscribe or query for rewards.recipient='...' ABCI response types and related types now include Events []Event instead of Tags []cmn.KVPair. PubSub logic now publishes/matches against map[string][]string instead of map[string]string to support duplicate keys in response events (from #1385). A match is successful if the value is found in the slice of strings. closes: #1859 closes: #2905 ## Commits: * Implement Event ABCI type and updates responses to use events * Update messages_test.go * Update kvstore.go * Update event_bus.go * Update subscription.go * Update pubsub.go * Update kvstore.go * Update query logic to handle slice of strings in events * Update Empty#Matches and unit tests * Update pubsub logic * Update EventBus#Publish * Update kv tx indexer * Update godocs * Update ResultEvent to use slice of strings; update RPC * Update more tests * Update abci.md * Check for key in validateAndStringifyEvents * Fix KV indexer to skip empty keys * Fix linting errors * Update CHANGELOG_PENDING.md * Update docs/spec/abci/abci.md Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update abci/types/types.proto Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update docs/spec/abci/abci.md Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update libs/pubsub/query/query.go Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update match function to match if ANY value matches * Implement TestSubscribeDuplicateKeys * Update TestMatches to include multi-key test cases * Update events.go * Update Query interface godoc * Update match godoc * Add godoc for matchValue * DRY-up tx indexing * Return error from PublishWithEvents in EventBus#Publish * Update PublishEventNewBlockHeader to return an error * Fix build * Update events doc in ABCI * Update ABCI events godoc * Implement TestEventBusPublishEventTxDuplicateKeys * Update TestSubscribeDuplicateKeys to be table-driven * Remove mod file * Remove markdown from events godoc * Implement TestTxSearchDeprecatedIndexing test
6 years ago
7 years ago
abci: Refactor tagging events using list of lists (#3643) ## PR This PR introduces a fundamental breaking change to the structure of ABCI response and tx tags and the way they're processed. Namely, the SDK can support more complex and aggregated events for distribution and slashing. In addition, block responses can include duplicate keys in events. Implement new Event type. An event has a type and a list of KV pairs (ie. list-of-lists). Typical events may look like: "rewards": [{"amount": "5000uatom", "validator": "...", "recipient": "..."}] "sender": [{"address": "...", "balance": "100uatom"}] The events are indexed by {even.type}.{even.attribute[i].key}/.... In this case a client would subscribe or query for rewards.recipient='...' ABCI response types and related types now include Events []Event instead of Tags []cmn.KVPair. PubSub logic now publishes/matches against map[string][]string instead of map[string]string to support duplicate keys in response events (from #1385). A match is successful if the value is found in the slice of strings. closes: #1859 closes: #2905 ## Commits: * Implement Event ABCI type and updates responses to use events * Update messages_test.go * Update kvstore.go * Update event_bus.go * Update subscription.go * Update pubsub.go * Update kvstore.go * Update query logic to handle slice of strings in events * Update Empty#Matches and unit tests * Update pubsub logic * Update EventBus#Publish * Update kv tx indexer * Update godocs * Update ResultEvent to use slice of strings; update RPC * Update more tests * Update abci.md * Check for key in validateAndStringifyEvents * Fix KV indexer to skip empty keys * Fix linting errors * Update CHANGELOG_PENDING.md * Update docs/spec/abci/abci.md Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update abci/types/types.proto Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update docs/spec/abci/abci.md Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update libs/pubsub/query/query.go Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update match function to match if ANY value matches * Implement TestSubscribeDuplicateKeys * Update TestMatches to include multi-key test cases * Update events.go * Update Query interface godoc * Update match godoc * Add godoc for matchValue * DRY-up tx indexing * Return error from PublishWithEvents in EventBus#Publish * Update PublishEventNewBlockHeader to return an error * Fix build * Update events doc in ABCI * Update ABCI events godoc * Implement TestEventBusPublishEventTxDuplicateKeys * Update TestSubscribeDuplicateKeys to be table-driven * Remove mod file * Remove markdown from events godoc * Implement TestTxSearchDeprecatedIndexing test
6 years ago
abci: Refactor tagging events using list of lists (#3643) ## PR This PR introduces a fundamental breaking change to the structure of ABCI response and tx tags and the way they're processed. Namely, the SDK can support more complex and aggregated events for distribution and slashing. In addition, block responses can include duplicate keys in events. Implement new Event type. An event has a type and a list of KV pairs (ie. list-of-lists). Typical events may look like: "rewards": [{"amount": "5000uatom", "validator": "...", "recipient": "..."}] "sender": [{"address": "...", "balance": "100uatom"}] The events are indexed by {even.type}.{even.attribute[i].key}/.... In this case a client would subscribe or query for rewards.recipient='...' ABCI response types and related types now include Events []Event instead of Tags []cmn.KVPair. PubSub logic now publishes/matches against map[string][]string instead of map[string]string to support duplicate keys in response events (from #1385). A match is successful if the value is found in the slice of strings. closes: #1859 closes: #2905 ## Commits: * Implement Event ABCI type and updates responses to use events * Update messages_test.go * Update kvstore.go * Update event_bus.go * Update subscription.go * Update pubsub.go * Update kvstore.go * Update query logic to handle slice of strings in events * Update Empty#Matches and unit tests * Update pubsub logic * Update EventBus#Publish * Update kv tx indexer * Update godocs * Update ResultEvent to use slice of strings; update RPC * Update more tests * Update abci.md * Check for key in validateAndStringifyEvents * Fix KV indexer to skip empty keys * Fix linting errors * Update CHANGELOG_PENDING.md * Update docs/spec/abci/abci.md Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update abci/types/types.proto Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update docs/spec/abci/abci.md Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update libs/pubsub/query/query.go Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update match function to match if ANY value matches * Implement TestSubscribeDuplicateKeys * Update TestMatches to include multi-key test cases * Update events.go * Update Query interface godoc * Update match godoc * Add godoc for matchValue * DRY-up tx indexing * Return error from PublishWithEvents in EventBus#Publish * Update PublishEventNewBlockHeader to return an error * Fix build * Update events doc in ABCI * Update ABCI events godoc * Implement TestEventBusPublishEventTxDuplicateKeys * Update TestSubscribeDuplicateKeys to be table-driven * Remove mod file * Remove markdown from events godoc * Implement TestTxSearchDeprecatedIndexing test
6 years ago
abci: Refactor tagging events using list of lists (#3643) ## PR This PR introduces a fundamental breaking change to the structure of ABCI response and tx tags and the way they're processed. Namely, the SDK can support more complex and aggregated events for distribution and slashing. In addition, block responses can include duplicate keys in events. Implement new Event type. An event has a type and a list of KV pairs (ie. list-of-lists). Typical events may look like: "rewards": [{"amount": "5000uatom", "validator": "...", "recipient": "..."}] "sender": [{"address": "...", "balance": "100uatom"}] The events are indexed by {even.type}.{even.attribute[i].key}/.... In this case a client would subscribe or query for rewards.recipient='...' ABCI response types and related types now include Events []Event instead of Tags []cmn.KVPair. PubSub logic now publishes/matches against map[string][]string instead of map[string]string to support duplicate keys in response events (from #1385). A match is successful if the value is found in the slice of strings. closes: #1859 closes: #2905 ## Commits: * Implement Event ABCI type and updates responses to use events * Update messages_test.go * Update kvstore.go * Update event_bus.go * Update subscription.go * Update pubsub.go * Update kvstore.go * Update query logic to handle slice of strings in events * Update Empty#Matches and unit tests * Update pubsub logic * Update EventBus#Publish * Update kv tx indexer * Update godocs * Update ResultEvent to use slice of strings; update RPC * Update more tests * Update abci.md * Check for key in validateAndStringifyEvents * Fix KV indexer to skip empty keys * Fix linting errors * Update CHANGELOG_PENDING.md * Update docs/spec/abci/abci.md Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update abci/types/types.proto Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update docs/spec/abci/abci.md Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update libs/pubsub/query/query.go Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update match function to match if ANY value matches * Implement TestSubscribeDuplicateKeys * Update TestMatches to include multi-key test cases * Update events.go * Update Query interface godoc * Update match godoc * Add godoc for matchValue * DRY-up tx indexing * Return error from PublishWithEvents in EventBus#Publish * Update PublishEventNewBlockHeader to return an error * Fix build * Update events doc in ABCI * Update ABCI events godoc * Implement TestEventBusPublishEventTxDuplicateKeys * Update TestSubscribeDuplicateKeys to be table-driven * Remove mod file * Remove markdown from events godoc * Implement TestTxSearchDeprecatedIndexing test
6 years ago
libs/pubsub: relax tx querying (#4070) Some linting/cleanup missed from the initial events refactor Don't panic; instead, return false, error when matching breaks unexpectedly Strip non-numeric chars from values when attempting to match against query values Have the server log during send upon error * cleanup/lint Query#Conditions and do not panic * cleanup/lint Query#Matches and do not panic * cleanup/lint matchValue and do not panic * rever to panic in Query#Conditions * linting * strip alpha chars when attempting to match * add pending log entries * Update libs/pubsub/query/query.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * build: update variable names * update matchValue to return an error * update Query#Matches to return an error * update TestMatches * log error in send * Fix tests * Fix TestEmptyQueryMatchesAnything * fix linting * Update libs/pubsub/query/query.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update libs/pubsub/query/query.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update libs/pubsub/query/query.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update libs/pubsub/query/query.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update libs/pubsub/query/query.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update libs/pubsub/pubsub.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * add missing errors pkg import * update Query#Conditions to return an error * update query pkg unit tests * update TxIndex#Search * update pending changelog
5 years ago
libs/pubsub: relax tx querying (#4070) Some linting/cleanup missed from the initial events refactor Don't panic; instead, return false, error when matching breaks unexpectedly Strip non-numeric chars from values when attempting to match against query values Have the server log during send upon error * cleanup/lint Query#Conditions and do not panic * cleanup/lint Query#Matches and do not panic * cleanup/lint matchValue and do not panic * rever to panic in Query#Conditions * linting * strip alpha chars when attempting to match * add pending log entries * Update libs/pubsub/query/query.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * build: update variable names * update matchValue to return an error * update Query#Matches to return an error * update TestMatches * log error in send * Fix tests * Fix TestEmptyQueryMatchesAnything * fix linting * Update libs/pubsub/query/query.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update libs/pubsub/query/query.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update libs/pubsub/query/query.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update libs/pubsub/query/query.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update libs/pubsub/query/query.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update libs/pubsub/pubsub.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * add missing errors pkg import * update Query#Conditions to return an error * update query pkg unit tests * update TxIndex#Search * update pending changelog
5 years ago
abci: Refactor tagging events using list of lists (#3643) ## PR This PR introduces a fundamental breaking change to the structure of ABCI response and tx tags and the way they're processed. Namely, the SDK can support more complex and aggregated events for distribution and slashing. In addition, block responses can include duplicate keys in events. Implement new Event type. An event has a type and a list of KV pairs (ie. list-of-lists). Typical events may look like: "rewards": [{"amount": "5000uatom", "validator": "...", "recipient": "..."}] "sender": [{"address": "...", "balance": "100uatom"}] The events are indexed by {even.type}.{even.attribute[i].key}/.... In this case a client would subscribe or query for rewards.recipient='...' ABCI response types and related types now include Events []Event instead of Tags []cmn.KVPair. PubSub logic now publishes/matches against map[string][]string instead of map[string]string to support duplicate keys in response events (from #1385). A match is successful if the value is found in the slice of strings. closes: #1859 closes: #2905 ## Commits: * Implement Event ABCI type and updates responses to use events * Update messages_test.go * Update kvstore.go * Update event_bus.go * Update subscription.go * Update pubsub.go * Update kvstore.go * Update query logic to handle slice of strings in events * Update Empty#Matches and unit tests * Update pubsub logic * Update EventBus#Publish * Update kv tx indexer * Update godocs * Update ResultEvent to use slice of strings; update RPC * Update more tests * Update abci.md * Check for key in validateAndStringifyEvents * Fix KV indexer to skip empty keys * Fix linting errors * Update CHANGELOG_PENDING.md * Update docs/spec/abci/abci.md Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update abci/types/types.proto Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update docs/spec/abci/abci.md Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update libs/pubsub/query/query.go Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update match function to match if ANY value matches * Implement TestSubscribeDuplicateKeys * Update TestMatches to include multi-key test cases * Update events.go * Update Query interface godoc * Update match godoc * Add godoc for matchValue * DRY-up tx indexing * Return error from PublishWithEvents in EventBus#Publish * Update PublishEventNewBlockHeader to return an error * Fix build * Update events doc in ABCI * Update ABCI events godoc * Implement TestEventBusPublishEventTxDuplicateKeys * Update TestSubscribeDuplicateKeys to be table-driven * Remove mod file * Remove markdown from events godoc * Implement TestTxSearchDeprecatedIndexing test
6 years ago
  1. package kv
  2. import (
  3. "context"
  4. "encoding/hex"
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. "github.com/gogo/protobuf/proto"
  9. "github.com/google/orderedcode"
  10. dbm "github.com/tendermint/tm-db"
  11. abci "github.com/tendermint/tendermint/abci/types"
  12. indexer "github.com/tendermint/tendermint/internal/state/indexer"
  13. "github.com/tendermint/tendermint/libs/pubsub/query"
  14. "github.com/tendermint/tendermint/types"
  15. )
  16. var _ indexer.TxIndexer = (*TxIndex)(nil)
  17. // TxIndex is the simplest possible indexer
  18. // It is backed by two kv stores:
  19. // 1. txhash - result (primary key)
  20. // 2. event - txhash (secondary key)
  21. type TxIndex struct {
  22. store dbm.DB
  23. }
  24. // NewTxIndex creates new KV indexer.
  25. func NewTxIndex(store dbm.DB) *TxIndex {
  26. return &TxIndex{
  27. store: store,
  28. }
  29. }
  30. // Get gets transaction from the TxIndex storage and returns it or nil if the
  31. // transaction is not found.
  32. func (txi *TxIndex) Get(hash []byte) (*abci.TxResult, error) {
  33. if len(hash) == 0 {
  34. return nil, indexer.ErrorEmptyHash
  35. }
  36. rawBytes, err := txi.store.Get(primaryKey(hash))
  37. if err != nil {
  38. panic(err)
  39. }
  40. if rawBytes == nil {
  41. return nil, nil
  42. }
  43. txResult := new(abci.TxResult)
  44. err = proto.Unmarshal(rawBytes, txResult)
  45. if err != nil {
  46. return nil, fmt.Errorf("error reading TxResult: %v", err)
  47. }
  48. return txResult, nil
  49. }
  50. // Index indexes transactions using the given list of events. Each key
  51. // that indexed from the tx's events is a composite of the event type and the
  52. // respective attribute's key delimited by a "." (eg. "account.number").
  53. // Any event with an empty type is not indexed.
  54. func (txi *TxIndex) Index(results []*abci.TxResult) error {
  55. b := txi.store.NewBatch()
  56. defer b.Close()
  57. for _, result := range results {
  58. hash := types.Tx(result.Tx).Hash()
  59. // index tx by events
  60. err := txi.indexEvents(result, hash, b)
  61. if err != nil {
  62. return err
  63. }
  64. // index by height (always)
  65. err = b.Set(KeyFromHeight(result), hash)
  66. if err != nil {
  67. return err
  68. }
  69. rawBytes, err := proto.Marshal(result)
  70. if err != nil {
  71. return err
  72. }
  73. // index by hash (always)
  74. err = b.Set(primaryKey(hash), rawBytes)
  75. if err != nil {
  76. return err
  77. }
  78. }
  79. return b.WriteSync()
  80. }
  81. func (txi *TxIndex) indexEvents(result *abci.TxResult, hash []byte, store dbm.Batch) error {
  82. for _, event := range result.Result.Events {
  83. // only index events with a non-empty type
  84. if len(event.Type) == 0 {
  85. continue
  86. }
  87. for _, attr := range event.Attributes {
  88. if len(attr.Key) == 0 {
  89. continue
  90. }
  91. // index if `index: true` is set
  92. compositeTag := fmt.Sprintf("%s.%s", event.Type, attr.Key)
  93. // ensure event does not conflict with a reserved prefix key
  94. if compositeTag == types.TxHashKey || compositeTag == types.TxHeightKey {
  95. return fmt.Errorf("event type and attribute key \"%s\" is reserved; please use a different key", compositeTag)
  96. }
  97. if attr.GetIndex() {
  98. err := store.Set(keyFromEvent(compositeTag, attr.Value, result), hash)
  99. if err != nil {
  100. return err
  101. }
  102. }
  103. }
  104. }
  105. return nil
  106. }
  107. // Search performs a search using the given query.
  108. //
  109. // It breaks the query into conditions (like "tx.height > 5"). For each
  110. // condition, it queries the DB index. One special use cases here: (1) if
  111. // "tx.hash" is found, it returns tx result for it (2) for range queries it is
  112. // better for the client to provide both lower and upper bounds, so we are not
  113. // performing a full scan. Results from querying indexes are then intersected
  114. // and returned to the caller, in no particular order.
  115. //
  116. // Search will exit early and return any result fetched so far,
  117. // when a message is received on the context chan.
  118. func (txi *TxIndex) Search(ctx context.Context, q *query.Query) ([]*abci.TxResult, error) {
  119. select {
  120. case <-ctx.Done():
  121. return make([]*abci.TxResult, 0), nil
  122. default:
  123. }
  124. var hashesInitialized bool
  125. filteredHashes := make(map[string][]byte)
  126. // get a list of conditions (like "tx.height > 5")
  127. conditions, err := q.Conditions()
  128. if err != nil {
  129. return nil, fmt.Errorf("error during parsing conditions from query: %w", err)
  130. }
  131. // if there is a hash condition, return the result immediately
  132. hash, ok, err := lookForHash(conditions)
  133. if err != nil {
  134. return nil, fmt.Errorf("error during searching for a hash in the query: %w", err)
  135. } else if ok {
  136. res, err := txi.Get(hash)
  137. switch {
  138. case err != nil:
  139. return []*abci.TxResult{}, fmt.Errorf("error while retrieving the result: %w", err)
  140. case res == nil:
  141. return []*abci.TxResult{}, nil
  142. default:
  143. return []*abci.TxResult{res}, nil
  144. }
  145. }
  146. // conditions to skip because they're handled before "everything else"
  147. skipIndexes := make([]int, 0)
  148. // extract ranges
  149. // if both upper and lower bounds exist, it's better to get them in order not
  150. // no iterate over kvs that are not within range.
  151. ranges, rangeIndexes := indexer.LookForRanges(conditions)
  152. if len(ranges) > 0 {
  153. skipIndexes = append(skipIndexes, rangeIndexes...)
  154. for _, qr := range ranges {
  155. if !hashesInitialized {
  156. filteredHashes = txi.matchRange(ctx, qr, prefixFromCompositeKey(qr.Key), filteredHashes, true)
  157. hashesInitialized = true
  158. // Ignore any remaining conditions if the first condition resulted
  159. // in no matches (assuming implicit AND operand).
  160. if len(filteredHashes) == 0 {
  161. break
  162. }
  163. } else {
  164. filteredHashes = txi.matchRange(ctx, qr, prefixFromCompositeKey(qr.Key), filteredHashes, false)
  165. }
  166. }
  167. }
  168. // if there is a height condition ("tx.height=3"), extract it
  169. height := lookForHeight(conditions)
  170. // for all other conditions
  171. for i, c := range conditions {
  172. if intInSlice(i, skipIndexes) {
  173. continue
  174. }
  175. if !hashesInitialized {
  176. filteredHashes = txi.match(ctx, c, prefixForCondition(c, height), filteredHashes, true)
  177. hashesInitialized = true
  178. // Ignore any remaining conditions if the first condition resulted
  179. // in no matches (assuming implicit AND operand).
  180. if len(filteredHashes) == 0 {
  181. break
  182. }
  183. } else {
  184. filteredHashes = txi.match(ctx, c, prefixForCondition(c, height), filteredHashes, false)
  185. }
  186. }
  187. results := make([]*abci.TxResult, 0, len(filteredHashes))
  188. hashes:
  189. for _, h := range filteredHashes {
  190. res, err := txi.Get(h)
  191. if err != nil {
  192. return nil, fmt.Errorf("failed to get Tx{%X}: %w", h, err)
  193. }
  194. results = append(results, res)
  195. // Potentially exit early.
  196. select {
  197. case <-ctx.Done():
  198. break hashes
  199. default:
  200. }
  201. }
  202. return results, nil
  203. }
  204. func lookForHash(conditions []query.Condition) (hash []byte, ok bool, err error) {
  205. for _, c := range conditions {
  206. if c.CompositeKey == types.TxHashKey {
  207. decoded, err := hex.DecodeString(c.Operand.(string))
  208. return decoded, true, err
  209. }
  210. }
  211. return
  212. }
  213. // lookForHeight returns a height if there is an "height=X" condition.
  214. func lookForHeight(conditions []query.Condition) (height int64) {
  215. for _, c := range conditions {
  216. if c.CompositeKey == types.TxHeightKey && c.Op == query.OpEqual {
  217. return c.Operand.(int64)
  218. }
  219. }
  220. return 0
  221. }
  222. // match returns all matching txs by hash that meet a given condition and start
  223. // key. An already filtered result (filteredHashes) is provided such that any
  224. // non-intersecting matches are removed.
  225. //
  226. // NOTE: filteredHashes may be empty if no previous condition has matched.
  227. func (txi *TxIndex) match(
  228. ctx context.Context,
  229. c query.Condition,
  230. startKeyBz []byte,
  231. filteredHashes map[string][]byte,
  232. firstRun bool,
  233. ) map[string][]byte {
  234. // A previous match was attempted but resulted in no matches, so we return
  235. // no matches (assuming AND operand).
  236. if !firstRun && len(filteredHashes) == 0 {
  237. return filteredHashes
  238. }
  239. tmpHashes := make(map[string][]byte)
  240. switch {
  241. case c.Op == query.OpEqual:
  242. it, err := dbm.IteratePrefix(txi.store, startKeyBz)
  243. if err != nil {
  244. panic(err)
  245. }
  246. defer it.Close()
  247. iterEqual:
  248. for ; it.Valid(); it.Next() {
  249. tmpHashes[string(it.Value())] = it.Value()
  250. // Potentially exit early.
  251. select {
  252. case <-ctx.Done():
  253. break iterEqual
  254. default:
  255. }
  256. }
  257. if err := it.Error(); err != nil {
  258. panic(err)
  259. }
  260. case c.Op == query.OpExists:
  261. // XXX: can't use startKeyBz here because c.Operand is nil
  262. // (e.g. "account.owner/<nil>/" won't match w/ a single row)
  263. it, err := dbm.IteratePrefix(txi.store, prefixFromCompositeKey(c.CompositeKey))
  264. if err != nil {
  265. panic(err)
  266. }
  267. defer it.Close()
  268. iterExists:
  269. for ; it.Valid(); it.Next() {
  270. tmpHashes[string(it.Value())] = it.Value()
  271. // Potentially exit early.
  272. select {
  273. case <-ctx.Done():
  274. break iterExists
  275. default:
  276. }
  277. }
  278. if err := it.Error(); err != nil {
  279. panic(err)
  280. }
  281. case c.Op == query.OpContains:
  282. // XXX: startKey does not apply here.
  283. // For example, if startKey = "account.owner/an/" and search query = "account.owner CONTAINS an"
  284. // we can't iterate with prefix "account.owner/an/" because we might miss keys like "account.owner/Ulan/"
  285. it, err := dbm.IteratePrefix(txi.store, prefixFromCompositeKey(c.CompositeKey))
  286. if err != nil {
  287. panic(err)
  288. }
  289. defer it.Close()
  290. iterContains:
  291. for ; it.Valid(); it.Next() {
  292. value, err := parseValueFromKey(it.Key())
  293. if err != nil {
  294. continue
  295. }
  296. if strings.Contains(value, c.Operand.(string)) {
  297. tmpHashes[string(it.Value())] = it.Value()
  298. }
  299. // Potentially exit early.
  300. select {
  301. case <-ctx.Done():
  302. break iterContains
  303. default:
  304. }
  305. }
  306. if err := it.Error(); err != nil {
  307. panic(err)
  308. }
  309. default:
  310. panic("other operators should be handled already")
  311. }
  312. if len(tmpHashes) == 0 || firstRun {
  313. // Either:
  314. //
  315. // 1. Regardless if a previous match was attempted, which may have had
  316. // results, but no match was found for the current condition, then we
  317. // return no matches (assuming AND operand).
  318. //
  319. // 2. A previous match was not attempted, so we return all results.
  320. return tmpHashes
  321. }
  322. // Remove/reduce matches in filteredHashes that were not found in this
  323. // match (tmpHashes).
  324. for k := range filteredHashes {
  325. if tmpHashes[k] == nil {
  326. delete(filteredHashes, k)
  327. // Potentially exit early.
  328. select {
  329. case <-ctx.Done():
  330. break
  331. default:
  332. }
  333. }
  334. }
  335. return filteredHashes
  336. }
  337. // matchRange returns all matching txs by hash that meet a given queryRange and
  338. // start key. An already filtered result (filteredHashes) is provided such that
  339. // any non-intersecting matches are removed.
  340. //
  341. // NOTE: filteredHashes may be empty if no previous condition has matched.
  342. func (txi *TxIndex) matchRange(
  343. ctx context.Context,
  344. qr indexer.QueryRange,
  345. startKey []byte,
  346. filteredHashes map[string][]byte,
  347. firstRun bool,
  348. ) map[string][]byte {
  349. // A previous match was attempted but resulted in no matches, so we return
  350. // no matches (assuming AND operand).
  351. if !firstRun && len(filteredHashes) == 0 {
  352. return filteredHashes
  353. }
  354. tmpHashes := make(map[string][]byte)
  355. lowerBound := qr.LowerBoundValue()
  356. upperBound := qr.UpperBoundValue()
  357. it, err := dbm.IteratePrefix(txi.store, startKey)
  358. if err != nil {
  359. panic(err)
  360. }
  361. defer it.Close()
  362. iter:
  363. for ; it.Valid(); it.Next() {
  364. value, err := parseValueFromKey(it.Key())
  365. if err != nil {
  366. continue
  367. }
  368. if _, ok := qr.AnyBound().(int64); ok {
  369. v, err := strconv.ParseInt(value, 10, 64)
  370. if err != nil {
  371. continue iter
  372. }
  373. include := true
  374. if lowerBound != nil && v < lowerBound.(int64) {
  375. include = false
  376. }
  377. if upperBound != nil && v > upperBound.(int64) {
  378. include = false
  379. }
  380. if include {
  381. tmpHashes[string(it.Value())] = it.Value()
  382. }
  383. // XXX: passing time in a ABCI Events is not yet implemented
  384. // case time.Time:
  385. // v := strconv.ParseInt(extractValueFromKey(it.Key()), 10, 64)
  386. // if v == r.upperBound {
  387. // break
  388. // }
  389. }
  390. // Potentially exit early.
  391. select {
  392. case <-ctx.Done():
  393. break iter
  394. default:
  395. }
  396. }
  397. if err := it.Error(); err != nil {
  398. panic(err)
  399. }
  400. if len(tmpHashes) == 0 || firstRun {
  401. // Either:
  402. //
  403. // 1. Regardless if a previous match was attempted, which may have had
  404. // results, but no match was found for the current condition, then we
  405. // return no matches (assuming AND operand).
  406. //
  407. // 2. A previous match was not attempted, so we return all results.
  408. return tmpHashes
  409. }
  410. // Remove/reduce matches in filteredHashes that were not found in this
  411. // match (tmpHashes).
  412. for k := range filteredHashes {
  413. if tmpHashes[k] == nil {
  414. delete(filteredHashes, k)
  415. // Potentially exit early.
  416. select {
  417. case <-ctx.Done():
  418. break
  419. default:
  420. }
  421. }
  422. }
  423. return filteredHashes
  424. }
  425. // ########################## Keys #############################
  426. //
  427. // The indexer has two types of kv stores:
  428. // 1. txhash - result (primary key)
  429. // 2. event - txhash (secondary key)
  430. //
  431. // The event key can be decomposed into 4 parts.
  432. // 1. A composite key which can be any string.
  433. // Usually something like "tx.height" or "account.owner"
  434. // 2. A value. That corresponds to the key. In the above
  435. // example the value could be "5" or "Ivan"
  436. // 3. The height of the Tx that aligns with the key and value.
  437. // 4. The index of the Tx that aligns with the key and value
  438. // the hash/primary key
  439. func primaryKey(hash []byte) []byte {
  440. key, err := orderedcode.Append(
  441. nil,
  442. types.TxHashKey,
  443. string(hash),
  444. )
  445. if err != nil {
  446. panic(err)
  447. }
  448. return key
  449. }
  450. // The event/secondary key
  451. func secondaryKey(compositeKey, value string, height int64, index uint32) []byte {
  452. key, err := orderedcode.Append(
  453. nil,
  454. compositeKey,
  455. value,
  456. height,
  457. int64(index),
  458. )
  459. if err != nil {
  460. panic(err)
  461. }
  462. return key
  463. }
  464. // parseValueFromKey parses an event key and extracts out the value, returning an error if one arises.
  465. // This will also involve ensuring that the key has the correct format.
  466. // CONTRACT: function doesn't check that the prefix is correct. This should have already been done by the iterator
  467. func parseValueFromKey(key []byte) (string, error) {
  468. var (
  469. compositeKey, value string
  470. height, index int64
  471. )
  472. remaining, err := orderedcode.Parse(string(key), &compositeKey, &value, &height, &index)
  473. if err != nil {
  474. return "", err
  475. }
  476. if len(remaining) != 0 {
  477. return "", fmt.Errorf("unexpected remainder in key: %s", remaining)
  478. }
  479. return value, nil
  480. }
  481. func keyFromEvent(compositeKey string, value string, result *abci.TxResult) []byte {
  482. return secondaryKey(compositeKey, value, result.Height, result.Index)
  483. }
  484. func KeyFromHeight(result *abci.TxResult) []byte {
  485. return secondaryKey(types.TxHeightKey, fmt.Sprintf("%d", result.Height), result.Height, result.Index)
  486. }
  487. // Prefixes: these represent an initial part of the key and are used by iterators to iterate over a small
  488. // section of the kv store during searches.
  489. func prefixFromCompositeKey(compositeKey string) []byte {
  490. key, err := orderedcode.Append(nil, compositeKey)
  491. if err != nil {
  492. panic(err)
  493. }
  494. return key
  495. }
  496. func prefixFromCompositeKeyAndValue(compositeKey, value string) []byte {
  497. key, err := orderedcode.Append(nil, compositeKey, value)
  498. if err != nil {
  499. panic(err)
  500. }
  501. return key
  502. }
  503. // a small utility function for getting a keys prefix based on a condition and a height
  504. func prefixForCondition(c query.Condition, height int64) []byte {
  505. key := prefixFromCompositeKeyAndValue(c.CompositeKey, fmt.Sprintf("%v", c.Operand))
  506. if height > 0 {
  507. var err error
  508. key, err = orderedcode.Append(key, height)
  509. if err != nil {
  510. panic(err)
  511. }
  512. }
  513. return key
  514. }