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.

586 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. "github.com/tendermint/tendermint/libs/pubsub/query"
  13. indexer "github.com/tendermint/tendermint/state/indexer"
  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. for _, h := range filteredHashes {
  189. res, err := txi.Get(h)
  190. if err != nil {
  191. return nil, fmt.Errorf("failed to get Tx{%X}: %w", h, err)
  192. }
  193. results = append(results, res)
  194. // Potentially exit early.
  195. select {
  196. case <-ctx.Done():
  197. break
  198. default:
  199. }
  200. }
  201. return results, nil
  202. }
  203. func lookForHash(conditions []query.Condition) (hash []byte, ok bool, err error) {
  204. for _, c := range conditions {
  205. if c.CompositeKey == types.TxHashKey {
  206. decoded, err := hex.DecodeString(c.Operand.(string))
  207. return decoded, true, err
  208. }
  209. }
  210. return
  211. }
  212. // lookForHeight returns a height if there is an "height=X" condition.
  213. func lookForHeight(conditions []query.Condition) (height int64) {
  214. for _, c := range conditions {
  215. if c.CompositeKey == types.TxHeightKey && c.Op == query.OpEqual {
  216. return c.Operand.(int64)
  217. }
  218. }
  219. return 0
  220. }
  221. // match returns all matching txs by hash that meet a given condition and start
  222. // key. An already filtered result (filteredHashes) is provided such that any
  223. // non-intersecting matches are removed.
  224. //
  225. // NOTE: filteredHashes may be empty if no previous condition has matched.
  226. func (txi *TxIndex) match(
  227. ctx context.Context,
  228. c query.Condition,
  229. startKeyBz []byte,
  230. filteredHashes map[string][]byte,
  231. firstRun bool,
  232. ) map[string][]byte {
  233. // A previous match was attempted but resulted in no matches, so we return
  234. // no matches (assuming AND operand).
  235. if !firstRun && len(filteredHashes) == 0 {
  236. return filteredHashes
  237. }
  238. tmpHashes := make(map[string][]byte)
  239. switch {
  240. case c.Op == query.OpEqual:
  241. it, err := dbm.IteratePrefix(txi.store, startKeyBz)
  242. if err != nil {
  243. panic(err)
  244. }
  245. defer it.Close()
  246. for ; it.Valid(); it.Next() {
  247. tmpHashes[string(it.Value())] = it.Value()
  248. // Potentially exit early.
  249. select {
  250. case <-ctx.Done():
  251. break
  252. default:
  253. }
  254. }
  255. if err := it.Error(); err != nil {
  256. panic(err)
  257. }
  258. case c.Op == query.OpExists:
  259. // XXX: can't use startKeyBz here because c.Operand is nil
  260. // (e.g. "account.owner/<nil>/" won't match w/ a single row)
  261. it, err := dbm.IteratePrefix(txi.store, prefixFromCompositeKey(c.CompositeKey))
  262. if err != nil {
  263. panic(err)
  264. }
  265. defer it.Close()
  266. for ; it.Valid(); it.Next() {
  267. tmpHashes[string(it.Value())] = it.Value()
  268. // Potentially exit early.
  269. select {
  270. case <-ctx.Done():
  271. break
  272. default:
  273. }
  274. }
  275. if err := it.Error(); err != nil {
  276. panic(err)
  277. }
  278. case c.Op == query.OpContains:
  279. // XXX: startKey does not apply here.
  280. // For example, if startKey = "account.owner/an/" and search query = "account.owner CONTAINS an"
  281. // we can't iterate with prefix "account.owner/an/" because we might miss keys like "account.owner/Ulan/"
  282. it, err := dbm.IteratePrefix(txi.store, prefixFromCompositeKey(c.CompositeKey))
  283. if err != nil {
  284. panic(err)
  285. }
  286. defer it.Close()
  287. for ; it.Valid(); it.Next() {
  288. value, err := parseValueFromKey(it.Key())
  289. if err != nil {
  290. continue
  291. }
  292. if strings.Contains(value, c.Operand.(string)) {
  293. tmpHashes[string(it.Value())] = it.Value()
  294. }
  295. // Potentially exit early.
  296. select {
  297. case <-ctx.Done():
  298. break
  299. default:
  300. }
  301. }
  302. if err := it.Error(); err != nil {
  303. panic(err)
  304. }
  305. default:
  306. panic("other operators should be handled already")
  307. }
  308. if len(tmpHashes) == 0 || firstRun {
  309. // Either:
  310. //
  311. // 1. Regardless if a previous match was attempted, which may have had
  312. // results, but no match was found for the current condition, then we
  313. // return no matches (assuming AND operand).
  314. //
  315. // 2. A previous match was not attempted, so we return all results.
  316. return tmpHashes
  317. }
  318. // Remove/reduce matches in filteredHashes that were not found in this
  319. // match (tmpHashes).
  320. for k := range filteredHashes {
  321. if tmpHashes[k] == nil {
  322. delete(filteredHashes, k)
  323. // Potentially exit early.
  324. select {
  325. case <-ctx.Done():
  326. break
  327. default:
  328. }
  329. }
  330. }
  331. return filteredHashes
  332. }
  333. // matchRange returns all matching txs by hash that meet a given queryRange and
  334. // start key. An already filtered result (filteredHashes) is provided such that
  335. // any non-intersecting matches are removed.
  336. //
  337. // NOTE: filteredHashes may be empty if no previous condition has matched.
  338. func (txi *TxIndex) matchRange(
  339. ctx context.Context,
  340. qr indexer.QueryRange,
  341. startKey []byte,
  342. filteredHashes map[string][]byte,
  343. firstRun bool,
  344. ) map[string][]byte {
  345. // A previous match was attempted but resulted in no matches, so we return
  346. // no matches (assuming AND operand).
  347. if !firstRun && len(filteredHashes) == 0 {
  348. return filteredHashes
  349. }
  350. tmpHashes := make(map[string][]byte)
  351. lowerBound := qr.LowerBoundValue()
  352. upperBound := qr.UpperBoundValue()
  353. it, err := dbm.IteratePrefix(txi.store, startKey)
  354. if err != nil {
  355. panic(err)
  356. }
  357. defer it.Close()
  358. LOOP:
  359. for ; it.Valid(); it.Next() {
  360. value, err := parseValueFromKey(it.Key())
  361. if err != nil {
  362. continue
  363. }
  364. if _, ok := qr.AnyBound().(int64); ok {
  365. v, err := strconv.ParseInt(value, 10, 64)
  366. if err != nil {
  367. continue LOOP
  368. }
  369. include := true
  370. if lowerBound != nil && v < lowerBound.(int64) {
  371. include = false
  372. }
  373. if upperBound != nil && v > upperBound.(int64) {
  374. include = false
  375. }
  376. if include {
  377. tmpHashes[string(it.Value())] = it.Value()
  378. }
  379. // XXX: passing time in a ABCI Events is not yet implemented
  380. // case time.Time:
  381. // v := strconv.ParseInt(extractValueFromKey(it.Key()), 10, 64)
  382. // if v == r.upperBound {
  383. // break
  384. // }
  385. }
  386. // Potentially exit early.
  387. select {
  388. case <-ctx.Done():
  389. break
  390. default:
  391. }
  392. }
  393. if err := it.Error(); err != nil {
  394. panic(err)
  395. }
  396. if len(tmpHashes) == 0 || firstRun {
  397. // Either:
  398. //
  399. // 1. Regardless if a previous match was attempted, which may have had
  400. // results, but no match was found for the current condition, then we
  401. // return no matches (assuming AND operand).
  402. //
  403. // 2. A previous match was not attempted, so we return all results.
  404. return tmpHashes
  405. }
  406. // Remove/reduce matches in filteredHashes that were not found in this
  407. // match (tmpHashes).
  408. for k := range filteredHashes {
  409. if tmpHashes[k] == nil {
  410. delete(filteredHashes, k)
  411. // Potentially exit early.
  412. select {
  413. case <-ctx.Done():
  414. break
  415. default:
  416. }
  417. }
  418. }
  419. return filteredHashes
  420. }
  421. // ########################## Keys #############################
  422. //
  423. // The indexer has two types of kv stores:
  424. // 1. txhash - result (primary key)
  425. // 2. event - txhash (secondary key)
  426. //
  427. // The event key can be decomposed into 4 parts.
  428. // 1. A composite key which can be any string.
  429. // Usually something like "tx.height" or "account.owner"
  430. // 2. A value. That corresponds to the key. In the above
  431. // example the value could be "5" or "Ivan"
  432. // 3. The height of the Tx that aligns with the key and value.
  433. // 4. The index of the Tx that aligns with the key and value
  434. // the hash/primary key
  435. func primaryKey(hash []byte) []byte {
  436. key, err := orderedcode.Append(
  437. nil,
  438. types.TxHashKey,
  439. string(hash),
  440. )
  441. if err != nil {
  442. panic(err)
  443. }
  444. return key
  445. }
  446. // The event/secondary key
  447. func secondaryKey(compositeKey, value string, height int64, index uint32) []byte {
  448. key, err := orderedcode.Append(
  449. nil,
  450. compositeKey,
  451. value,
  452. height,
  453. int64(index),
  454. )
  455. if err != nil {
  456. panic(err)
  457. }
  458. return key
  459. }
  460. // parseValueFromKey parses an event key and extracts out the value, returning an error if one arises.
  461. // This will also involve ensuring that the key has the correct format.
  462. // CONTRACT: function doesn't check that the prefix is correct. This should have already been done by the iterator
  463. func parseValueFromKey(key []byte) (string, error) {
  464. var (
  465. compositeKey, value string
  466. height, index int64
  467. )
  468. remaining, err := orderedcode.Parse(string(key), &compositeKey, &value, &height, &index)
  469. if err != nil {
  470. return "", err
  471. }
  472. if len(remaining) != 0 {
  473. return "", fmt.Errorf("unexpected remainder in key: %s", remaining)
  474. }
  475. return value, nil
  476. }
  477. func keyFromEvent(compositeKey string, value string, result *abci.TxResult) []byte {
  478. return secondaryKey(compositeKey, value, result.Height, result.Index)
  479. }
  480. func KeyFromHeight(result *abci.TxResult) []byte {
  481. return secondaryKey(types.TxHeightKey, fmt.Sprintf("%d", result.Height), result.Height, result.Index)
  482. }
  483. // Prefixes: these represent an initial part of the key and are used by iterators to iterate over a small
  484. // section of the kv store during searches.
  485. func prefixFromCompositeKey(compositeKey string) []byte {
  486. key, err := orderedcode.Append(nil, compositeKey)
  487. if err != nil {
  488. panic(err)
  489. }
  490. return key
  491. }
  492. func prefixFromCompositeKeyAndValue(compositeKey, value string) []byte {
  493. key, err := orderedcode.Append(nil, compositeKey, value)
  494. if err != nil {
  495. panic(err)
  496. }
  497. return key
  498. }
  499. // a small utility function for getting a keys prefix based on a condition and a height
  500. func prefixForCondition(c query.Condition, height int64) []byte {
  501. key := prefixFromCompositeKeyAndValue(c.CompositeKey, fmt.Sprintf("%v", c.Operand))
  502. if height > 0 {
  503. var err error
  504. key, err = orderedcode.Append(key, height)
  505. if err != nil {
  506. panic(err)
  507. }
  508. }
  509. return key
  510. }