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.

659 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
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
5 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
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
5 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
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
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
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
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
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
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
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
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
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
5 years ago
  1. package kv
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/hex"
  6. "fmt"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/gogo/protobuf/proto"
  11. dbm "github.com/tendermint/tm-db"
  12. abci "github.com/tendermint/tendermint/abci/types"
  13. "github.com/tendermint/tendermint/libs/pubsub/query"
  14. "github.com/tendermint/tendermint/state/txindex"
  15. "github.com/tendermint/tendermint/types"
  16. )
  17. const (
  18. tagKeySeparator = "/"
  19. )
  20. var _ txindex.TxIndexer = (*TxIndex)(nil)
  21. // TxIndex is the simplest possible indexer, backed by key-value storage (levelDB).
  22. type TxIndex struct {
  23. store dbm.DB
  24. }
  25. // NewTxIndex creates new KV indexer.
  26. func NewTxIndex(store dbm.DB) *TxIndex {
  27. return &TxIndex{
  28. store: store,
  29. }
  30. }
  31. // Get gets transaction from the TxIndex storage and returns it or nil if the
  32. // transaction is not found.
  33. func (txi *TxIndex) Get(hash []byte) (*abci.TxResult, error) {
  34. if len(hash) == 0 {
  35. return nil, txindex.ErrorEmptyHash
  36. }
  37. rawBytes, err := txi.store.Get(hash)
  38. if err != nil {
  39. panic(err)
  40. }
  41. if rawBytes == nil {
  42. return nil, nil
  43. }
  44. txResult := new(abci.TxResult)
  45. err = proto.Unmarshal(rawBytes, txResult)
  46. if err != nil {
  47. return nil, fmt.Errorf("error reading TxResult: %v", err)
  48. }
  49. return txResult, nil
  50. }
  51. // AddBatch indexes a batch of transactions using the given list of events. Each
  52. // key that indexed from the tx's events is a composite of the event type and
  53. // the respective attribute's key delimited by a "." (eg. "account.number").
  54. // Any event with an empty type is not indexed.
  55. func (txi *TxIndex) AddBatch(b *txindex.Batch) error {
  56. storeBatch := txi.store.NewBatch()
  57. defer storeBatch.Close()
  58. for _, result := range b.Ops {
  59. hash := types.Tx(result.Tx).Hash()
  60. // index tx by events
  61. err := txi.indexEvents(result, hash, storeBatch)
  62. if err != nil {
  63. return err
  64. }
  65. // index by height (always)
  66. err = storeBatch.Set(keyForHeight(result), hash)
  67. if err != nil {
  68. return err
  69. }
  70. rawBytes, err := proto.Marshal(result)
  71. if err != nil {
  72. return err
  73. }
  74. // index by hash (always)
  75. err = storeBatch.Set(hash, rawBytes)
  76. if err != nil {
  77. return err
  78. }
  79. }
  80. return storeBatch.WriteSync()
  81. }
  82. // Index indexes a single transaction using the given list of events. Each key
  83. // that indexed from the tx's events is a composite of the event type and the
  84. // respective attribute's key delimited by a "." (eg. "account.number").
  85. // Any event with an empty type is not indexed.
  86. func (txi *TxIndex) Index(result *abci.TxResult) error {
  87. b := txi.store.NewBatch()
  88. defer b.Close()
  89. hash := types.Tx(result.Tx).Hash()
  90. // index tx by events
  91. err := txi.indexEvents(result, hash, b)
  92. if err != nil {
  93. return err
  94. }
  95. // index by height (always)
  96. err = b.Set(keyForHeight(result), hash)
  97. if err != nil {
  98. return err
  99. }
  100. rawBytes, err := proto.Marshal(result)
  101. if err != nil {
  102. return err
  103. }
  104. // index by hash (always)
  105. err = b.Set(hash, rawBytes)
  106. if err != nil {
  107. return err
  108. }
  109. return b.WriteSync()
  110. }
  111. func (txi *TxIndex) indexEvents(result *abci.TxResult, hash []byte, store dbm.Batch) error {
  112. for _, event := range result.Result.Events {
  113. // only index events with a non-empty type
  114. if len(event.Type) == 0 {
  115. continue
  116. }
  117. for _, attr := range event.Attributes {
  118. if len(attr.Key) == 0 {
  119. continue
  120. }
  121. // index if `index: true` is set
  122. compositeTag := fmt.Sprintf("%s.%s", event.Type, string(attr.Key))
  123. if attr.GetIndex() {
  124. err := store.Set(keyForEvent(compositeTag, attr.Value, result), hash)
  125. if err != nil {
  126. return err
  127. }
  128. }
  129. }
  130. }
  131. return nil
  132. }
  133. // Search performs a search using the given query.
  134. //
  135. // It breaks the query into conditions (like "tx.height > 5"). For each
  136. // condition, it queries the DB index. One special use cases here: (1) if
  137. // "tx.hash" is found, it returns tx result for it (2) for range queries it is
  138. // better for the client to provide both lower and upper bounds, so we are not
  139. // performing a full scan. Results from querying indexes are then intersected
  140. // and returned to the caller, in no particular order.
  141. //
  142. // Search will exit early and return any result fetched so far,
  143. // when a message is received on the context chan.
  144. func (txi *TxIndex) Search(ctx context.Context, q *query.Query) ([]*abci.TxResult, error) {
  145. // Potentially exit early.
  146. select {
  147. case <-ctx.Done():
  148. results := make([]*abci.TxResult, 0)
  149. return results, nil
  150. default:
  151. }
  152. var hashesInitialized bool
  153. filteredHashes := make(map[string][]byte)
  154. // get a list of conditions (like "tx.height > 5")
  155. conditions, err := q.Conditions()
  156. if err != nil {
  157. return nil, fmt.Errorf("error during parsing conditions from query: %w", err)
  158. }
  159. // if there is a hash condition, return the result immediately
  160. hash, ok, err := lookForHash(conditions)
  161. if err != nil {
  162. return nil, fmt.Errorf("error during searching for a hash in the query: %w", err)
  163. } else if ok {
  164. res, err := txi.Get(hash)
  165. switch {
  166. case err != nil:
  167. return []*abci.TxResult{}, fmt.Errorf("error while retrieving the result: %w", err)
  168. case res == nil:
  169. return []*abci.TxResult{}, nil
  170. default:
  171. return []*abci.TxResult{res}, nil
  172. }
  173. }
  174. // conditions to skip because they're handled before "everything else"
  175. skipIndexes := make([]int, 0)
  176. // extract ranges
  177. // if both upper and lower bounds exist, it's better to get them in order not
  178. // no iterate over kvs that are not within range.
  179. ranges, rangeIndexes := lookForRanges(conditions)
  180. if len(ranges) > 0 {
  181. skipIndexes = append(skipIndexes, rangeIndexes...)
  182. for _, r := range ranges {
  183. if !hashesInitialized {
  184. filteredHashes = txi.matchRange(ctx, r, startKey(r.key), filteredHashes, true)
  185. hashesInitialized = true
  186. // Ignore any remaining conditions if the first condition resulted
  187. // in no matches (assuming implicit AND operand).
  188. if len(filteredHashes) == 0 {
  189. break
  190. }
  191. } else {
  192. filteredHashes = txi.matchRange(ctx, r, startKey(r.key), filteredHashes, false)
  193. }
  194. }
  195. }
  196. // if there is a height condition ("tx.height=3"), extract it
  197. height := lookForHeight(conditions)
  198. // for all other conditions
  199. for i, c := range conditions {
  200. if intInSlice(i, skipIndexes) {
  201. continue
  202. }
  203. if !hashesInitialized {
  204. filteredHashes = txi.match(ctx, c, startKeyForCondition(c, height), filteredHashes, true)
  205. hashesInitialized = true
  206. // Ignore any remaining conditions if the first condition resulted
  207. // in no matches (assuming implicit AND operand).
  208. if len(filteredHashes) == 0 {
  209. break
  210. }
  211. } else {
  212. filteredHashes = txi.match(ctx, c, startKeyForCondition(c, height), filteredHashes, false)
  213. }
  214. }
  215. results := make([]*abci.TxResult, 0, len(filteredHashes))
  216. for _, h := range filteredHashes {
  217. res, err := txi.Get(h)
  218. if err != nil {
  219. return nil, fmt.Errorf("failed to get Tx{%X}: %w", h, err)
  220. }
  221. results = append(results, res)
  222. // Potentially exit early.
  223. select {
  224. case <-ctx.Done():
  225. break
  226. default:
  227. }
  228. }
  229. return results, nil
  230. }
  231. func lookForHash(conditions []query.Condition) (hash []byte, ok bool, err error) {
  232. for _, c := range conditions {
  233. if c.CompositeKey == types.TxHashKey {
  234. decoded, err := hex.DecodeString(c.Operand.(string))
  235. return decoded, true, err
  236. }
  237. }
  238. return
  239. }
  240. // lookForHeight returns a height if there is an "height=X" condition.
  241. func lookForHeight(conditions []query.Condition) (height int64) {
  242. for _, c := range conditions {
  243. if c.CompositeKey == types.TxHeightKey && c.Op == query.OpEqual {
  244. return c.Operand.(int64)
  245. }
  246. }
  247. return 0
  248. }
  249. // special map to hold range conditions
  250. // Example: account.number => queryRange{lowerBound: 1, upperBound: 5}
  251. type queryRanges map[string]queryRange
  252. type queryRange struct {
  253. lowerBound interface{} // int || time.Time
  254. upperBound interface{} // int || time.Time
  255. key string
  256. includeLowerBound bool
  257. includeUpperBound bool
  258. }
  259. func (r queryRange) lowerBoundValue() interface{} {
  260. if r.lowerBound == nil {
  261. return nil
  262. }
  263. if r.includeLowerBound {
  264. return r.lowerBound
  265. }
  266. switch t := r.lowerBound.(type) {
  267. case int64:
  268. return t + 1
  269. case time.Time:
  270. return t.Unix() + 1
  271. default:
  272. panic("not implemented")
  273. }
  274. }
  275. func (r queryRange) AnyBound() interface{} {
  276. if r.lowerBound != nil {
  277. return r.lowerBound
  278. }
  279. return r.upperBound
  280. }
  281. func (r queryRange) upperBoundValue() interface{} {
  282. if r.upperBound == nil {
  283. return nil
  284. }
  285. if r.includeUpperBound {
  286. return r.upperBound
  287. }
  288. switch t := r.upperBound.(type) {
  289. case int64:
  290. return t - 1
  291. case time.Time:
  292. return t.Unix() - 1
  293. default:
  294. panic("not implemented")
  295. }
  296. }
  297. func lookForRanges(conditions []query.Condition) (ranges queryRanges, indexes []int) {
  298. ranges = make(queryRanges)
  299. for i, c := range conditions {
  300. if isRangeOperation(c.Op) {
  301. r, ok := ranges[c.CompositeKey]
  302. if !ok {
  303. r = queryRange{key: c.CompositeKey}
  304. }
  305. switch c.Op {
  306. case query.OpGreater:
  307. r.lowerBound = c.Operand
  308. case query.OpGreaterEqual:
  309. r.includeLowerBound = true
  310. r.lowerBound = c.Operand
  311. case query.OpLess:
  312. r.upperBound = c.Operand
  313. case query.OpLessEqual:
  314. r.includeUpperBound = true
  315. r.upperBound = c.Operand
  316. }
  317. ranges[c.CompositeKey] = r
  318. indexes = append(indexes, i)
  319. }
  320. }
  321. return ranges, indexes
  322. }
  323. func isRangeOperation(op query.Operator) bool {
  324. switch op {
  325. case query.OpGreater, query.OpGreaterEqual, query.OpLess, query.OpLessEqual:
  326. return true
  327. default:
  328. return false
  329. }
  330. }
  331. // match returns all matching txs by hash that meet a given condition and start
  332. // key. An already filtered result (filteredHashes) is provided such that any
  333. // non-intersecting matches are removed.
  334. //
  335. // NOTE: filteredHashes may be empty if no previous condition has matched.
  336. func (txi *TxIndex) match(
  337. ctx context.Context,
  338. c query.Condition,
  339. startKeyBz []byte,
  340. filteredHashes map[string][]byte,
  341. firstRun bool,
  342. ) map[string][]byte {
  343. // A previous match was attempted but resulted in no matches, so we return
  344. // no matches (assuming AND operand).
  345. if !firstRun && len(filteredHashes) == 0 {
  346. return filteredHashes
  347. }
  348. tmpHashes := make(map[string][]byte)
  349. switch {
  350. case c.Op == query.OpEqual:
  351. it, err := dbm.IteratePrefix(txi.store, startKeyBz)
  352. if err != nil {
  353. panic(err)
  354. }
  355. defer it.Close()
  356. for ; it.Valid(); it.Next() {
  357. tmpHashes[string(it.Value())] = it.Value()
  358. // Potentially exit early.
  359. select {
  360. case <-ctx.Done():
  361. break
  362. default:
  363. }
  364. }
  365. if err := it.Error(); err != nil {
  366. panic(err)
  367. }
  368. case c.Op == query.OpExists:
  369. // XXX: can't use startKeyBz here because c.Operand is nil
  370. // (e.g. "account.owner/<nil>/" won't match w/ a single row)
  371. it, err := dbm.IteratePrefix(txi.store, startKey(c.CompositeKey))
  372. if err != nil {
  373. panic(err)
  374. }
  375. defer it.Close()
  376. for ; it.Valid(); it.Next() {
  377. tmpHashes[string(it.Value())] = it.Value()
  378. // Potentially exit early.
  379. select {
  380. case <-ctx.Done():
  381. break
  382. default:
  383. }
  384. }
  385. if err := it.Error(); err != nil {
  386. panic(err)
  387. }
  388. case c.Op == query.OpContains:
  389. // XXX: startKey does not apply here.
  390. // For example, if startKey = "account.owner/an/" and search query = "account.owner CONTAINS an"
  391. // we can't iterate with prefix "account.owner/an/" because we might miss keys like "account.owner/Ulan/"
  392. it, err := dbm.IteratePrefix(txi.store, startKey(c.CompositeKey))
  393. if err != nil {
  394. panic(err)
  395. }
  396. defer it.Close()
  397. for ; it.Valid(); it.Next() {
  398. if !isTagKey(it.Key()) {
  399. continue
  400. }
  401. if strings.Contains(extractValueFromKey(it.Key()), c.Operand.(string)) {
  402. tmpHashes[string(it.Value())] = it.Value()
  403. }
  404. // Potentially exit early.
  405. select {
  406. case <-ctx.Done():
  407. break
  408. default:
  409. }
  410. }
  411. if err := it.Error(); err != nil {
  412. panic(err)
  413. }
  414. default:
  415. panic("other operators should be handled already")
  416. }
  417. if len(tmpHashes) == 0 || firstRun {
  418. // Either:
  419. //
  420. // 1. Regardless if a previous match was attempted, which may have had
  421. // results, but no match was found for the current condition, then we
  422. // return no matches (assuming AND operand).
  423. //
  424. // 2. A previous match was not attempted, so we return all results.
  425. return tmpHashes
  426. }
  427. // Remove/reduce matches in filteredHashes that were not found in this
  428. // match (tmpHashes).
  429. for k := range filteredHashes {
  430. if tmpHashes[k] == nil {
  431. delete(filteredHashes, k)
  432. // Potentially exit early.
  433. select {
  434. case <-ctx.Done():
  435. break
  436. default:
  437. }
  438. }
  439. }
  440. return filteredHashes
  441. }
  442. // matchRange returns all matching txs by hash that meet a given queryRange and
  443. // start key. An already filtered result (filteredHashes) is provided such that
  444. // any non-intersecting matches are removed.
  445. //
  446. // NOTE: filteredHashes may be empty if no previous condition has matched.
  447. func (txi *TxIndex) matchRange(
  448. ctx context.Context,
  449. r queryRange,
  450. startKey []byte,
  451. filteredHashes map[string][]byte,
  452. firstRun bool,
  453. ) map[string][]byte {
  454. // A previous match was attempted but resulted in no matches, so we return
  455. // no matches (assuming AND operand).
  456. if !firstRun && len(filteredHashes) == 0 {
  457. return filteredHashes
  458. }
  459. tmpHashes := make(map[string][]byte)
  460. lowerBound := r.lowerBoundValue()
  461. upperBound := r.upperBoundValue()
  462. it, err := dbm.IteratePrefix(txi.store, startKey)
  463. if err != nil {
  464. panic(err)
  465. }
  466. defer it.Close()
  467. LOOP:
  468. for ; it.Valid(); it.Next() {
  469. if !isTagKey(it.Key()) {
  470. continue
  471. }
  472. if _, ok := r.AnyBound().(int64); ok {
  473. v, err := strconv.ParseInt(extractValueFromKey(it.Key()), 10, 64)
  474. if err != nil {
  475. continue LOOP
  476. }
  477. include := true
  478. if lowerBound != nil && v < lowerBound.(int64) {
  479. include = false
  480. }
  481. if upperBound != nil && v > upperBound.(int64) {
  482. include = false
  483. }
  484. if include {
  485. tmpHashes[string(it.Value())] = it.Value()
  486. }
  487. // XXX: passing time in a ABCI Events is not yet implemented
  488. // case time.Time:
  489. // v := strconv.ParseInt(extractValueFromKey(it.Key()), 10, 64)
  490. // if v == r.upperBound {
  491. // break
  492. // }
  493. }
  494. // Potentially exit early.
  495. select {
  496. case <-ctx.Done():
  497. break
  498. default:
  499. }
  500. }
  501. if err := it.Error(); err != nil {
  502. panic(err)
  503. }
  504. if len(tmpHashes) == 0 || firstRun {
  505. // Either:
  506. //
  507. // 1. Regardless if a previous match was attempted, which may have had
  508. // results, but no match was found for the current condition, then we
  509. // return no matches (assuming AND operand).
  510. //
  511. // 2. A previous match was not attempted, so we return all results.
  512. return tmpHashes
  513. }
  514. // Remove/reduce matches in filteredHashes that were not found in this
  515. // match (tmpHashes).
  516. for k := range filteredHashes {
  517. if tmpHashes[k] == nil {
  518. delete(filteredHashes, k)
  519. // Potentially exit early.
  520. select {
  521. case <-ctx.Done():
  522. break
  523. default:
  524. }
  525. }
  526. }
  527. return filteredHashes
  528. }
  529. ///////////////////////////////////////////////////////////////////////////////
  530. // Keys
  531. func isTagKey(key []byte) bool {
  532. return strings.Count(string(key), tagKeySeparator) == 3
  533. }
  534. func extractValueFromKey(key []byte) string {
  535. parts := strings.SplitN(string(key), tagKeySeparator, 3)
  536. return parts[1]
  537. }
  538. func keyForEvent(key string, value []byte, result *abci.TxResult) []byte {
  539. return []byte(fmt.Sprintf("%s/%s/%d/%d",
  540. key,
  541. value,
  542. result.Height,
  543. result.Index,
  544. ))
  545. }
  546. func keyForHeight(result *abci.TxResult) []byte {
  547. return []byte(fmt.Sprintf("%s/%d/%d/%d",
  548. types.TxHeightKey,
  549. result.Height,
  550. result.Height,
  551. result.Index,
  552. ))
  553. }
  554. func startKeyForCondition(c query.Condition, height int64) []byte {
  555. if height > 0 {
  556. return startKey(c.CompositeKey, c.Operand, height)
  557. }
  558. return startKey(c.CompositeKey, c.Operand)
  559. }
  560. func startKey(fields ...interface{}) []byte {
  561. var b bytes.Buffer
  562. for _, f := range fields {
  563. b.Write([]byte(fmt.Sprintf("%v", f) + tagKeySeparator))
  564. }
  565. return b.Bytes()
  566. }