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.

335 lines
10 KiB

7 years ago
7 years ago
7 years ago
  1. package types
  2. import (
  3. "bytes"
  4. "crypto/sha256"
  5. "errors"
  6. "fmt"
  7. "sort"
  8. abci "github.com/tendermint/tendermint/abci/types"
  9. "github.com/tendermint/tendermint/crypto/merkle"
  10. "github.com/tendermint/tendermint/crypto/tmhash"
  11. tmbytes "github.com/tendermint/tendermint/libs/bytes"
  12. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  13. )
  14. // Tx is an arbitrary byte array.
  15. // NOTE: Tx has no types at this level, so when wire encoded it's just length-prefixed.
  16. // Might we want types here ?
  17. type Tx []byte
  18. // Key produces a fixed-length key for use in indexing.
  19. func (tx Tx) Key() TxKey { return sha256.Sum256(tx) }
  20. // Hash computes the TMHASH hash of the wire encoded transaction.
  21. func (tx Tx) Hash() []byte { return tmhash.Sum(tx) }
  22. // String returns the hex-encoded transaction as a string.
  23. func (tx Tx) String() string { return fmt.Sprintf("Tx{%X}", []byte(tx)) }
  24. // Txs is a slice of Tx.
  25. type Txs []Tx
  26. // Hash returns the Merkle root hash of the transaction hashes.
  27. // i.e. the leaves of the tree are the hashes of the txs.
  28. func (txs Txs) Hash() []byte {
  29. hl := txs.hashList()
  30. return merkle.HashFromByteSlices(hl)
  31. }
  32. // Index returns the index of this transaction in the list, or -1 if not found
  33. func (txs Txs) Index(tx Tx) int {
  34. for i := range txs {
  35. if bytes.Equal(txs[i], tx) {
  36. return i
  37. }
  38. }
  39. return -1
  40. }
  41. // IndexByHash returns the index of this transaction hash in the list, or -1 if not found
  42. func (txs Txs) IndexByHash(hash []byte) int {
  43. for i := range txs {
  44. if bytes.Equal(txs[i].Hash(), hash) {
  45. return i
  46. }
  47. }
  48. return -1
  49. }
  50. func (txs Txs) Proof(i int) TxProof {
  51. hl := txs.hashList()
  52. root, proofs := merkle.ProofsFromByteSlices(hl)
  53. return TxProof{
  54. RootHash: root,
  55. Data: txs[i],
  56. Proof: *proofs[i],
  57. }
  58. }
  59. func (txs Txs) hashList() [][]byte {
  60. hl := make([][]byte, len(txs))
  61. for i := 0; i < len(txs); i++ {
  62. hl[i] = txs[i].Hash()
  63. }
  64. return hl
  65. }
  66. // Txs is a slice of transactions. Sorting a Txs value orders the transactions
  67. // lexicographically.
  68. func (txs Txs) Len() int { return len(txs) }
  69. func (txs Txs) Swap(i, j int) { txs[i], txs[j] = txs[j], txs[i] }
  70. func (txs Txs) Less(i, j int) bool {
  71. return bytes.Compare(txs[i], txs[j]) == -1
  72. }
  73. // ToSliceOfBytes converts a Txs to slice of byte slices.
  74. func (txs Txs) ToSliceOfBytes() [][]byte {
  75. txBzs := make([][]byte, len(txs))
  76. for i := 0; i < len(txs); i++ {
  77. txBzs[i] = txs[i]
  78. }
  79. return txBzs
  80. }
  81. // TxRecordSet contains indexes into an underlying set of transactions.
  82. // These indexes are useful for validating and working with a list of TxRecords
  83. // from the PrepareProposal response.
  84. //
  85. // Only one copy of the original data is referenced by all of the indexes but a
  86. // transaction may appear in multiple indexes.
  87. type TxRecordSet struct {
  88. // all holds the complete list of all transactions from the original list of
  89. // TxRecords.
  90. all Txs
  91. // included is an index of the transactions that will be included in the block
  92. // and is constructed from the list of both added and unmodified transactions.
  93. // included maintains the original order that the transactions were present
  94. // in the list of TxRecords.
  95. included Txs
  96. // added, unmodified, removed, and unknown are indexes for each of the actions
  97. // that may be supplied with a transaction.
  98. //
  99. // Because each transaction only has one action, it can be referenced by
  100. // at most 3 indexes in this data structure: the action-specific index, the
  101. // included index, and the all index.
  102. added Txs
  103. unmodified Txs
  104. removed Txs
  105. unknown Txs
  106. }
  107. // NewTxRecordSet constructs a new set from the given transaction records.
  108. // The contents of the input transactions are shared by the set, and must not
  109. // be modified during the lifetime of the set.
  110. func NewTxRecordSet(trs []*abci.TxRecord) TxRecordSet {
  111. txrSet := TxRecordSet{
  112. all: make([]Tx, len(trs)),
  113. }
  114. for i, tr := range trs {
  115. txrSet.all[i] = Tx(tr.Tx)
  116. // The following set of assignments do not allocate new []byte, they create
  117. // pointers to the already allocated slice.
  118. switch tr.GetAction() {
  119. case abci.TxRecord_UNKNOWN:
  120. txrSet.unknown = append(txrSet.unknown, txrSet.all[i])
  121. case abci.TxRecord_UNMODIFIED:
  122. txrSet.unmodified = append(txrSet.unmodified, txrSet.all[i])
  123. txrSet.included = append(txrSet.included, txrSet.all[i])
  124. case abci.TxRecord_ADDED:
  125. txrSet.added = append(txrSet.added, txrSet.all[i])
  126. txrSet.included = append(txrSet.included, txrSet.all[i])
  127. case abci.TxRecord_REMOVED:
  128. txrSet.removed = append(txrSet.removed, txrSet.all[i])
  129. }
  130. }
  131. return txrSet
  132. }
  133. // IncludedTxs returns the transactions marked for inclusion in a block. This
  134. // list maintains the order that the transactions were included in the list of
  135. // TxRecords that were used to construct the TxRecordSet.
  136. func (t TxRecordSet) IncludedTxs() []Tx {
  137. return t.included
  138. }
  139. // RemovedTxs returns the transactions marked for removal by the application.
  140. func (t TxRecordSet) RemovedTxs() []Tx {
  141. return t.removed
  142. }
  143. // Validate checks that the record set was correctly constructed from the original
  144. // list of transactions.
  145. func (t TxRecordSet) Validate(maxSizeBytes int64, otxs Txs) error {
  146. if len(t.unknown) > 0 {
  147. return fmt.Errorf("%d transactions marked unknown (first unknown hash: %x)", len(t.unknown), t.unknown[0].Hash())
  148. }
  149. // The following validation logic performs a set of sorts on the data in the TxRecordSet indexes.
  150. // It sorts the original transaction list, otxs, once.
  151. // It sorts the new transaction list twice: once when sorting 'all', the total list,
  152. // and once by sorting the set of the added, removed, and unmodified transactions indexes,
  153. // which, when combined, comprise the complete list of modified transactions.
  154. //
  155. // Each of the added, removed, and unmodified indices is then iterated and once
  156. // and each value index is checked against the sorted original list for containment.
  157. // Asymptotically, this yields a total runtime of O(N*log(N) + 2*M*log(M) + M*log(N)).
  158. // in the input size of the original list, N, and the input size of the new list, M, respectively.
  159. // Performance gains are likely possible, but this was preferred for readability and maintainability.
  160. // Sort a copy of the complete transaction slice so we can check for
  161. // duplication. The copy is so we do not change the original ordering.
  162. // Only the slices are copied, the transaction contents are shared.
  163. allCopy := sortedCopy(t.all)
  164. var size int64
  165. for i, cur := range allCopy {
  166. size += int64(len(cur))
  167. if size > maxSizeBytes {
  168. return fmt.Errorf("transaction data size %d exceeds maximum %d", size, maxSizeBytes)
  169. }
  170. // allCopy is sorted, so any duplicated data will be adjacent.
  171. if i+1 < len(allCopy) && bytes.Equal(cur, allCopy[i+1]) {
  172. return fmt.Errorf("found duplicate transaction with hash: %x", cur.Hash())
  173. }
  174. }
  175. // create copies of each of the action-specific indexes so that order of the original
  176. // indexes can be preserved.
  177. addedCopy := sortedCopy(t.added)
  178. removedCopy := sortedCopy(t.removed)
  179. unmodifiedCopy := sortedCopy(t.unmodified)
  180. // make a defensive copy of otxs so that the order of
  181. // the caller's data is not altered.
  182. otxsCopy := sortedCopy(otxs)
  183. if ix, ok := containsAll(otxsCopy, unmodifiedCopy); !ok {
  184. return fmt.Errorf("new transaction incorrectly marked as removed, transaction hash: %x", unmodifiedCopy[ix].Hash())
  185. }
  186. if ix, ok := containsAll(otxsCopy, removedCopy); !ok {
  187. return fmt.Errorf("new transaction incorrectly marked as removed, transaction hash: %x", removedCopy[ix].Hash())
  188. }
  189. if ix, ok := containsAny(otxsCopy, addedCopy); ok {
  190. return fmt.Errorf("existing transaction incorrectly marked as added, transaction hash: %x", addedCopy[ix].Hash())
  191. }
  192. return nil
  193. }
  194. func sortedCopy(txs Txs) Txs {
  195. cp := make(Txs, len(txs))
  196. copy(cp, txs)
  197. sort.Sort(cp)
  198. return cp
  199. }
  200. // containsAny checks that list a contains one of the transactions in list
  201. // b. If a match is found, the index in b of the matching transaction is returned.
  202. // Both lists must be sorted.
  203. func containsAny(a, b []Tx) (int, bool) {
  204. for i, cur := range b {
  205. if _, ok := contains(a, cur); ok {
  206. return i, true
  207. }
  208. }
  209. return -1, false
  210. }
  211. // containsAll checks that super contains all of the transactions in the sub
  212. // list. If not all values in sub are present in super, the index in sub of the
  213. // first Tx absent from super is returned.
  214. func containsAll(super, sub Txs) (int, bool) {
  215. for i, cur := range sub {
  216. if _, ok := contains(super, cur); !ok {
  217. return i, false
  218. }
  219. }
  220. return -1, true
  221. }
  222. // contains checks that the sorted list, set contains elem. If set does contain elem, then the
  223. // index in set of elem is returned.
  224. func contains(set []Tx, elem Tx) (int, bool) {
  225. n := sort.Search(len(set), func(i int) bool {
  226. return bytes.Compare(elem, set[i]) <= 0
  227. })
  228. if n == len(set) || !bytes.Equal(elem, set[n]) {
  229. return -1, false
  230. }
  231. return n, true
  232. }
  233. // TxProof represents a Merkle proof of the presence of a transaction in the Merkle tree.
  234. type TxProof struct {
  235. RootHash tmbytes.HexBytes `json:"root_hash"`
  236. Data Tx `json:"data"`
  237. Proof merkle.Proof `json:"proof"`
  238. }
  239. // Leaf returns the hash(tx), which is the leaf in the merkle tree which this proof refers to.
  240. func (tp TxProof) Leaf() []byte {
  241. return tp.Data.Hash()
  242. }
  243. // Validate verifies the proof. It returns nil if the RootHash matches the dataHash argument,
  244. // and if the proof is internally consistent. Otherwise, it returns a sensible error.
  245. func (tp TxProof) Validate(dataHash []byte) error {
  246. if !bytes.Equal(dataHash, tp.RootHash) {
  247. return errors.New("proof matches different data hash")
  248. }
  249. if tp.Proof.Index < 0 {
  250. return errors.New("proof index cannot be negative")
  251. }
  252. if tp.Proof.Total <= 0 {
  253. return errors.New("proof total must be positive")
  254. }
  255. valid := tp.Proof.Verify(tp.RootHash, tp.Leaf())
  256. if valid != nil {
  257. return errors.New("proof is not internally consistent")
  258. }
  259. return nil
  260. }
  261. func (tp TxProof) ToProto() tmproto.TxProof {
  262. pbProof := tp.Proof.ToProto()
  263. pbtp := tmproto.TxProof{
  264. RootHash: tp.RootHash,
  265. Data: tp.Data,
  266. Proof: pbProof,
  267. }
  268. return pbtp
  269. }
  270. func TxProofFromProto(pb tmproto.TxProof) (TxProof, error) {
  271. pbProof, err := merkle.ProofFromProto(pb.Proof)
  272. if err != nil {
  273. return TxProof{}, err
  274. }
  275. pbtp := TxProof{
  276. RootHash: pb.RootHash,
  277. Data: pb.Data,
  278. Proof: *pbProof,
  279. }
  280. return pbtp, nil
  281. }
  282. // ComputeProtoSizeForTxs wraps the transactions in tmproto.Data{} and calculates the size.
  283. // https://developers.google.com/protocol-buffers/docs/encoding
  284. func ComputeProtoSizeForTxs(txs []Tx) int64 {
  285. data := Data{Txs: txs}
  286. pdData := data.ToProto()
  287. return int64(pdData.Size())
  288. }