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.

722 lines
20 KiB

max-bytes PR follow-up (#2318) * ReapMaxTxs: return all txs if max is negative this mirrors ReapMaxBytes behavior See https://github.com/tendermint/tendermint/pull/2184#discussion_r214439950 * increase MaxAminoOverheadForBlock tested with: ``` func TestMaxAminoOverheadForBlock(t *testing.T) { maxChainID := "" for i := 0; i < MaxChainIDLen; i++ { maxChainID += "𠜎" } h := Header{ ChainID: maxChainID, Height: 10, Time: time.Now().UTC(), NumTxs: 100, TotalTxs: 200, LastBlockID: makeBlockID(make([]byte, 20), 300, make([]byte, 20)), LastCommitHash: tmhash.Sum([]byte("last_commit_hash")), DataHash: tmhash.Sum([]byte("data_hash")), ValidatorsHash: tmhash.Sum([]byte("validators_hash")), NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")), ConsensusHash: tmhash.Sum([]byte("consensus_hash")), AppHash: tmhash.Sum([]byte("app_hash")), LastResultsHash: tmhash.Sum([]byte("last_results_hash")), EvidenceHash: tmhash.Sum([]byte("evidence_hash")), ProposerAddress: tmhash.Sum([]byte("proposer_address")), } b := Block{ Header: h, Data: Data{Txs: makeTxs(10000, 100)}, Evidence: EvidenceData{}, LastCommit: &Commit{}, } bz, err := cdc.MarshalBinary(b) require.NoError(t, err) assert.Equal(t, MaxHeaderBytes+MaxAminoOverheadForBlock-2, len(bz)-1000000-20000-1) } ``` * fix MaxYYY constants calculation by using math.MaxInt64 See https://github.com/tendermint/tendermint/pull/2184#discussion_r214444244 * pass mempool filter as an option See https://github.com/tendermint/tendermint/pull/2184#discussion_r214445869 * fixes after Dev's comments
6 years ago
max-bytes PR follow-up (#2318) * ReapMaxTxs: return all txs if max is negative this mirrors ReapMaxBytes behavior See https://github.com/tendermint/tendermint/pull/2184#discussion_r214439950 * increase MaxAminoOverheadForBlock tested with: ``` func TestMaxAminoOverheadForBlock(t *testing.T) { maxChainID := "" for i := 0; i < MaxChainIDLen; i++ { maxChainID += "𠜎" } h := Header{ ChainID: maxChainID, Height: 10, Time: time.Now().UTC(), NumTxs: 100, TotalTxs: 200, LastBlockID: makeBlockID(make([]byte, 20), 300, make([]byte, 20)), LastCommitHash: tmhash.Sum([]byte("last_commit_hash")), DataHash: tmhash.Sum([]byte("data_hash")), ValidatorsHash: tmhash.Sum([]byte("validators_hash")), NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")), ConsensusHash: tmhash.Sum([]byte("consensus_hash")), AppHash: tmhash.Sum([]byte("app_hash")), LastResultsHash: tmhash.Sum([]byte("last_results_hash")), EvidenceHash: tmhash.Sum([]byte("evidence_hash")), ProposerAddress: tmhash.Sum([]byte("proposer_address")), } b := Block{ Header: h, Data: Data{Txs: makeTxs(10000, 100)}, Evidence: EvidenceData{}, LastCommit: &Commit{}, } bz, err := cdc.MarshalBinary(b) require.NoError(t, err) assert.Equal(t, MaxHeaderBytes+MaxAminoOverheadForBlock-2, len(bz)-1000000-20000-1) } ``` * fix MaxYYY constants calculation by using math.MaxInt64 See https://github.com/tendermint/tendermint/pull/2184#discussion_r214444244 * pass mempool filter as an option See https://github.com/tendermint/tendermint/pull/2184#discussion_r214445869 * fixes after Dev's comments
6 years ago
10 years ago
10 years ago
7 years ago
10 years ago
10 years ago
7 years ago
7 years ago
7 years ago
10 years ago
10 years ago
7 years ago
7 years ago
11 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package types
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/tendermint/tendermint/crypto/merkle"
  10. "github.com/tendermint/tendermint/crypto/tmhash"
  11. cmn "github.com/tendermint/tendermint/libs/common"
  12. )
  13. const (
  14. // MaxHeaderBytes is a maximum header size (including amino overhead).
  15. MaxHeaderBytes int64 = 511
  16. // MaxAminoOverheadForBlock - maximum amino overhead to encode a block (up to
  17. // MaxBlockSizeBytes in size) not including it's parts except Data.
  18. //
  19. // Uvarint length of MaxBlockSizeBytes: 4 bytes
  20. // 2 fields (2 embedded): 2 bytes
  21. // Uvarint length of Data.Txs: 4 bytes
  22. // Data.Txs field: 1 byte
  23. MaxAminoOverheadForBlock int64 = 11
  24. )
  25. // Block defines the atomic unit of a Tendermint blockchain.
  26. // TODO: add Version byte
  27. type Block struct {
  28. mtx sync.Mutex
  29. Header `json:"header"`
  30. Data `json:"data"`
  31. Evidence EvidenceData `json:"evidence"`
  32. LastCommit *Commit `json:"last_commit"`
  33. }
  34. // MakeBlock returns a new block with an empty header, except what can be
  35. // computed from itself.
  36. // It populates the same set of fields validated by ValidateBasic.
  37. func MakeBlock(height int64, txs []Tx, lastCommit *Commit, evidence []Evidence) *Block {
  38. block := &Block{
  39. Header: Header{
  40. Height: height,
  41. NumTxs: int64(len(txs)),
  42. },
  43. Data: Data{
  44. Txs: txs,
  45. },
  46. Evidence: EvidenceData{Evidence: evidence},
  47. LastCommit: lastCommit,
  48. }
  49. block.fillHeader()
  50. return block
  51. }
  52. // ValidateBasic performs basic validation that doesn't involve state data.
  53. // It checks the internal consistency of the block.
  54. func (b *Block) ValidateBasic() error {
  55. if b == nil {
  56. return errors.New("Nil blocks are invalid")
  57. }
  58. b.mtx.Lock()
  59. defer b.mtx.Unlock()
  60. newTxs := int64(len(b.Data.Txs))
  61. if b.NumTxs != newTxs {
  62. return fmt.Errorf(
  63. "Wrong Block.Header.NumTxs. Expected %v, got %v",
  64. newTxs,
  65. b.NumTxs,
  66. )
  67. }
  68. if !bytes.Equal(b.LastCommitHash, b.LastCommit.Hash()) {
  69. return fmt.Errorf(
  70. "Wrong Block.Header.LastCommitHash. Expected %v, got %v",
  71. b.LastCommitHash,
  72. b.LastCommit.Hash(),
  73. )
  74. }
  75. if b.Header.Height != 1 {
  76. if err := b.LastCommit.ValidateBasic(); err != nil {
  77. return err
  78. }
  79. }
  80. if !bytes.Equal(b.DataHash, b.Data.Hash()) {
  81. return fmt.Errorf(
  82. "Wrong Block.Header.DataHash. Expected %v, got %v",
  83. b.DataHash,
  84. b.Data.Hash(),
  85. )
  86. }
  87. if !bytes.Equal(b.EvidenceHash, b.Evidence.Hash()) {
  88. return fmt.Errorf(
  89. "Wrong Block.Header.EvidenceHash. Expected %v, got %v",
  90. b.EvidenceHash,
  91. b.Evidence.Hash(),
  92. )
  93. }
  94. return nil
  95. }
  96. // fillHeader fills in any remaining header fields that are a function of the block data
  97. func (b *Block) fillHeader() {
  98. if b.LastCommitHash == nil {
  99. b.LastCommitHash = b.LastCommit.Hash()
  100. }
  101. if b.DataHash == nil {
  102. b.DataHash = b.Data.Hash()
  103. }
  104. if b.EvidenceHash == nil {
  105. b.EvidenceHash = b.Evidence.Hash()
  106. }
  107. }
  108. // Hash computes and returns the block hash.
  109. // If the block is incomplete, block hash is nil for safety.
  110. func (b *Block) Hash() cmn.HexBytes {
  111. if b == nil {
  112. return nil
  113. }
  114. b.mtx.Lock()
  115. defer b.mtx.Unlock()
  116. if b == nil || b.LastCommit == nil {
  117. return nil
  118. }
  119. b.fillHeader()
  120. return b.Header.Hash()
  121. }
  122. // MakePartSet returns a PartSet containing parts of a serialized block.
  123. // This is the form in which the block is gossipped to peers.
  124. // CONTRACT: partSize is greater than zero.
  125. func (b *Block) MakePartSet(partSize int) *PartSet {
  126. if b == nil {
  127. return nil
  128. }
  129. b.mtx.Lock()
  130. defer b.mtx.Unlock()
  131. // We prefix the byte length, so that unmarshaling
  132. // can easily happen via a reader.
  133. bz, err := cdc.MarshalBinary(b)
  134. if err != nil {
  135. panic(err)
  136. }
  137. return NewPartSetFromData(bz, partSize)
  138. }
  139. // HashesTo is a convenience function that checks if a block hashes to the given argument.
  140. // Returns false if the block is nil or the hash is empty.
  141. func (b *Block) HashesTo(hash []byte) bool {
  142. if len(hash) == 0 {
  143. return false
  144. }
  145. if b == nil {
  146. return false
  147. }
  148. return bytes.Equal(b.Hash(), hash)
  149. }
  150. // Size returns size of the block in bytes.
  151. func (b *Block) Size() int {
  152. bz, err := cdc.MarshalBinaryBare(b)
  153. if err != nil {
  154. return 0
  155. }
  156. return len(bz)
  157. }
  158. // String returns a string representation of the block
  159. func (b *Block) String() string {
  160. return b.StringIndented("")
  161. }
  162. // StringIndented returns a string representation of the block
  163. func (b *Block) StringIndented(indent string) string {
  164. if b == nil {
  165. return "nil-Block"
  166. }
  167. return fmt.Sprintf(`Block{
  168. %s %v
  169. %s %v
  170. %s %v
  171. %s %v
  172. %s}#%v`,
  173. indent, b.Header.StringIndented(indent+" "),
  174. indent, b.Data.StringIndented(indent+" "),
  175. indent, b.Evidence.StringIndented(indent+" "),
  176. indent, b.LastCommit.StringIndented(indent+" "),
  177. indent, b.Hash())
  178. }
  179. // StringShort returns a shortened string representation of the block
  180. func (b *Block) StringShort() string {
  181. if b == nil {
  182. return "nil-Block"
  183. }
  184. return fmt.Sprintf("Block#%v", b.Hash())
  185. }
  186. //-----------------------------------------------------------------------------
  187. // MaxDataBytes returns the maximum size of block's data.
  188. //
  189. // XXX: Panics on negative result.
  190. func MaxDataBytes(maxBytes int64, valsCount, evidenceCount int) int64 {
  191. maxDataBytes := maxBytes -
  192. MaxAminoOverheadForBlock -
  193. MaxHeaderBytes -
  194. int64(valsCount)*MaxVoteBytes -
  195. int64(evidenceCount)*MaxEvidenceBytes
  196. if maxDataBytes < 0 {
  197. panic(fmt.Sprintf(
  198. "Negative MaxDataBytes. BlockSize.MaxBytes=%d is too small to accommodate header&lastCommit&evidence=%d",
  199. maxBytes,
  200. -(maxDataBytes - maxBytes),
  201. ))
  202. }
  203. return maxDataBytes
  204. }
  205. // MaxDataBytesUnknownEvidence returns the maximum size of block's data when
  206. // evidence count is unknown. MaxEvidenceBytesPerBlock will be used as the size
  207. // of evidence.
  208. //
  209. // XXX: Panics on negative result.
  210. func MaxDataBytesUnknownEvidence(maxBytes int64, valsCount int) int64 {
  211. maxDataBytes := maxBytes -
  212. MaxAminoOverheadForBlock -
  213. MaxHeaderBytes -
  214. int64(valsCount)*MaxVoteBytes -
  215. MaxEvidenceBytesPerBlock(maxBytes)
  216. if maxDataBytes < 0 {
  217. panic(fmt.Sprintf(
  218. "Negative MaxDataBytesUnknownEvidence. BlockSize.MaxBytes=%d is too small to accommodate header&lastCommit&evidence=%d",
  219. maxBytes,
  220. -(maxDataBytes - maxBytes),
  221. ))
  222. }
  223. return maxDataBytes
  224. }
  225. //-----------------------------------------------------------------------------
  226. // Header defines the structure of a Tendermint block header
  227. // TODO: limit header size
  228. // NOTE: changes to the Header should be duplicated in the abci Header
  229. // and in /docs/spec/blockchain/blockchain.md
  230. type Header struct {
  231. // basic block info
  232. ChainID string `json:"chain_id"`
  233. Height int64 `json:"height"`
  234. Time time.Time `json:"time"`
  235. NumTxs int64 `json:"num_txs"`
  236. TotalTxs int64 `json:"total_txs"`
  237. // prev block info
  238. LastBlockID BlockID `json:"last_block_id"`
  239. // hashes of block data
  240. LastCommitHash cmn.HexBytes `json:"last_commit_hash"` // commit from validators from the last block
  241. DataHash cmn.HexBytes `json:"data_hash"` // transactions
  242. // hashes from the app output from the prev block
  243. ValidatorsHash cmn.HexBytes `json:"validators_hash"` // validators for the current block
  244. NextValidatorsHash cmn.HexBytes `json:"next_validators_hash"` // validators for the next block
  245. ConsensusHash cmn.HexBytes `json:"consensus_hash"` // consensus params for current block
  246. AppHash cmn.HexBytes `json:"app_hash"` // state after txs from the previous block
  247. LastResultsHash cmn.HexBytes `json:"last_results_hash"` // root hash of all results from the txs from the previous block
  248. // consensus info
  249. EvidenceHash cmn.HexBytes `json:"evidence_hash"` // evidence included in the block
  250. ProposerAddress Address `json:"proposer_address"` // original proposer of the block
  251. }
  252. // Hash returns the hash of the header.
  253. // Returns nil if ValidatorHash is missing,
  254. // since a Header is not valid unless there is
  255. // a ValidatorsHash (corresponding to the validator set).
  256. func (h *Header) Hash() cmn.HexBytes {
  257. if h == nil || len(h.ValidatorsHash) == 0 {
  258. return nil
  259. }
  260. return merkle.SimpleHashFromMap(map[string]merkle.Hasher{
  261. "ChainID": aminoHasher(h.ChainID),
  262. "Height": aminoHasher(h.Height),
  263. "Time": aminoHasher(h.Time),
  264. "NumTxs": aminoHasher(h.NumTxs),
  265. "TotalTxs": aminoHasher(h.TotalTxs),
  266. "LastBlockID": aminoHasher(h.LastBlockID),
  267. "LastCommit": aminoHasher(h.LastCommitHash),
  268. "Data": aminoHasher(h.DataHash),
  269. "Validators": aminoHasher(h.ValidatorsHash),
  270. "NextValidators": aminoHasher(h.NextValidatorsHash),
  271. "App": aminoHasher(h.AppHash),
  272. "Consensus": aminoHasher(h.ConsensusHash),
  273. "Results": aminoHasher(h.LastResultsHash),
  274. "Evidence": aminoHasher(h.EvidenceHash),
  275. "Proposer": aminoHasher(h.ProposerAddress),
  276. })
  277. }
  278. // StringIndented returns a string representation of the header
  279. func (h *Header) StringIndented(indent string) string {
  280. if h == nil {
  281. return "nil-Header"
  282. }
  283. return fmt.Sprintf(`Header{
  284. %s ChainID: %v
  285. %s Height: %v
  286. %s Time: %v
  287. %s NumTxs: %v
  288. %s TotalTxs: %v
  289. %s LastBlockID: %v
  290. %s LastCommit: %v
  291. %s Data: %v
  292. %s Validators: %v
  293. %s NextValidators: %v
  294. %s App: %v
  295. %s Consensus: %v
  296. %s Results: %v
  297. %s Evidence: %v
  298. %s Proposer: %v
  299. %s}#%v`,
  300. indent, h.ChainID,
  301. indent, h.Height,
  302. indent, h.Time,
  303. indent, h.NumTxs,
  304. indent, h.TotalTxs,
  305. indent, h.LastBlockID,
  306. indent, h.LastCommitHash,
  307. indent, h.DataHash,
  308. indent, h.ValidatorsHash,
  309. indent, h.NextValidatorsHash,
  310. indent, h.AppHash,
  311. indent, h.ConsensusHash,
  312. indent, h.LastResultsHash,
  313. indent, h.EvidenceHash,
  314. indent, h.ProposerAddress,
  315. indent, h.Hash())
  316. }
  317. //-------------------------------------
  318. // Commit contains the evidence that a block was committed by a set of validators.
  319. // NOTE: Commit is empty for height 1, but never nil.
  320. type Commit struct {
  321. // NOTE: The Precommits are in order of address to preserve the bonded ValidatorSet order.
  322. // Any peer with a block can gossip precommits by index with a peer without recalculating the
  323. // active ValidatorSet.
  324. BlockID BlockID `json:"block_id"`
  325. Precommits []*Vote `json:"precommits"`
  326. // Volatile
  327. firstPrecommit *Vote
  328. hash cmn.HexBytes
  329. bitArray *cmn.BitArray
  330. }
  331. // FirstPrecommit returns the first non-nil precommit in the commit.
  332. // If all precommits are nil, it returns an empty precommit with height 0.
  333. func (commit *Commit) FirstPrecommit() *Vote {
  334. if len(commit.Precommits) == 0 {
  335. return nil
  336. }
  337. if commit.firstPrecommit != nil {
  338. return commit.firstPrecommit
  339. }
  340. for _, precommit := range commit.Precommits {
  341. if precommit != nil {
  342. commit.firstPrecommit = precommit
  343. return precommit
  344. }
  345. }
  346. return &Vote{
  347. Type: VoteTypePrecommit,
  348. }
  349. }
  350. // Height returns the height of the commit
  351. func (commit *Commit) Height() int64 {
  352. if len(commit.Precommits) == 0 {
  353. return 0
  354. }
  355. return commit.FirstPrecommit().Height
  356. }
  357. // Round returns the round of the commit
  358. func (commit *Commit) Round() int {
  359. if len(commit.Precommits) == 0 {
  360. return 0
  361. }
  362. return commit.FirstPrecommit().Round
  363. }
  364. // Type returns the vote type of the commit, which is always VoteTypePrecommit
  365. func (commit *Commit) Type() byte {
  366. return VoteTypePrecommit
  367. }
  368. // Size returns the number of votes in the commit
  369. func (commit *Commit) Size() int {
  370. if commit == nil {
  371. return 0
  372. }
  373. return len(commit.Precommits)
  374. }
  375. // BitArray returns a BitArray of which validators voted in this commit
  376. func (commit *Commit) BitArray() *cmn.BitArray {
  377. if commit.bitArray == nil {
  378. commit.bitArray = cmn.NewBitArray(len(commit.Precommits))
  379. for i, precommit := range commit.Precommits {
  380. // TODO: need to check the BlockID otherwise we could be counting conflicts,
  381. // not just the one with +2/3 !
  382. commit.bitArray.SetIndex(i, precommit != nil)
  383. }
  384. }
  385. return commit.bitArray
  386. }
  387. // GetByIndex returns the vote corresponding to a given validator index
  388. func (commit *Commit) GetByIndex(index int) *Vote {
  389. return commit.Precommits[index]
  390. }
  391. // IsCommit returns true if there is at least one vote
  392. func (commit *Commit) IsCommit() bool {
  393. return len(commit.Precommits) != 0
  394. }
  395. // ValidateBasic performs basic validation that doesn't involve state data.
  396. // Does not actually check the cryptographic signatures.
  397. func (commit *Commit) ValidateBasic() error {
  398. if commit.BlockID.IsZero() {
  399. return errors.New("Commit cannot be for nil block")
  400. }
  401. if len(commit.Precommits) == 0 {
  402. return errors.New("No precommits in commit")
  403. }
  404. height, round := commit.Height(), commit.Round()
  405. // Validate the precommits.
  406. for _, precommit := range commit.Precommits {
  407. // It's OK for precommits to be missing.
  408. if precommit == nil {
  409. continue
  410. }
  411. // Ensure that all votes are precommits.
  412. if precommit.Type != VoteTypePrecommit {
  413. return fmt.Errorf("Invalid commit vote. Expected precommit, got %v",
  414. precommit.Type)
  415. }
  416. // Ensure that all heights are the same.
  417. if precommit.Height != height {
  418. return fmt.Errorf("Invalid commit precommit height. Expected %v, got %v",
  419. height, precommit.Height)
  420. }
  421. // Ensure that all rounds are the same.
  422. if precommit.Round != round {
  423. return fmt.Errorf("Invalid commit precommit round. Expected %v, got %v",
  424. round, precommit.Round)
  425. }
  426. }
  427. return nil
  428. }
  429. // Hash returns the hash of the commit
  430. func (commit *Commit) Hash() cmn.HexBytes {
  431. if commit == nil {
  432. return nil
  433. }
  434. if commit.hash == nil {
  435. bs := make([]merkle.Hasher, len(commit.Precommits))
  436. for i, precommit := range commit.Precommits {
  437. bs[i] = aminoHasher(precommit)
  438. }
  439. commit.hash = merkle.SimpleHashFromHashers(bs)
  440. }
  441. return commit.hash
  442. }
  443. // StringIndented returns a string representation of the commit
  444. func (commit *Commit) StringIndented(indent string) string {
  445. if commit == nil {
  446. return "nil-Commit"
  447. }
  448. precommitStrings := make([]string, len(commit.Precommits))
  449. for i, precommit := range commit.Precommits {
  450. precommitStrings[i] = precommit.String()
  451. }
  452. return fmt.Sprintf(`Commit{
  453. %s BlockID: %v
  454. %s Precommits:
  455. %s %v
  456. %s}#%v`,
  457. indent, commit.BlockID,
  458. indent,
  459. indent, strings.Join(precommitStrings, "\n"+indent+" "),
  460. indent, commit.hash)
  461. }
  462. //-----------------------------------------------------------------------------
  463. // SignedHeader is a header along with the commits that prove it.
  464. type SignedHeader struct {
  465. *Header `json:"header"`
  466. Commit *Commit `json:"commit"`
  467. }
  468. // ValidateBasic does basic consistency checks and makes sure the header
  469. // and commit are consistent.
  470. //
  471. // NOTE: This does not actually check the cryptographic signatures. Make
  472. // sure to use a Verifier to validate the signatures actually provide a
  473. // significantly strong proof for this header's validity.
  474. func (sh SignedHeader) ValidateBasic(chainID string) error {
  475. // Make sure the header is consistent with the commit.
  476. if sh.Header == nil {
  477. return errors.New("SignedHeader missing header.")
  478. }
  479. if sh.Commit == nil {
  480. return errors.New("SignedHeader missing commit (precommit votes).")
  481. }
  482. // Check ChainID.
  483. if sh.ChainID != chainID {
  484. return fmt.Errorf("Header belongs to another chain '%s' not '%s'",
  485. sh.ChainID, chainID)
  486. }
  487. // Check Height.
  488. if sh.Commit.Height() != sh.Height {
  489. return fmt.Errorf("SignedHeader header and commit height mismatch: %v vs %v",
  490. sh.Height, sh.Commit.Height())
  491. }
  492. // Check Hash.
  493. hhash := sh.Hash()
  494. chash := sh.Commit.BlockID.Hash
  495. if !bytes.Equal(hhash, chash) {
  496. return fmt.Errorf("SignedHeader commit signs block %X, header is block %X",
  497. chash, hhash)
  498. }
  499. // ValidateBasic on the Commit.
  500. err := sh.Commit.ValidateBasic()
  501. if err != nil {
  502. return cmn.ErrorWrap(err, "commit.ValidateBasic failed during SignedHeader.ValidateBasic")
  503. }
  504. return nil
  505. }
  506. func (sh SignedHeader) String() string {
  507. return sh.StringIndented("")
  508. }
  509. // StringIndented returns a string representation of the SignedHeader.
  510. func (sh SignedHeader) StringIndented(indent string) string {
  511. return fmt.Sprintf(`SignedHeader{
  512. %s %v
  513. %s %v
  514. %s}`,
  515. indent, sh.Header.StringIndented(indent+" "),
  516. indent, sh.Commit.StringIndented(indent+" "),
  517. indent)
  518. return ""
  519. }
  520. //-----------------------------------------------------------------------------
  521. // Data contains the set of transactions included in the block
  522. type Data struct {
  523. // Txs that will be applied by state @ block.Height+1.
  524. // NOTE: not all txs here are valid. We're just agreeing on the order first.
  525. // This means that block.AppHash does not include these txs.
  526. Txs Txs `json:"txs"`
  527. // Volatile
  528. hash cmn.HexBytes
  529. }
  530. // Hash returns the hash of the data
  531. func (data *Data) Hash() cmn.HexBytes {
  532. if data == nil {
  533. return (Txs{}).Hash()
  534. }
  535. if data.hash == nil {
  536. data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs
  537. }
  538. return data.hash
  539. }
  540. // StringIndented returns a string representation of the transactions
  541. func (data *Data) StringIndented(indent string) string {
  542. if data == nil {
  543. return "nil-Data"
  544. }
  545. txStrings := make([]string, cmn.MinInt(len(data.Txs), 21))
  546. for i, tx := range data.Txs {
  547. if i == 20 {
  548. txStrings[i] = fmt.Sprintf("... (%v total)", len(data.Txs))
  549. break
  550. }
  551. txStrings[i] = fmt.Sprintf("%X (%d bytes)", tx.Hash(), len(tx))
  552. }
  553. return fmt.Sprintf(`Data{
  554. %s %v
  555. %s}#%v`,
  556. indent, strings.Join(txStrings, "\n"+indent+" "),
  557. indent, data.hash)
  558. }
  559. //-----------------------------------------------------------------------------
  560. // EvidenceData contains any evidence of malicious wrong-doing by validators
  561. type EvidenceData struct {
  562. Evidence EvidenceList `json:"evidence"`
  563. // Volatile
  564. hash cmn.HexBytes
  565. }
  566. // Hash returns the hash of the data.
  567. func (data *EvidenceData) Hash() cmn.HexBytes {
  568. if data.hash == nil {
  569. data.hash = data.Evidence.Hash()
  570. }
  571. return data.hash
  572. }
  573. // StringIndented returns a string representation of the evidence.
  574. func (data *EvidenceData) StringIndented(indent string) string {
  575. if data == nil {
  576. return "nil-Evidence"
  577. }
  578. evStrings := make([]string, cmn.MinInt(len(data.Evidence), 21))
  579. for i, ev := range data.Evidence {
  580. if i == 20 {
  581. evStrings[i] = fmt.Sprintf("... (%v total)", len(data.Evidence))
  582. break
  583. }
  584. evStrings[i] = fmt.Sprintf("Evidence:%v", ev)
  585. }
  586. return fmt.Sprintf(`EvidenceData{
  587. %s %v
  588. %s}#%v`,
  589. indent, strings.Join(evStrings, "\n"+indent+" "),
  590. indent, data.hash)
  591. return ""
  592. }
  593. //--------------------------------------------------------------------------------
  594. // BlockID defines the unique ID of a block as its Hash and its PartSetHeader
  595. type BlockID struct {
  596. Hash cmn.HexBytes `json:"hash"`
  597. PartsHeader PartSetHeader `json:"parts"`
  598. }
  599. // IsZero returns true if this is the BlockID for a nil-block
  600. func (blockID BlockID) IsZero() bool {
  601. return len(blockID.Hash) == 0 && blockID.PartsHeader.IsZero()
  602. }
  603. // Equals returns true if the BlockID matches the given BlockID
  604. func (blockID BlockID) Equals(other BlockID) bool {
  605. return bytes.Equal(blockID.Hash, other.Hash) &&
  606. blockID.PartsHeader.Equals(other.PartsHeader)
  607. }
  608. // Key returns a machine-readable string representation of the BlockID
  609. func (blockID BlockID) Key() string {
  610. bz, err := cdc.MarshalBinaryBare(blockID.PartsHeader)
  611. if err != nil {
  612. panic(err)
  613. }
  614. return string(blockID.Hash) + string(bz)
  615. }
  616. // String returns a human readable string representation of the BlockID
  617. func (blockID BlockID) String() string {
  618. return fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartsHeader)
  619. }
  620. //-------------------------------------------------------
  621. type hasher struct {
  622. item interface{}
  623. }
  624. func (h hasher) Hash() []byte {
  625. hasher := tmhash.New()
  626. if h.item != nil && !cmn.IsTypedNil(h.item) && !cmn.IsEmpty(h.item) {
  627. bz, err := cdc.MarshalBinaryBare(h.item)
  628. if err != nil {
  629. panic(err)
  630. }
  631. _, err = hasher.Write(bz)
  632. if err != nil {
  633. panic(err)
  634. }
  635. }
  636. return hasher.Sum(nil)
  637. }
  638. func aminoHash(item interface{}) []byte {
  639. h := hasher{item}
  640. return h.Hash()
  641. }
  642. func aminoHasher(item interface{}) merkle.Hasher {
  643. return hasher{item}
  644. }