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.

400 lines
9.9 KiB

7 years ago
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. "strconv"
  7. "strings"
  8. "time"
  9. "github.com/pkg/errors"
  10. wire "github.com/tendermint/go-wire"
  11. cmn "github.com/tendermint/tmlibs/common"
  12. dbm "github.com/tendermint/tmlibs/db"
  13. "github.com/tendermint/tmlibs/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 := wire.UnmarshalBinary(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 hash
  76. rawBytes, err := wire.MarshalBinary(result)
  77. if err != nil {
  78. return err
  79. }
  80. storeBatch.Set(hash, rawBytes)
  81. }
  82. storeBatch.Write()
  83. return nil
  84. }
  85. // Index indexes a single transaction using the given list of tags.
  86. func (txi *TxIndex) Index(result *types.TxResult) error {
  87. b := txi.store.NewBatch()
  88. hash := result.Tx.Hash()
  89. // index tx by tags
  90. for _, tag := range result.Result.Tags {
  91. if txi.indexAllTags || cmn.StringInSlice(string(tag.Key), txi.tagsToIndex) {
  92. b.Set(keyForTag(tag, result), hash)
  93. }
  94. }
  95. // index tx by hash
  96. rawBytes, err := wire.MarshalBinary(result)
  97. if err != nil {
  98. return err
  99. }
  100. b.Set(hash, rawBytes)
  101. b.Write()
  102. return nil
  103. }
  104. // Search performs a search using the given query. It breaks the query into
  105. // conditions (like "tx.height > 5"). For each condition, it queries the DB
  106. // index. One special use cases here: (1) if "tx.hash" is found, it returns tx
  107. // result for it (2) for range queries it is better for the client to provide
  108. // both lower and upper bounds, so we are not performing a full scan. Results
  109. // from querying indexes are then intersected and returned to the caller.
  110. func (txi *TxIndex) Search(q *query.Query) ([]*types.TxResult, error) {
  111. var hashes [][]byte
  112. var hashesInitialized bool
  113. // get a list of conditions (like "tx.height > 5")
  114. conditions := q.Conditions()
  115. // if there is a hash condition, return the result immediately
  116. hash, err, ok := lookForHash(conditions)
  117. if err != nil {
  118. return nil, errors.Wrap(err, "error during searching for a hash in the query")
  119. } else if ok {
  120. res, err := txi.Get(hash)
  121. if res == nil {
  122. return []*types.TxResult{}, nil
  123. } else {
  124. return []*types.TxResult{res}, errors.Wrap(err, "error while retrieving the result")
  125. }
  126. }
  127. // conditions to skip because they're handled before "everything else"
  128. skipIndexes := make([]int, 0)
  129. // if there is a height condition ("tx.height=3"), extract it for faster lookups
  130. height, heightIndex := lookForHeight(conditions)
  131. if heightIndex >= 0 {
  132. skipIndexes = append(skipIndexes, heightIndex)
  133. }
  134. // extract ranges
  135. // if both upper and lower bounds exist, it's better to get them in order not
  136. // no iterate over kvs that are not within range.
  137. ranges, rangeIndexes := lookForRanges(conditions)
  138. if len(ranges) > 0 {
  139. skipIndexes = append(skipIndexes, rangeIndexes...)
  140. for _, r := range ranges {
  141. if !hashesInitialized {
  142. hashes = txi.matchRange(r, startKeyForRange(r, height))
  143. hashesInitialized = true
  144. } else {
  145. hashes = intersect(hashes, txi.matchRange(r, startKeyForRange(r, height)))
  146. }
  147. }
  148. }
  149. // for all other conditions
  150. for i, c := range conditions {
  151. if cmn.IntInSlice(i, skipIndexes) {
  152. continue
  153. }
  154. if !hashesInitialized {
  155. hashes = txi.match(c, startKey(c, height))
  156. hashesInitialized = true
  157. } else {
  158. hashes = intersect(hashes, txi.match(c, startKey(c, height)))
  159. }
  160. }
  161. results := make([]*types.TxResult, len(hashes))
  162. i := 0
  163. for _, h := range hashes {
  164. results[i], err = txi.Get(h)
  165. if err != nil {
  166. return nil, errors.Wrapf(err, "failed to get Tx{%X}", h)
  167. }
  168. i++
  169. }
  170. return results, nil
  171. }
  172. func lookForHash(conditions []query.Condition) (hash []byte, err error, ok bool) {
  173. for _, c := range conditions {
  174. if c.Tag == types.TxHashKey {
  175. decoded, err := hex.DecodeString(c.Operand.(string))
  176. return decoded, err, true
  177. }
  178. }
  179. return
  180. }
  181. func lookForHeight(conditions []query.Condition) (height int64, index int) {
  182. for i, c := range conditions {
  183. if c.Tag == types.TxHeightKey {
  184. return c.Operand.(int64), i
  185. }
  186. }
  187. return 0, -1
  188. }
  189. // special map to hold range conditions
  190. // Example: account.number => queryRange{lowerBound: 1, upperBound: 5}
  191. type queryRanges map[string]queryRange
  192. type queryRange struct {
  193. key string
  194. lowerBound interface{} // int || time.Time
  195. includeLowerBound bool
  196. upperBound interface{} // int || time.Time
  197. includeUpperBound bool
  198. }
  199. func lookForRanges(conditions []query.Condition) (ranges queryRanges, indexes []int) {
  200. ranges = make(queryRanges)
  201. for i, c := range conditions {
  202. if isRangeOperation(c.Op) {
  203. r, ok := ranges[c.Tag]
  204. if !ok {
  205. r = queryRange{key: c.Tag}
  206. }
  207. switch c.Op {
  208. case query.OpGreater:
  209. r.lowerBound = c.Operand
  210. case query.OpGreaterEqual:
  211. r.includeLowerBound = true
  212. r.lowerBound = c.Operand
  213. case query.OpLess:
  214. r.upperBound = c.Operand
  215. case query.OpLessEqual:
  216. r.includeUpperBound = true
  217. r.upperBound = c.Operand
  218. }
  219. ranges[c.Tag] = r
  220. indexes = append(indexes, i)
  221. }
  222. }
  223. return ranges, indexes
  224. }
  225. func isRangeOperation(op query.Operator) bool {
  226. switch op {
  227. case query.OpGreater, query.OpGreaterEqual, query.OpLess, query.OpLessEqual:
  228. return true
  229. default:
  230. return false
  231. }
  232. }
  233. func (txi *TxIndex) match(c query.Condition, startKey []byte) (hashes [][]byte) {
  234. if c.Op == query.OpEqual {
  235. it := dbm.IteratePrefix(txi.store, startKey)
  236. defer it.Close()
  237. for ; it.Valid(); it.Next() {
  238. hashes = append(hashes, it.Value())
  239. }
  240. } else if c.Op == query.OpContains {
  241. // XXX: doing full scan because startKey does not apply here
  242. // For example, if startKey = "account.owner=an" and search query = "accoutn.owner CONSISTS an"
  243. // we can't iterate with prefix "account.owner=an" because we might miss keys like "account.owner=Ulan"
  244. it := txi.store.Iterator(nil, nil)
  245. defer it.Close()
  246. for ; it.Valid(); it.Next() {
  247. if !isTagKey(it.Key()) {
  248. continue
  249. }
  250. if strings.Contains(extractValueFromKey(it.Key()), c.Operand.(string)) {
  251. hashes = append(hashes, it.Value())
  252. }
  253. }
  254. } else {
  255. panic("other operators should be handled already")
  256. }
  257. return
  258. }
  259. func (txi *TxIndex) matchRange(r queryRange, startKey []byte) (hashes [][]byte) {
  260. it := dbm.IteratePrefix(txi.store, startKey)
  261. defer it.Close()
  262. LOOP:
  263. for ; it.Valid(); it.Next() {
  264. if !isTagKey(it.Key()) {
  265. continue
  266. }
  267. if r.upperBound != nil {
  268. // no other way to stop iterator other than checking for upperBound
  269. switch (r.upperBound).(type) {
  270. case int64:
  271. v, err := strconv.ParseInt(extractValueFromKey(it.Key()), 10, 64)
  272. if err == nil && v == r.upperBound {
  273. if r.includeUpperBound {
  274. hashes = append(hashes, it.Value())
  275. }
  276. break LOOP
  277. }
  278. // XXX: passing time in a ABCI Tags is not yet implemented
  279. // case time.Time:
  280. // v := strconv.ParseInt(extractValueFromKey(it.Key()), 10, 64)
  281. // if v == r.upperBound {
  282. // break
  283. // }
  284. }
  285. }
  286. hashes = append(hashes, it.Value())
  287. }
  288. return
  289. }
  290. ///////////////////////////////////////////////////////////////////////////////
  291. // Keys
  292. func startKey(c query.Condition, height int64) []byte {
  293. var key string
  294. if height > 0 {
  295. key = fmt.Sprintf("%s/%v/%d", c.Tag, c.Operand, height)
  296. } else {
  297. key = fmt.Sprintf("%s/%v", c.Tag, c.Operand)
  298. }
  299. return []byte(key)
  300. }
  301. func startKeyForRange(r queryRange, height int64) []byte {
  302. if r.lowerBound == nil {
  303. return []byte(r.key)
  304. }
  305. var lowerBound interface{}
  306. if r.includeLowerBound {
  307. lowerBound = r.lowerBound
  308. } else {
  309. switch t := r.lowerBound.(type) {
  310. case int64:
  311. lowerBound = t + 1
  312. case time.Time:
  313. lowerBound = t.Unix() + 1
  314. default:
  315. panic("not implemented")
  316. }
  317. }
  318. var key string
  319. if height > 0 {
  320. key = fmt.Sprintf("%s/%v/%d", r.key, lowerBound, height)
  321. } else {
  322. key = fmt.Sprintf("%s/%v", r.key, lowerBound)
  323. }
  324. return []byte(key)
  325. }
  326. func isTagKey(key []byte) bool {
  327. return strings.Count(string(key), tagKeySeparator) == 3
  328. }
  329. func extractValueFromKey(key []byte) string {
  330. parts := strings.SplitN(string(key), tagKeySeparator, 3)
  331. return parts[1]
  332. }
  333. func keyForTag(tag cmn.KVPair, result *types.TxResult) []byte {
  334. return []byte(fmt.Sprintf("%s/%s/%d/%d", tag.Key, tag.Value, result.Height, result.Index))
  335. }
  336. ///////////////////////////////////////////////////////////////////////////////
  337. // Utils
  338. func intersect(as, bs [][]byte) [][]byte {
  339. i := make([][]byte, 0, cmn.MinInt(len(as), len(bs)))
  340. for _, a := range as {
  341. for _, b := range bs {
  342. if bytes.Equal(a, b) {
  343. i = append(i, a)
  344. }
  345. }
  346. }
  347. return i
  348. }