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.

340 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. // AddedTxs returns the transactions added by the application.
  140. func (t TxRecordSet) AddedTxs() []Tx {
  141. return t.added
  142. }
  143. // RemovedTxs returns the transactions marked for removal by the application.
  144. func (t TxRecordSet) RemovedTxs() []Tx {
  145. return t.removed
  146. }
  147. // Validate checks that the record set was correctly constructed from the original
  148. // list of transactions.
  149. func (t TxRecordSet) Validate(maxSizeBytes int64, otxs Txs) error {
  150. if len(t.unknown) > 0 {
  151. return fmt.Errorf("%d transactions marked unknown (first unknown hash: %x)", len(t.unknown), t.unknown[0].Hash())
  152. }
  153. // The following validation logic performs a set of sorts on the data in the TxRecordSet indexes.
  154. // It sorts the original transaction list, otxs, once.
  155. // It sorts the new transaction list twice: once when sorting 'all', the total list,
  156. // and once by sorting the set of the added, removed, and unmodified transactions indexes,
  157. // which, when combined, comprise the complete list of modified transactions.
  158. //
  159. // Each of the added, removed, and unmodified indices is then iterated and once
  160. // and each value index is checked against the sorted original list for containment.
  161. // Asymptotically, this yields a total runtime of O(N*log(N) + 2*M*log(M) + M*log(N)).
  162. // in the input size of the original list, N, and the input size of the new list, M, respectively.
  163. // Performance gains are likely possible, but this was preferred for readability and maintainability.
  164. // Sort a copy of the complete transaction slice so we can check for
  165. // duplication. The copy is so we do not change the original ordering.
  166. // Only the slices are copied, the transaction contents are shared.
  167. allCopy := sortedCopy(t.all)
  168. var size int64
  169. for i, cur := range allCopy {
  170. size += int64(len(cur))
  171. if size > maxSizeBytes {
  172. return fmt.Errorf("transaction data size %d exceeds maximum %d", size, maxSizeBytes)
  173. }
  174. // allCopy is sorted, so any duplicated data will be adjacent.
  175. if i+1 < len(allCopy) && bytes.Equal(cur, allCopy[i+1]) {
  176. return fmt.Errorf("found duplicate transaction with hash: %x", cur.Hash())
  177. }
  178. }
  179. // create copies of each of the action-specific indexes so that order of the original
  180. // indexes can be preserved.
  181. addedCopy := sortedCopy(t.added)
  182. removedCopy := sortedCopy(t.removed)
  183. unmodifiedCopy := sortedCopy(t.unmodified)
  184. // make a defensive copy of otxs so that the order of
  185. // the caller's data is not altered.
  186. otxsCopy := sortedCopy(otxs)
  187. if ix, ok := containsAll(otxsCopy, unmodifiedCopy); !ok {
  188. return fmt.Errorf("new transaction incorrectly marked as removed, transaction hash: %x", unmodifiedCopy[ix].Hash())
  189. }
  190. if ix, ok := containsAll(otxsCopy, removedCopy); !ok {
  191. return fmt.Errorf("new transaction incorrectly marked as removed, transaction hash: %x", removedCopy[ix].Hash())
  192. }
  193. if ix, ok := containsAny(otxsCopy, addedCopy); ok {
  194. return fmt.Errorf("existing transaction incorrectly marked as added, transaction hash: %x", addedCopy[ix].Hash())
  195. }
  196. return nil
  197. }
  198. func sortedCopy(txs Txs) Txs {
  199. cp := make(Txs, len(txs))
  200. copy(cp, txs)
  201. sort.Sort(cp)
  202. return cp
  203. }
  204. // containsAny checks that list a contains one of the transactions in list
  205. // b. If a match is found, the index in b of the matching transaction is returned.
  206. // Both lists must be sorted.
  207. func containsAny(a, b []Tx) (int, bool) {
  208. for i, cur := range b {
  209. if _, ok := contains(a, cur); ok {
  210. return i, true
  211. }
  212. }
  213. return -1, false
  214. }
  215. // containsAll checks that super contains all of the transactions in the sub
  216. // list. If not all values in sub are present in super, the index in sub of the
  217. // first Tx absent from super is returned.
  218. func containsAll(super, sub Txs) (int, bool) {
  219. for i, cur := range sub {
  220. if _, ok := contains(super, cur); !ok {
  221. return i, false
  222. }
  223. }
  224. return -1, true
  225. }
  226. // contains checks that the sorted list, set contains elem. If set does contain elem, then the
  227. // index in set of elem is returned.
  228. func contains(set []Tx, elem Tx) (int, bool) {
  229. n := sort.Search(len(set), func(i int) bool {
  230. return bytes.Compare(elem, set[i]) <= 0
  231. })
  232. if n == len(set) || !bytes.Equal(elem, set[n]) {
  233. return -1, false
  234. }
  235. return n, true
  236. }
  237. // TxProof represents a Merkle proof of the presence of a transaction in the Merkle tree.
  238. type TxProof struct {
  239. RootHash tmbytes.HexBytes `json:"root_hash"`
  240. Data Tx `json:"data"`
  241. Proof merkle.Proof `json:"proof"`
  242. }
  243. // Leaf returns the hash(tx), which is the leaf in the merkle tree which this proof refers to.
  244. func (tp TxProof) Leaf() []byte {
  245. return tp.Data.Hash()
  246. }
  247. // Validate verifies the proof. It returns nil if the RootHash matches the dataHash argument,
  248. // and if the proof is internally consistent. Otherwise, it returns a sensible error.
  249. func (tp TxProof) Validate(dataHash []byte) error {
  250. if !bytes.Equal(dataHash, tp.RootHash) {
  251. return errors.New("proof matches different data hash")
  252. }
  253. if tp.Proof.Index < 0 {
  254. return errors.New("proof index cannot be negative")
  255. }
  256. if tp.Proof.Total <= 0 {
  257. return errors.New("proof total must be positive")
  258. }
  259. valid := tp.Proof.Verify(tp.RootHash, tp.Leaf())
  260. if valid != nil {
  261. return errors.New("proof is not internally consistent")
  262. }
  263. return nil
  264. }
  265. func (tp TxProof) ToProto() tmproto.TxProof {
  266. pbProof := tp.Proof.ToProto()
  267. pbtp := tmproto.TxProof{
  268. RootHash: tp.RootHash,
  269. Data: tp.Data,
  270. Proof: pbProof,
  271. }
  272. return pbtp
  273. }
  274. func TxProofFromProto(pb tmproto.TxProof) (TxProof, error) {
  275. pbProof, err := merkle.ProofFromProto(pb.Proof)
  276. if err != nil {
  277. return TxProof{}, err
  278. }
  279. pbtp := TxProof{
  280. RootHash: pb.RootHash,
  281. Data: pb.Data,
  282. Proof: *pbProof,
  283. }
  284. return pbtp, nil
  285. }
  286. // ComputeProtoSizeForTxs wraps the transactions in tmproto.Data{} and calculates the size.
  287. // https://developers.google.com/protocol-buffers/docs/encoding
  288. func ComputeProtoSizeForTxs(txs []Tx) int64 {
  289. data := Data{Txs: txs}
  290. pdData := data.ToProto()
  291. return int64(pdData.Size())
  292. }