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.

265 lines
7.6 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
  1. package query_test
  2. import (
  3. "fmt"
  4. "strings"
  5. "testing"
  6. "time"
  7. "github.com/tendermint/tendermint/abci/types"
  8. "github.com/tendermint/tendermint/internal/pubsub/query"
  9. "github.com/tendermint/tendermint/internal/pubsub/query/syntax"
  10. )
  11. // Example events from the OpenAPI documentation:
  12. // https://github.com/tendermint/tendermint/blob/master/rpc/openapi/openapi.yaml
  13. //
  14. // Redactions:
  15. //
  16. // - Add an explicit "tm" event for the built-in attributes.
  17. // - Remove Index fields (not relevant to tests).
  18. // - Add explicit balance values (to use in tests).
  19. //
  20. var apiEvents = []types.Event{
  21. {
  22. Type: "tm",
  23. Attributes: []types.EventAttribute{
  24. {Key: "event", Value: "Tx"},
  25. {Key: "hash", Value: "XYZ"},
  26. {Key: "height", Value: "5"},
  27. },
  28. },
  29. {
  30. Type: "rewards.withdraw",
  31. Attributes: []types.EventAttribute{
  32. {Key: "address", Value: "AddrA"},
  33. {Key: "source", Value: "SrcX"},
  34. {Key: "amount", Value: "100"},
  35. {Key: "balance", Value: "1500"},
  36. },
  37. },
  38. {
  39. Type: "rewards.withdraw",
  40. Attributes: []types.EventAttribute{
  41. {Key: "address", Value: "AddrB"},
  42. {Key: "source", Value: "SrcY"},
  43. {Key: "amount", Value: "45"},
  44. {Key: "balance", Value: "999"},
  45. },
  46. },
  47. {
  48. Type: "transfer",
  49. Attributes: []types.EventAttribute{
  50. {Key: "sender", Value: "AddrC"},
  51. {Key: "recipient", Value: "AddrD"},
  52. {Key: "amount", Value: "160"},
  53. },
  54. },
  55. }
  56. func TestCompiledMatches(t *testing.T) {
  57. var (
  58. txDate = "2017-01-01"
  59. txTime = "2018-05-03T14:45:00Z"
  60. )
  61. testCases := []struct {
  62. s string
  63. events []types.Event
  64. matches bool
  65. }{
  66. {`tm.events.type='NewBlock'`,
  67. newTestEvents(`tm|events.type=NewBlock`),
  68. true},
  69. {`tx.gas > 7`,
  70. newTestEvents(`tx|gas=8`),
  71. true},
  72. {`transfer.amount > 7`,
  73. newTestEvents(`transfer|amount=8stake`),
  74. true},
  75. {`transfer.amount > 7`,
  76. newTestEvents(`transfer|amount=8.045`),
  77. true},
  78. {`transfer.amount > 7.043`,
  79. newTestEvents(`transfer|amount=8.045stake`),
  80. true},
  81. {`transfer.amount > 8.045`,
  82. newTestEvents(`transfer|amount=8.045stake`),
  83. false},
  84. {`tx.gas > 7 AND tx.gas < 9`,
  85. newTestEvents(`tx|gas=8`),
  86. true},
  87. {`body.weight >= 3.5`,
  88. newTestEvents(`body|weight=3.5`),
  89. true},
  90. {`account.balance < 1000.0`,
  91. newTestEvents(`account|balance=900`),
  92. true},
  93. {`apples.kg <= 4`,
  94. newTestEvents(`apples|kg=4.0`),
  95. true},
  96. {`body.weight >= 4.5`,
  97. newTestEvents(`body|weight=4.5`),
  98. true},
  99. {`oranges.kg < 4 AND watermellons.kg > 10`,
  100. newTestEvents(`oranges|kg=3`, `watermellons|kg=12`),
  101. true},
  102. {`peaches.kg < 4`,
  103. newTestEvents(`peaches|kg=5`),
  104. false},
  105. {`tx.date > DATE 2017-01-01`,
  106. newTestEvents(`tx|date=` + time.Now().Format(syntax.DateFormat)),
  107. true},
  108. {`tx.date = DATE 2017-01-01`,
  109. newTestEvents(`tx|date=` + txDate),
  110. true},
  111. {`tx.date = DATE 2018-01-01`,
  112. newTestEvents(`tx|date=` + txDate),
  113. false},
  114. {`tx.time >= TIME 2013-05-03T14:45:00Z`,
  115. newTestEvents(`tx|time=` + time.Now().Format(syntax.TimeFormat)),
  116. true},
  117. {`tx.time = TIME 2013-05-03T14:45:00Z`,
  118. newTestEvents(`tx|time=` + txTime),
  119. false},
  120. {`abci.owner.name CONTAINS 'Igor'`,
  121. newTestEvents(`abci|owner.name=Igor|owner.name=Ivan`),
  122. true},
  123. {`abci.owner.name CONTAINS 'Igor'`,
  124. newTestEvents(`abci|owner.name=Pavel|owner.name=Ivan`),
  125. false},
  126. {`abci.owner.name = 'Igor'`,
  127. newTestEvents(`abci|owner.name=Igor|owner.name=Ivan`),
  128. true},
  129. {`abci.owner.name = 'Ivan'`,
  130. newTestEvents(`abci|owner.name=Igor|owner.name=Ivan`),
  131. true},
  132. {`abci.owner.name = 'Ivan' AND abci.owner.name = 'Igor'`,
  133. newTestEvents(`abci|owner.name=Igor|owner.name=Ivan`),
  134. true},
  135. {`abci.owner.name = 'Ivan' AND abci.owner.name = 'John'`,
  136. newTestEvents(`abci|owner.name=Igor|owner.name=Ivan`),
  137. false},
  138. {`tm.events.type='NewBlock'`,
  139. newTestEvents(`tm|events.type=NewBlock`, `app|name=fuzzed`),
  140. true},
  141. {`app.name = 'fuzzed'`,
  142. newTestEvents(`tm|events.type=NewBlock`, `app|name=fuzzed`),
  143. true},
  144. {`tm.events.type='NewBlock' AND app.name = 'fuzzed'`,
  145. newTestEvents(`tm|events.type=NewBlock`, `app|name=fuzzed`),
  146. true},
  147. {`tm.events.type='NewHeader' AND app.name = 'fuzzed'`,
  148. newTestEvents(`tm|events.type=NewBlock`, `app|name=fuzzed`),
  149. false},
  150. {`slash EXISTS`,
  151. newTestEvents(`slash|reason=missing_signature|power=6000`),
  152. true},
  153. {`slash EXISTS`,
  154. newTestEvents(`transfer|recipient=cosmos1gu6y2a0ffteesyeyeesk23082c6998xyzmt9mz|sender=cosmos1crje20aj4gxdtyct7z3knxqry2jqt2fuaey6u5`),
  155. false},
  156. {`slash.reason EXISTS AND slash.power > 1000`,
  157. newTestEvents(`slash|reason=missing_signature|power=6000`),
  158. true},
  159. {`slash.reason EXISTS AND slash.power > 1000`,
  160. newTestEvents(`slash|reason=missing_signature|power=500`),
  161. false},
  162. {`slash.reason EXISTS`,
  163. newTestEvents(`transfer|recipient=cosmos1gu6y2a0ffteesyeyeesk23082c6998xyzmt9mz|sender=cosmos1crje20aj4gxdtyct7z3knxqry2jqt2fuaey6u5`),
  164. false},
  165. // Test cases based on the OpenAPI examples.
  166. {`tm.event = 'Tx' AND rewards.withdraw.address = 'AddrA'`,
  167. apiEvents, true},
  168. {`tm.event = 'Tx' AND rewards.withdraw.address = 'AddrA' AND rewards.withdraw.source = 'SrcY'`,
  169. apiEvents, true},
  170. {`tm.event = 'Tx' AND transfer.sender = 'AddrA'`,
  171. apiEvents, false},
  172. {`tm.event = 'Tx' AND transfer.sender = 'AddrC'`,
  173. apiEvents, true},
  174. {`tm.event = 'Tx' AND transfer.sender = 'AddrZ'`,
  175. apiEvents, false},
  176. {`tm.event = 'Tx' AND rewards.withdraw.address = 'AddrZ'`,
  177. apiEvents, false},
  178. {`tm.event = 'Tx' AND rewards.withdraw.source = 'W'`,
  179. apiEvents, false},
  180. }
  181. // NOTE: The original implementation allowed arbitrary prefix matches on
  182. // attribute tags, e.g., "sl" would match "slash".
  183. //
  184. // That is weird and probably wrong: "foo.ba" should not match "foo.bar",
  185. // or there is no way to distinguish the case where there were two values
  186. // for "foo.bar" or one value each for "foo.ba" and "foo.bar".
  187. //
  188. // Apart from a single test case, I could not find any attested usage of
  189. // this implementation detail. It isn't documented in the OpenAPI docs and
  190. // is not shown in any of the example inputs.
  191. //
  192. // On that basis, I removed that test case. This implementation still does
  193. // correctly handle variable type/attribute splits ("x", "y.z" / "x.y", "z")
  194. // since that was required by the original "flattened" event representation.
  195. for i, tc := range testCases {
  196. t.Run(fmt.Sprintf("%02d", i+1), func(t *testing.T) {
  197. c, err := query.New(tc.s)
  198. if err != nil {
  199. t.Fatalf("NewCompiled %#q: unexpected error: %v", tc.s, err)
  200. }
  201. got := c.Matches(tc.events)
  202. if got != tc.matches {
  203. t.Errorf("Query: %#q\nInput: %+v\nMatches: got %v, want %v",
  204. tc.s, tc.events, got, tc.matches)
  205. }
  206. })
  207. }
  208. }
  209. func TestAllMatchesAll(t *testing.T) {
  210. events := newTestEvents(
  211. ``,
  212. `Asher|Roth=`,
  213. `Route|66=`,
  214. `Rilly|Blue=`,
  215. )
  216. for i := 0; i < len(events); i++ {
  217. if !query.All.Matches(events[:i]) {
  218. t.Errorf("Did not match on %+v ", events[:i])
  219. }
  220. }
  221. }
  222. // newTestEvent constructs an Event message from a template string.
  223. // The format is "type|attr1=val1|attr2=val2|...".
  224. func newTestEvent(s string) types.Event {
  225. var event types.Event
  226. parts := strings.Split(s, "|")
  227. event.Type = parts[0]
  228. if len(parts) == 1 {
  229. return event // type only, no attributes
  230. }
  231. for _, kv := range parts[1:] {
  232. key, val := splitKV(kv)
  233. event.Attributes = append(event.Attributes, types.EventAttribute{
  234. Key: key,
  235. Value: val,
  236. })
  237. }
  238. return event
  239. }
  240. // newTestEvents constructs a slice of Event messages by applying newTestEvent
  241. // to each element of ss.
  242. func newTestEvents(ss ...string) []types.Event {
  243. events := make([]types.Event, len(ss))
  244. for i, s := range ss {
  245. events[i] = newTestEvent(s)
  246. }
  247. return events
  248. }
  249. func splitKV(s string) (key, value string) {
  250. kv := strings.SplitN(s, "=", 2)
  251. return kv[0], kv[1]
  252. }