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.

452 lines
11 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package kv
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "fmt"
  6. "sort"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/pkg/errors"
  11. cmn "github.com/tendermint/tendermint/libs/common"
  12. dbm "github.com/tendermint/tendermint/libs/db"
  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. tagsToIndex []string
  25. indexAllTags bool
  26. }
  27. // NewTxIndex creates new KV indexer.
  28. func NewTxIndex(store dbm.DB, options ...func(*TxIndex)) *TxIndex {
  29. txi := &TxIndex{store: store, tagsToIndex: make([]string, 0), indexAllTags: false}
  30. for _, o := range options {
  31. o(txi)
  32. }
  33. return txi
  34. }
  35. // IndexTags is an option for setting which tags to index.
  36. func IndexTags(tags []string) func(*TxIndex) {
  37. return func(txi *TxIndex) {
  38. txi.tagsToIndex = tags
  39. }
  40. }
  41. // IndexAllTags is an option for indexing all tags.
  42. func IndexAllTags() func(*TxIndex) {
  43. return func(txi *TxIndex) {
  44. txi.indexAllTags = true
  45. }
  46. }
  47. // Get gets transaction from the TxIndex storage and returns it or nil if the
  48. // transaction is not found.
  49. func (txi *TxIndex) Get(hash []byte) (*types.TxResult, error) {
  50. if len(hash) == 0 {
  51. return nil, txindex.ErrorEmptyHash
  52. }
  53. rawBytes := txi.store.Get(hash)
  54. if rawBytes == nil {
  55. return nil, nil
  56. }
  57. txResult := new(types.TxResult)
  58. err := cdc.UnmarshalBinaryBare(rawBytes, &txResult)
  59. if err != nil {
  60. return nil, fmt.Errorf("Error reading TxResult: %v", err)
  61. }
  62. return txResult, nil
  63. }
  64. // AddBatch indexes a batch of transactions using the given list of tags.
  65. func (txi *TxIndex) AddBatch(b *txindex.Batch) error {
  66. storeBatch := txi.store.NewBatch()
  67. for _, result := range b.Ops {
  68. hash := result.Tx.Hash()
  69. // index tx by tags
  70. for _, tag := range result.Result.Tags {
  71. if txi.indexAllTags || cmn.StringInSlice(string(tag.Key), txi.tagsToIndex) {
  72. storeBatch.Set(keyForTag(tag, result), hash)
  73. }
  74. }
  75. // index tx by height
  76. if txi.indexAllTags || cmn.StringInSlice(types.TxHeightKey, txi.tagsToIndex) {
  77. storeBatch.Set(keyForHeight(result), hash)
  78. }
  79. // index tx by hash
  80. rawBytes, err := cdc.MarshalBinaryBare(result)
  81. if err != nil {
  82. return err
  83. }
  84. storeBatch.Set(hash, rawBytes)
  85. }
  86. storeBatch.Write()
  87. return nil
  88. }
  89. // Index indexes a single transaction using the given list of tags.
  90. func (txi *TxIndex) Index(result *types.TxResult) error {
  91. b := txi.store.NewBatch()
  92. hash := result.Tx.Hash()
  93. // index tx by tags
  94. for _, tag := range result.Result.Tags {
  95. if txi.indexAllTags || cmn.StringInSlice(string(tag.Key), txi.tagsToIndex) {
  96. b.Set(keyForTag(tag, result), hash)
  97. }
  98. }
  99. // index tx by height
  100. if txi.indexAllTags || cmn.StringInSlice(types.TxHeightKey, txi.tagsToIndex) {
  101. b.Set(keyForHeight(result), hash)
  102. }
  103. // index tx by hash
  104. rawBytes, err := cdc.MarshalBinaryBare(result)
  105. if err != nil {
  106. return err
  107. }
  108. b.Set(hash, rawBytes)
  109. b.Write()
  110. return nil
  111. }
  112. // Search performs a search using the given query. It breaks the query into
  113. // conditions (like "tx.height > 5"). For each condition, it queries the DB
  114. // index. One special use cases here: (1) if "tx.hash" is found, it returns tx
  115. // result for it (2) for range queries it is better for the client to provide
  116. // both lower and upper bounds, so we are not performing a full scan. Results
  117. // from querying indexes are then intersected and returned to the caller.
  118. func (txi *TxIndex) Search(q *query.Query) ([]*types.TxResult, error) {
  119. var hashes [][]byte
  120. var hashesInitialized bool
  121. // get a list of conditions (like "tx.height > 5")
  122. conditions := q.Conditions()
  123. // if there is a hash condition, return the result immediately
  124. hash, err, ok := lookForHash(conditions)
  125. if err != nil {
  126. return nil, errors.Wrap(err, "error during searching for a hash in the query")
  127. } else if ok {
  128. res, err := txi.Get(hash)
  129. if res == nil {
  130. return []*types.TxResult{}, nil
  131. }
  132. return []*types.TxResult{res}, errors.Wrap(err, "error while retrieving the result")
  133. }
  134. // conditions to skip because they're handled before "everything else"
  135. skipIndexes := make([]int, 0)
  136. // extract ranges
  137. // if both upper and lower bounds exist, it's better to get them in order not
  138. // no iterate over kvs that are not within range.
  139. ranges, rangeIndexes := lookForRanges(conditions)
  140. if len(ranges) > 0 {
  141. skipIndexes = append(skipIndexes, rangeIndexes...)
  142. for _, r := range ranges {
  143. if !hashesInitialized {
  144. hashes = txi.matchRange(r, []byte(r.key))
  145. hashesInitialized = true
  146. } else {
  147. hashes = intersect(hashes, txi.matchRange(r, []byte(r.key)))
  148. }
  149. }
  150. }
  151. // if there is a height condition ("tx.height=3"), extract it
  152. height := lookForHeight(conditions)
  153. // for all other conditions
  154. for i, c := range conditions {
  155. if cmn.IntInSlice(i, skipIndexes) {
  156. continue
  157. }
  158. if !hashesInitialized {
  159. hashes = txi.match(c, startKey(c, height))
  160. hashesInitialized = true
  161. } else {
  162. hashes = intersect(hashes, txi.match(c, startKey(c, height)))
  163. }
  164. }
  165. results := make([]*types.TxResult, len(hashes))
  166. i := 0
  167. for _, h := range hashes {
  168. results[i], err = txi.Get(h)
  169. if err != nil {
  170. return nil, errors.Wrapf(err, "failed to get Tx{%X}", h)
  171. }
  172. i++
  173. }
  174. // sort by height & index by default
  175. sort.Slice(results, func(i, j int) bool {
  176. if results[i].Height == results[j].Height {
  177. return results[i].Index < results[j].Index
  178. }
  179. return results[i].Height < results[j].Height
  180. })
  181. return results, nil
  182. }
  183. func lookForHash(conditions []query.Condition) (hash []byte, err error, ok bool) {
  184. for _, c := range conditions {
  185. if c.Tag == types.TxHashKey {
  186. decoded, err := hex.DecodeString(c.Operand.(string))
  187. return decoded, err, true
  188. }
  189. }
  190. return
  191. }
  192. // lookForHeight returns a height if there is an "height=X" condition.
  193. func lookForHeight(conditions []query.Condition) (height int64) {
  194. for _, c := range conditions {
  195. if c.Tag == types.TxHeightKey && c.Op == query.OpEqual {
  196. return c.Operand.(int64)
  197. }
  198. }
  199. return 0
  200. }
  201. // special map to hold range conditions
  202. // Example: account.number => queryRange{lowerBound: 1, upperBound: 5}
  203. type queryRanges map[string]queryRange
  204. type queryRange struct {
  205. key string
  206. lowerBound interface{} // int || time.Time
  207. includeLowerBound bool
  208. upperBound interface{} // int || time.Time
  209. includeUpperBound bool
  210. }
  211. func (r queryRange) lowerBoundValue() interface{} {
  212. if r.lowerBound == nil {
  213. return nil
  214. }
  215. if r.includeLowerBound {
  216. return r.lowerBound
  217. } else {
  218. switch t := r.lowerBound.(type) {
  219. case int64:
  220. return t + 1
  221. case time.Time:
  222. return t.Unix() + 1
  223. default:
  224. panic("not implemented")
  225. }
  226. }
  227. }
  228. func (r queryRange) AnyBound() interface{} {
  229. if r.lowerBound != nil {
  230. return r.lowerBound
  231. } else {
  232. return r.upperBound
  233. }
  234. }
  235. func (r queryRange) upperBoundValue() interface{} {
  236. if r.upperBound == nil {
  237. return nil
  238. }
  239. if r.includeUpperBound {
  240. return r.upperBound
  241. } else {
  242. switch t := r.upperBound.(type) {
  243. case int64:
  244. return t - 1
  245. case time.Time:
  246. return t.Unix() - 1
  247. default:
  248. panic("not implemented")
  249. }
  250. }
  251. }
  252. func lookForRanges(conditions []query.Condition) (ranges queryRanges, indexes []int) {
  253. ranges = make(queryRanges)
  254. for i, c := range conditions {
  255. if isRangeOperation(c.Op) {
  256. r, ok := ranges[c.Tag]
  257. if !ok {
  258. r = queryRange{key: c.Tag}
  259. }
  260. switch c.Op {
  261. case query.OpGreater:
  262. r.lowerBound = c.Operand
  263. case query.OpGreaterEqual:
  264. r.includeLowerBound = true
  265. r.lowerBound = c.Operand
  266. case query.OpLess:
  267. r.upperBound = c.Operand
  268. case query.OpLessEqual:
  269. r.includeUpperBound = true
  270. r.upperBound = c.Operand
  271. }
  272. ranges[c.Tag] = r
  273. indexes = append(indexes, i)
  274. }
  275. }
  276. return ranges, indexes
  277. }
  278. func isRangeOperation(op query.Operator) bool {
  279. switch op {
  280. case query.OpGreater, query.OpGreaterEqual, query.OpLess, query.OpLessEqual:
  281. return true
  282. default:
  283. return false
  284. }
  285. }
  286. func (txi *TxIndex) match(c query.Condition, startKey []byte) (hashes [][]byte) {
  287. if c.Op == query.OpEqual {
  288. it := dbm.IteratePrefix(txi.store, startKey)
  289. defer it.Close()
  290. for ; it.Valid(); it.Next() {
  291. hashes = append(hashes, it.Value())
  292. }
  293. } else if c.Op == query.OpContains {
  294. // XXX: doing full scan because startKey does not apply here
  295. // For example, if startKey = "account.owner=an" and search query = "accoutn.owner CONSISTS an"
  296. // we can't iterate with prefix "account.owner=an" because we might miss keys like "account.owner=Ulan"
  297. it := txi.store.Iterator(nil, nil)
  298. defer it.Close()
  299. for ; it.Valid(); it.Next() {
  300. if !isTagKey(it.Key()) {
  301. continue
  302. }
  303. if strings.Contains(extractValueFromKey(it.Key()), c.Operand.(string)) {
  304. hashes = append(hashes, it.Value())
  305. }
  306. }
  307. } else {
  308. panic("other operators should be handled already")
  309. }
  310. return
  311. }
  312. func (txi *TxIndex) matchRange(r queryRange, prefix []byte) (hashes [][]byte) {
  313. // create a map to prevent duplicates
  314. hashesMap := make(map[string][]byte)
  315. lowerBound := r.lowerBoundValue()
  316. upperBound := r.upperBoundValue()
  317. it := dbm.IteratePrefix(txi.store, prefix)
  318. defer it.Close()
  319. LOOP:
  320. for ; it.Valid(); it.Next() {
  321. if !isTagKey(it.Key()) {
  322. continue
  323. }
  324. switch r.AnyBound().(type) {
  325. case int64:
  326. v, err := strconv.ParseInt(extractValueFromKey(it.Key()), 10, 64)
  327. if err != nil {
  328. continue LOOP
  329. }
  330. include := true
  331. if lowerBound != nil && v < lowerBound.(int64) {
  332. include = false
  333. }
  334. if upperBound != nil && v > upperBound.(int64) {
  335. include = false
  336. }
  337. if include {
  338. hashesMap[fmt.Sprintf("%X", it.Value())] = it.Value()
  339. }
  340. // XXX: passing time in a ABCI Tags is not yet implemented
  341. // case time.Time:
  342. // v := strconv.ParseInt(extractValueFromKey(it.Key()), 10, 64)
  343. // if v == r.upperBound {
  344. // break
  345. // }
  346. }
  347. }
  348. hashes = make([][]byte, len(hashesMap))
  349. i := 0
  350. for _, h := range hashesMap {
  351. hashes[i] = h
  352. i++
  353. }
  354. return
  355. }
  356. ///////////////////////////////////////////////////////////////////////////////
  357. // Keys
  358. func startKey(c query.Condition, height int64) []byte {
  359. var key string
  360. if height > 0 {
  361. key = fmt.Sprintf("%s/%v/%d/", c.Tag, c.Operand, height)
  362. } else {
  363. key = fmt.Sprintf("%s/%v/", c.Tag, c.Operand)
  364. }
  365. return []byte(key)
  366. }
  367. func isTagKey(key []byte) bool {
  368. return strings.Count(string(key), tagKeySeparator) == 3
  369. }
  370. func extractValueFromKey(key []byte) string {
  371. parts := strings.SplitN(string(key), tagKeySeparator, 3)
  372. return parts[1]
  373. }
  374. func keyForTag(tag cmn.KVPair, result *types.TxResult) []byte {
  375. return []byte(fmt.Sprintf("%s/%s/%d/%d", tag.Key, tag.Value, result.Height, result.Index))
  376. }
  377. func keyForHeight(result *types.TxResult) []byte {
  378. return []byte(fmt.Sprintf("%s/%d/%d/%d", types.TxHeightKey, result.Height, result.Height, result.Index))
  379. }
  380. ///////////////////////////////////////////////////////////////////////////////
  381. // Utils
  382. func intersect(as, bs [][]byte) [][]byte {
  383. i := make([][]byte, 0, cmn.MinInt(len(as), len(bs)))
  384. for _, a := range as {
  385. for _, b := range bs {
  386. if bytes.Equal(a, b) {
  387. i = append(i, a)
  388. }
  389. }
  390. }
  391. return i
  392. }