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.

717 lines
18 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
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
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
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
6 years ago
  1. package kv
  2. import (
  3. "context"
  4. "encoding/hex"
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "github.com/gogo/protobuf/proto"
  10. "github.com/google/orderedcode"
  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. var _ txindex.TxIndexer = (*TxIndex)(nil)
  18. // TxIndex is the simplest possible indexer
  19. // It is backed by two kv stores:
  20. // 1. txhash - result (primary key)
  21. // 2. event - txhash (secondary key)
  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(primaryKey(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(keyFromHeight(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(primaryKey(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(keyFromHeight(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(primaryKey(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. // ensure event does not conflict with a reserved prefix key
  124. if compositeTag == types.TxHashKey || compositeTag == types.TxHeightKey {
  125. return fmt.Errorf("event type and attribute key \"%s\" is reserved. Please use a different key", compositeTag)
  126. }
  127. if attr.GetIndex() {
  128. err := store.Set(keyFromEvent(compositeTag, attr.Value, result), hash)
  129. if err != nil {
  130. return err
  131. }
  132. }
  133. }
  134. }
  135. return nil
  136. }
  137. // Search performs a search using the given query.
  138. //
  139. // It breaks the query into conditions (like "tx.height > 5"). For each
  140. // condition, it queries the DB index. One special use cases here: (1) if
  141. // "tx.hash" is found, it returns tx result for it (2) for range queries it is
  142. // better for the client to provide both lower and upper bounds, so we are not
  143. // performing a full scan. Results from querying indexes are then intersected
  144. // and returned to the caller, in no particular order.
  145. //
  146. // Search will exit early and return any result fetched so far,
  147. // when a message is received on the context chan.
  148. func (txi *TxIndex) Search(ctx context.Context, q *query.Query) ([]*abci.TxResult, error) {
  149. // Potentially exit early.
  150. select {
  151. case <-ctx.Done():
  152. results := make([]*abci.TxResult, 0)
  153. return results, nil
  154. default:
  155. }
  156. var hashesInitialized bool
  157. filteredHashes := make(map[string][]byte)
  158. // get a list of conditions (like "tx.height > 5")
  159. conditions, err := q.Conditions()
  160. if err != nil {
  161. return nil, fmt.Errorf("error during parsing conditions from query: %w", err)
  162. }
  163. // if there is a hash condition, return the result immediately
  164. hash, ok, err := lookForHash(conditions)
  165. if err != nil {
  166. return nil, fmt.Errorf("error during searching for a hash in the query: %w", err)
  167. } else if ok {
  168. res, err := txi.Get(hash)
  169. switch {
  170. case err != nil:
  171. return []*abci.TxResult{}, fmt.Errorf("error while retrieving the result: %w", err)
  172. case res == nil:
  173. return []*abci.TxResult{}, nil
  174. default:
  175. return []*abci.TxResult{res}, nil
  176. }
  177. }
  178. // conditions to skip because they're handled before "everything else"
  179. skipIndexes := make([]int, 0)
  180. // extract ranges
  181. // if both upper and lower bounds exist, it's better to get them in order not
  182. // no iterate over kvs that are not within range.
  183. ranges, rangeIndexes := lookForRanges(conditions)
  184. if len(ranges) > 0 {
  185. skipIndexes = append(skipIndexes, rangeIndexes...)
  186. for _, r := range ranges {
  187. if !hashesInitialized {
  188. filteredHashes = txi.matchRange(ctx, r, prefixFromCompositeKey(r.key), filteredHashes, true)
  189. hashesInitialized = true
  190. // Ignore any remaining conditions if the first condition resulted
  191. // in no matches (assuming implicit AND operand).
  192. if len(filteredHashes) == 0 {
  193. break
  194. }
  195. } else {
  196. filteredHashes = txi.matchRange(ctx, r, prefixFromCompositeKey(r.key), filteredHashes, false)
  197. }
  198. }
  199. }
  200. // if there is a height condition ("tx.height=3"), extract it
  201. height := lookForHeight(conditions)
  202. // for all other conditions
  203. for i, c := range conditions {
  204. if intInSlice(i, skipIndexes) {
  205. continue
  206. }
  207. if !hashesInitialized {
  208. filteredHashes = txi.match(ctx, c, prefixForCondition(c, height), filteredHashes, true)
  209. hashesInitialized = true
  210. // Ignore any remaining conditions if the first condition resulted
  211. // in no matches (assuming implicit AND operand).
  212. if len(filteredHashes) == 0 {
  213. break
  214. }
  215. } else {
  216. filteredHashes = txi.match(ctx, c, prefixForCondition(c, height), filteredHashes, false)
  217. }
  218. }
  219. results := make([]*abci.TxResult, 0, len(filteredHashes))
  220. for _, h := range filteredHashes {
  221. res, err := txi.Get(h)
  222. if err != nil {
  223. return nil, fmt.Errorf("failed to get Tx{%X}: %w", h, err)
  224. }
  225. results = append(results, res)
  226. // Potentially exit early.
  227. select {
  228. case <-ctx.Done():
  229. break
  230. default:
  231. }
  232. }
  233. return results, nil
  234. }
  235. func lookForHash(conditions []query.Condition) (hash []byte, ok bool, err error) {
  236. for _, c := range conditions {
  237. if c.CompositeKey == types.TxHashKey {
  238. decoded, err := hex.DecodeString(c.Operand.(string))
  239. return decoded, true, err
  240. }
  241. }
  242. return
  243. }
  244. // lookForHeight returns a height if there is an "height=X" condition.
  245. func lookForHeight(conditions []query.Condition) (height int64) {
  246. for _, c := range conditions {
  247. if c.CompositeKey == types.TxHeightKey && c.Op == query.OpEqual {
  248. return c.Operand.(int64)
  249. }
  250. }
  251. return 0
  252. }
  253. // special map to hold range conditions
  254. // Example: account.number => queryRange{lowerBound: 1, upperBound: 5}
  255. type queryRanges map[string]queryRange
  256. type queryRange struct {
  257. lowerBound interface{} // int || time.Time
  258. upperBound interface{} // int || time.Time
  259. key string
  260. includeLowerBound bool
  261. includeUpperBound bool
  262. }
  263. func (r queryRange) lowerBoundValue() interface{} {
  264. if r.lowerBound == nil {
  265. return nil
  266. }
  267. if r.includeLowerBound {
  268. return r.lowerBound
  269. }
  270. switch t := r.lowerBound.(type) {
  271. case int64:
  272. return t + 1
  273. case time.Time:
  274. return t.Unix() + 1
  275. default:
  276. panic("not implemented")
  277. }
  278. }
  279. func (r queryRange) AnyBound() interface{} {
  280. if r.lowerBound != nil {
  281. return r.lowerBound
  282. }
  283. return r.upperBound
  284. }
  285. func (r queryRange) upperBoundValue() interface{} {
  286. if r.upperBound == nil {
  287. return nil
  288. }
  289. if r.includeUpperBound {
  290. return r.upperBound
  291. }
  292. switch t := r.upperBound.(type) {
  293. case int64:
  294. return t - 1
  295. case time.Time:
  296. return t.Unix() - 1
  297. default:
  298. panic("not implemented")
  299. }
  300. }
  301. func lookForRanges(conditions []query.Condition) (ranges queryRanges, indexes []int) {
  302. ranges = make(queryRanges)
  303. for i, c := range conditions {
  304. if isRangeOperation(c.Op) {
  305. r, ok := ranges[c.CompositeKey]
  306. if !ok {
  307. r = queryRange{key: c.CompositeKey}
  308. }
  309. switch c.Op {
  310. case query.OpGreater:
  311. r.lowerBound = c.Operand
  312. case query.OpGreaterEqual:
  313. r.includeLowerBound = true
  314. r.lowerBound = c.Operand
  315. case query.OpLess:
  316. r.upperBound = c.Operand
  317. case query.OpLessEqual:
  318. r.includeUpperBound = true
  319. r.upperBound = c.Operand
  320. }
  321. ranges[c.CompositeKey] = r
  322. indexes = append(indexes, i)
  323. }
  324. }
  325. return ranges, indexes
  326. }
  327. func isRangeOperation(op query.Operator) bool {
  328. switch op {
  329. case query.OpGreater, query.OpGreaterEqual, query.OpLess, query.OpLessEqual:
  330. return true
  331. default:
  332. return false
  333. }
  334. }
  335. // match returns all matching txs by hash that meet a given condition and start
  336. // key. An already filtered result (filteredHashes) is provided such that any
  337. // non-intersecting matches are removed.
  338. //
  339. // NOTE: filteredHashes may be empty if no previous condition has matched.
  340. func (txi *TxIndex) match(
  341. ctx context.Context,
  342. c query.Condition,
  343. startKeyBz []byte,
  344. filteredHashes map[string][]byte,
  345. firstRun bool,
  346. ) map[string][]byte {
  347. // A previous match was attempted but resulted in no matches, so we return
  348. // no matches (assuming AND operand).
  349. if !firstRun && len(filteredHashes) == 0 {
  350. return filteredHashes
  351. }
  352. tmpHashes := make(map[string][]byte)
  353. switch {
  354. case c.Op == query.OpEqual:
  355. it, err := dbm.IteratePrefix(txi.store, startKeyBz)
  356. if err != nil {
  357. panic(err)
  358. }
  359. defer it.Close()
  360. for ; it.Valid(); it.Next() {
  361. tmpHashes[string(it.Value())] = it.Value()
  362. // Potentially exit early.
  363. select {
  364. case <-ctx.Done():
  365. break
  366. default:
  367. }
  368. }
  369. if err := it.Error(); err != nil {
  370. panic(err)
  371. }
  372. case c.Op == query.OpExists:
  373. // XXX: can't use startKeyBz here because c.Operand is nil
  374. // (e.g. "account.owner/<nil>/" won't match w/ a single row)
  375. it, err := dbm.IteratePrefix(txi.store, prefixFromCompositeKey(c.CompositeKey))
  376. if err != nil {
  377. panic(err)
  378. }
  379. defer it.Close()
  380. for ; it.Valid(); it.Next() {
  381. tmpHashes[string(it.Value())] = it.Value()
  382. // Potentially exit early.
  383. select {
  384. case <-ctx.Done():
  385. break
  386. default:
  387. }
  388. }
  389. if err := it.Error(); err != nil {
  390. panic(err)
  391. }
  392. case c.Op == query.OpContains:
  393. // XXX: startKey does not apply here.
  394. // For example, if startKey = "account.owner/an/" and search query = "account.owner CONTAINS an"
  395. // we can't iterate with prefix "account.owner/an/" because we might miss keys like "account.owner/Ulan/"
  396. it, err := dbm.IteratePrefix(txi.store, prefixFromCompositeKey(c.CompositeKey))
  397. if err != nil {
  398. panic(err)
  399. }
  400. defer it.Close()
  401. for ; it.Valid(); it.Next() {
  402. value, err := parseValueFromKey(it.Key())
  403. if err != nil {
  404. continue
  405. }
  406. if strings.Contains(value, c.Operand.(string)) {
  407. tmpHashes[string(it.Value())] = it.Value()
  408. }
  409. // Potentially exit early.
  410. select {
  411. case <-ctx.Done():
  412. break
  413. default:
  414. }
  415. }
  416. if err := it.Error(); err != nil {
  417. panic(err)
  418. }
  419. default:
  420. panic("other operators should be handled already")
  421. }
  422. if len(tmpHashes) == 0 || firstRun {
  423. // Either:
  424. //
  425. // 1. Regardless if a previous match was attempted, which may have had
  426. // results, but no match was found for the current condition, then we
  427. // return no matches (assuming AND operand).
  428. //
  429. // 2. A previous match was not attempted, so we return all results.
  430. return tmpHashes
  431. }
  432. // Remove/reduce matches in filteredHashes that were not found in this
  433. // match (tmpHashes).
  434. for k := range filteredHashes {
  435. if tmpHashes[k] == nil {
  436. delete(filteredHashes, k)
  437. // Potentially exit early.
  438. select {
  439. case <-ctx.Done():
  440. break
  441. default:
  442. }
  443. }
  444. }
  445. return filteredHashes
  446. }
  447. // matchRange returns all matching txs by hash that meet a given queryRange and
  448. // start key. An already filtered result (filteredHashes) is provided such that
  449. // any non-intersecting matches are removed.
  450. //
  451. // NOTE: filteredHashes may be empty if no previous condition has matched.
  452. func (txi *TxIndex) matchRange(
  453. ctx context.Context,
  454. r queryRange,
  455. startKey []byte,
  456. filteredHashes map[string][]byte,
  457. firstRun bool,
  458. ) map[string][]byte {
  459. // A previous match was attempted but resulted in no matches, so we return
  460. // no matches (assuming AND operand).
  461. if !firstRun && len(filteredHashes) == 0 {
  462. return filteredHashes
  463. }
  464. tmpHashes := make(map[string][]byte)
  465. lowerBound := r.lowerBoundValue()
  466. upperBound := r.upperBoundValue()
  467. it, err := dbm.IteratePrefix(txi.store, startKey)
  468. if err != nil {
  469. panic(err)
  470. }
  471. defer it.Close()
  472. LOOP:
  473. for ; it.Valid(); it.Next() {
  474. value, err := parseValueFromKey(it.Key())
  475. if err != nil {
  476. continue
  477. }
  478. if _, ok := r.AnyBound().(int64); ok {
  479. v, err := strconv.ParseInt(value, 10, 64)
  480. if err != nil {
  481. continue LOOP
  482. }
  483. include := true
  484. if lowerBound != nil && v < lowerBound.(int64) {
  485. include = false
  486. }
  487. if upperBound != nil && v > upperBound.(int64) {
  488. include = false
  489. }
  490. if include {
  491. tmpHashes[string(it.Value())] = it.Value()
  492. }
  493. // XXX: passing time in a ABCI Events is not yet implemented
  494. // case time.Time:
  495. // v := strconv.ParseInt(extractValueFromKey(it.Key()), 10, 64)
  496. // if v == r.upperBound {
  497. // break
  498. // }
  499. }
  500. // Potentially exit early.
  501. select {
  502. case <-ctx.Done():
  503. break
  504. default:
  505. }
  506. }
  507. if err := it.Error(); err != nil {
  508. panic(err)
  509. }
  510. if len(tmpHashes) == 0 || firstRun {
  511. // Either:
  512. //
  513. // 1. Regardless if a previous match was attempted, which may have had
  514. // results, but no match was found for the current condition, then we
  515. // return no matches (assuming AND operand).
  516. //
  517. // 2. A previous match was not attempted, so we return all results.
  518. return tmpHashes
  519. }
  520. // Remove/reduce matches in filteredHashes that were not found in this
  521. // match (tmpHashes).
  522. for k := range filteredHashes {
  523. if tmpHashes[k] == nil {
  524. delete(filteredHashes, k)
  525. // Potentially exit early.
  526. select {
  527. case <-ctx.Done():
  528. break
  529. default:
  530. }
  531. }
  532. }
  533. return filteredHashes
  534. }
  535. // ########################## Keys #############################
  536. //
  537. // The indexer has two types of kv stores:
  538. // 1. txhash - result (primary key)
  539. // 2. event - txhash (secondary key)
  540. //
  541. // The event key can be decomposed into 4 parts.
  542. // 1. A composite key which can be any string.
  543. // Usually something like "tx.height" or "account.owner"
  544. // 2. A value. That corresponds to the key. In the above
  545. // example the value could be "5" or "Ivan"
  546. // 3. The height of the Tx that aligns with the key and value.
  547. // 4. The index of the Tx that aligns with the key and value
  548. // the hash/primary key
  549. func primaryKey(hash []byte) []byte {
  550. key, err := orderedcode.Append(
  551. nil,
  552. types.TxHashKey,
  553. string(hash),
  554. )
  555. if err != nil {
  556. panic(err)
  557. }
  558. return key
  559. }
  560. // The event/secondary key
  561. func secondaryKey(compositeKey, value string, height int64, index uint32) []byte {
  562. key, err := orderedcode.Append(
  563. nil,
  564. compositeKey,
  565. value,
  566. height,
  567. int64(index),
  568. )
  569. if err != nil {
  570. panic(err)
  571. }
  572. return key
  573. }
  574. // parseValueFromKey parses an event key and extracts out the value, returning an error if one arises.
  575. // This will also involve ensuring that the key has the correct format.
  576. // CONTRACT: function doesn't check that the prefix is correct. This should have already been done by the iterator
  577. func parseValueFromKey(key []byte) (string, error) {
  578. var (
  579. compositeKey, value string
  580. height, index int64
  581. )
  582. remaining, err := orderedcode.Parse(string(key), &compositeKey, &value, &height, &index)
  583. if err != nil {
  584. return "", err
  585. }
  586. if len(remaining) != 0 {
  587. return "", fmt.Errorf("unexpected remainder in key: %s", remaining)
  588. }
  589. return value, nil
  590. }
  591. func keyFromEvent(compositeKey string, value []byte, result *abci.TxResult) []byte {
  592. return secondaryKey(compositeKey, string(value), result.Height, result.Index)
  593. }
  594. func keyFromHeight(result *abci.TxResult) []byte {
  595. return secondaryKey(types.TxHeightKey, fmt.Sprintf("%d", result.Height), result.Height, result.Index)
  596. }
  597. // Prefixes: these represent an initial part of the key and are used by iterators to iterate over a small
  598. // section of the kv store during searches.
  599. func prefixFromCompositeKey(compositeKey string) []byte {
  600. key, err := orderedcode.Append(nil, compositeKey)
  601. if err != nil {
  602. panic(err)
  603. }
  604. return key
  605. }
  606. func prefixFromCompositeKeyAndValue(compositeKey, value string) []byte {
  607. key, err := orderedcode.Append(nil, compositeKey, value)
  608. if err != nil {
  609. panic(err)
  610. }
  611. return key
  612. }
  613. // a small utility function for getting a keys prefix based on a condition and a height
  614. func prefixForCondition(c query.Condition, height int64) []byte {
  615. key := prefixFromCompositeKeyAndValue(c.CompositeKey, fmt.Sprintf("%v", c.Operand))
  616. if height > 0 {
  617. var err error
  618. key, err = orderedcode.Append(key, height)
  619. if err != nil {
  620. panic(err)
  621. }
  622. }
  623. return key
  624. }