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.

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