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.

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