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.

58 lines
1.3 KiB

  1. package kv
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/tendermint/go-wire"
  6. db "github.com/tendermint/tmlibs/db"
  7. "github.com/tendermint/tendermint/state/txindex"
  8. "github.com/tendermint/tendermint/types"
  9. )
  10. // TxIndex is the simplest possible indexer, backed by Key-Value storage (levelDB).
  11. // It can only index transaction by its identifier.
  12. type TxIndex struct {
  13. store db.DB
  14. }
  15. // NewTxIndex returns new instance of TxIndex.
  16. func NewTxIndex(store db.DB) *TxIndex {
  17. return &TxIndex{store: store}
  18. }
  19. // Get gets transaction from the TxIndex storage and returns it or nil if the
  20. // transaction is not found.
  21. func (txi *TxIndex) Get(hash []byte) (*types.TxResult, error) {
  22. if len(hash) == 0 {
  23. return nil, txindex.ErrorEmptyHash
  24. }
  25. rawBytes := txi.store.Get(hash)
  26. if rawBytes == nil {
  27. return nil, nil
  28. }
  29. r := bytes.NewReader(rawBytes)
  30. var n int
  31. var err error
  32. txResult := wire.ReadBinary(&types.TxResult{}, r, 0, &n, &err).(*types.TxResult)
  33. if err != nil {
  34. return nil, fmt.Errorf("Error reading TxResult: %v", err)
  35. }
  36. return txResult, nil
  37. }
  38. // AddBatch writes a batch of transactions into the TxIndex storage.
  39. func (txi *TxIndex) AddBatch(b *txindex.Batch) error {
  40. storeBatch := txi.store.NewBatch()
  41. for _, result := range b.Ops {
  42. rawBytes := wire.BinaryBytes(&result)
  43. storeBatch.Set(result.Tx.Hash(), rawBytes)
  44. }
  45. storeBatch.Write()
  46. return nil
  47. }