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.

697 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
6 years ago
7 years ago
10 years ago
9 years ago
10 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. )
  12. const (
  13. // MaxHeaderBytes is a maximum header size (including amino overhead).
  14. MaxHeaderBytes int64 = 511
  15. // MaxAminoOverheadForBlock - maximum amino overhead to encode a block (up to
  16. // MaxBlockSizeBytes in size) not including it's parts except Data.
  17. //
  18. // Uvarint length of MaxBlockSizeBytes: 4 bytes
  19. // 2 fields (2 embedded): 2 bytes
  20. // Uvarint length of Data.Txs: 4 bytes
  21. // Data.Txs field: 1 byte
  22. MaxAminoOverheadForBlock int64 = 11
  23. )
  24. // Block defines the atomic unit of a Tendermint blockchain.
  25. // TODO: add Version byte
  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. // TODO: limit header size
  233. // NOTE: changes to the Header should be duplicated in the abci Header
  234. // and in /docs/spec/blockchain/blockchain.md
  235. type Header struct {
  236. // basic block info
  237. ChainID string `json:"chain_id"`
  238. Height int64 `json:"height"`
  239. Time time.Time `json:"time"`
  240. NumTxs int64 `json:"num_txs"`
  241. TotalTxs int64 `json:"total_txs"`
  242. // prev block info
  243. LastBlockID BlockID `json:"last_block_id"`
  244. // hashes of block data
  245. LastCommitHash cmn.HexBytes `json:"last_commit_hash"` // commit from validators from the last block
  246. DataHash cmn.HexBytes `json:"data_hash"` // transactions
  247. // hashes from the app output from the prev block
  248. ValidatorsHash cmn.HexBytes `json:"validators_hash"` // validators for the current block
  249. NextValidatorsHash cmn.HexBytes `json:"next_validators_hash"` // validators for the next block
  250. ConsensusHash cmn.HexBytes `json:"consensus_hash"` // consensus params for current block
  251. AppHash cmn.HexBytes `json:"app_hash"` // state after txs from the previous block
  252. LastResultsHash cmn.HexBytes `json:"last_results_hash"` // root hash of all results from the txs from the previous block
  253. // consensus info
  254. EvidenceHash cmn.HexBytes `json:"evidence_hash"` // evidence included in the block
  255. ProposerAddress Address `json:"proposer_address"` // original proposer of the block
  256. }
  257. // Hash returns the hash of the header.
  258. // Returns nil if ValidatorHash is missing,
  259. // since a Header is not valid unless there is
  260. // a ValidatorsHash (corresponding to the validator set).
  261. func (h *Header) Hash() cmn.HexBytes {
  262. if h == nil || len(h.ValidatorsHash) == 0 {
  263. return nil
  264. }
  265. return merkle.SimpleHashFromMap(map[string][]byte{
  266. "ChainID": cdcEncode(h.ChainID),
  267. "Height": cdcEncode(h.Height),
  268. "Time": cdcEncode(h.Time),
  269. "NumTxs": cdcEncode(h.NumTxs),
  270. "TotalTxs": cdcEncode(h.TotalTxs),
  271. "LastBlockID": cdcEncode(h.LastBlockID),
  272. "LastCommit": cdcEncode(h.LastCommitHash),
  273. "Data": cdcEncode(h.DataHash),
  274. "Validators": cdcEncode(h.ValidatorsHash),
  275. "NextValidators": cdcEncode(h.NextValidatorsHash),
  276. "App": cdcEncode(h.AppHash),
  277. "Consensus": cdcEncode(h.ConsensusHash),
  278. "Results": cdcEncode(h.LastResultsHash),
  279. "Evidence": cdcEncode(h.EvidenceHash),
  280. "Proposer": cdcEncode(h.ProposerAddress),
  281. })
  282. }
  283. // StringIndented returns a string representation of the header
  284. func (h *Header) StringIndented(indent string) string {
  285. if h == nil {
  286. return "nil-Header"
  287. }
  288. return fmt.Sprintf(`Header{
  289. %s ChainID: %v
  290. %s Height: %v
  291. %s Time: %v
  292. %s NumTxs: %v
  293. %s TotalTxs: %v
  294. %s LastBlockID: %v
  295. %s LastCommit: %v
  296. %s Data: %v
  297. %s Validators: %v
  298. %s NextValidators: %v
  299. %s App: %v
  300. %s Consensus: %v
  301. %s Results: %v
  302. %s Evidence: %v
  303. %s Proposer: %v
  304. %s}#%v`,
  305. indent, h.ChainID,
  306. indent, h.Height,
  307. indent, h.Time,
  308. indent, h.NumTxs,
  309. indent, h.TotalTxs,
  310. indent, h.LastBlockID,
  311. indent, h.LastCommitHash,
  312. indent, h.DataHash,
  313. indent, h.ValidatorsHash,
  314. indent, h.NextValidatorsHash,
  315. indent, h.AppHash,
  316. indent, h.ConsensusHash,
  317. indent, h.LastResultsHash,
  318. indent, h.EvidenceHash,
  319. indent, h.ProposerAddress,
  320. indent, h.Hash())
  321. }
  322. //-------------------------------------
  323. // Commit contains the evidence that a block was committed by a set of validators.
  324. // NOTE: Commit is empty for height 1, but never nil.
  325. type Commit struct {
  326. // NOTE: The Precommits are in order of address to preserve the bonded ValidatorSet order.
  327. // Any peer with a block can gossip precommits by index with a peer without recalculating the
  328. // active ValidatorSet.
  329. BlockID BlockID `json:"block_id"`
  330. Precommits []*Vote `json:"precommits"`
  331. // Volatile
  332. firstPrecommit *Vote
  333. hash cmn.HexBytes
  334. bitArray *cmn.BitArray
  335. }
  336. // FirstPrecommit returns the first non-nil precommit in the commit.
  337. // If all precommits are nil, it returns an empty precommit with height 0.
  338. func (commit *Commit) FirstPrecommit() *Vote {
  339. if len(commit.Precommits) == 0 {
  340. return nil
  341. }
  342. if commit.firstPrecommit != nil {
  343. return commit.firstPrecommit
  344. }
  345. for _, precommit := range commit.Precommits {
  346. if precommit != nil {
  347. commit.firstPrecommit = precommit
  348. return precommit
  349. }
  350. }
  351. return &Vote{
  352. Type: VoteTypePrecommit,
  353. }
  354. }
  355. // Height returns the height of the commit
  356. func (commit *Commit) Height() int64 {
  357. if len(commit.Precommits) == 0 {
  358. return 0
  359. }
  360. return commit.FirstPrecommit().Height
  361. }
  362. // Round returns the round of the commit
  363. func (commit *Commit) Round() int {
  364. if len(commit.Precommits) == 0 {
  365. return 0
  366. }
  367. return commit.FirstPrecommit().Round
  368. }
  369. // Type returns the vote type of the commit, which is always VoteTypePrecommit
  370. func (commit *Commit) Type() byte {
  371. return VoteTypePrecommit
  372. }
  373. // Size returns the number of votes in the commit
  374. func (commit *Commit) Size() int {
  375. if commit == nil {
  376. return 0
  377. }
  378. return len(commit.Precommits)
  379. }
  380. // BitArray returns a BitArray of which validators voted in this commit
  381. func (commit *Commit) BitArray() *cmn.BitArray {
  382. if commit.bitArray == nil {
  383. commit.bitArray = cmn.NewBitArray(len(commit.Precommits))
  384. for i, precommit := range commit.Precommits {
  385. // TODO: need to check the BlockID otherwise we could be counting conflicts,
  386. // not just the one with +2/3 !
  387. commit.bitArray.SetIndex(i, precommit != nil)
  388. }
  389. }
  390. return commit.bitArray
  391. }
  392. // GetByIndex returns the vote corresponding to a given validator index
  393. func (commit *Commit) GetByIndex(index int) *Vote {
  394. return commit.Precommits[index]
  395. }
  396. // IsCommit returns true if there is at least one vote
  397. func (commit *Commit) IsCommit() bool {
  398. return len(commit.Precommits) != 0
  399. }
  400. // ValidateBasic performs basic validation that doesn't involve state data.
  401. // Does not actually check the cryptographic signatures.
  402. func (commit *Commit) ValidateBasic() error {
  403. if commit.BlockID.IsZero() {
  404. return errors.New("Commit cannot be for nil block")
  405. }
  406. if len(commit.Precommits) == 0 {
  407. return errors.New("No precommits in commit")
  408. }
  409. height, round := commit.Height(), commit.Round()
  410. // Validate the precommits.
  411. for _, precommit := range commit.Precommits {
  412. // It's OK for precommits to be missing.
  413. if precommit == nil {
  414. continue
  415. }
  416. // Ensure that all votes are precommits.
  417. if precommit.Type != VoteTypePrecommit {
  418. return fmt.Errorf("Invalid commit vote. Expected precommit, got %v",
  419. precommit.Type)
  420. }
  421. // Ensure that all heights are the same.
  422. if precommit.Height != height {
  423. return fmt.Errorf("Invalid commit precommit height. Expected %v, got %v",
  424. height, precommit.Height)
  425. }
  426. // Ensure that all rounds are the same.
  427. if precommit.Round != round {
  428. return fmt.Errorf("Invalid commit precommit round. Expected %v, got %v",
  429. round, precommit.Round)
  430. }
  431. }
  432. return nil
  433. }
  434. // Hash returns the hash of the commit
  435. func (commit *Commit) Hash() cmn.HexBytes {
  436. if commit == nil {
  437. return nil
  438. }
  439. if commit.hash == nil {
  440. bs := make([][]byte, len(commit.Precommits))
  441. for i, precommit := range commit.Precommits {
  442. bs[i] = cdcEncode(precommit)
  443. }
  444. commit.hash = merkle.SimpleHashFromByteSlices(bs)
  445. }
  446. return commit.hash
  447. }
  448. // StringIndented returns a string representation of the commit
  449. func (commit *Commit) StringIndented(indent string) string {
  450. if commit == nil {
  451. return "nil-Commit"
  452. }
  453. precommitStrings := make([]string, len(commit.Precommits))
  454. for i, precommit := range commit.Precommits {
  455. precommitStrings[i] = precommit.String()
  456. }
  457. return fmt.Sprintf(`Commit{
  458. %s BlockID: %v
  459. %s Precommits:
  460. %s %v
  461. %s}#%v`,
  462. indent, commit.BlockID,
  463. indent,
  464. indent, strings.Join(precommitStrings, "\n"+indent+" "),
  465. indent, commit.hash)
  466. }
  467. //-----------------------------------------------------------------------------
  468. // SignedHeader is a header along with the commits that prove it.
  469. type SignedHeader struct {
  470. *Header `json:"header"`
  471. Commit *Commit `json:"commit"`
  472. }
  473. // ValidateBasic does basic consistency checks and makes sure the header
  474. // and commit are consistent.
  475. //
  476. // NOTE: This does not actually check the cryptographic signatures. Make
  477. // sure to use a Verifier to validate the signatures actually provide a
  478. // significantly strong proof for this header's validity.
  479. func (sh SignedHeader) ValidateBasic(chainID string) error {
  480. // Make sure the header is consistent with the commit.
  481. if sh.Header == nil {
  482. return errors.New("SignedHeader missing header.")
  483. }
  484. if sh.Commit == nil {
  485. return errors.New("SignedHeader missing commit (precommit votes).")
  486. }
  487. // Check ChainID.
  488. if sh.ChainID != chainID {
  489. return fmt.Errorf("Header belongs to another chain '%s' not '%s'",
  490. sh.ChainID, chainID)
  491. }
  492. // Check Height.
  493. if sh.Commit.Height() != sh.Height {
  494. return fmt.Errorf("SignedHeader header and commit height mismatch: %v vs %v",
  495. sh.Height, sh.Commit.Height())
  496. }
  497. // Check Hash.
  498. hhash := sh.Hash()
  499. chash := sh.Commit.BlockID.Hash
  500. if !bytes.Equal(hhash, chash) {
  501. return fmt.Errorf("SignedHeader commit signs block %X, header is block %X",
  502. chash, hhash)
  503. }
  504. // ValidateBasic on the Commit.
  505. err := sh.Commit.ValidateBasic()
  506. if err != nil {
  507. return cmn.ErrorWrap(err, "commit.ValidateBasic failed during SignedHeader.ValidateBasic")
  508. }
  509. return nil
  510. }
  511. func (sh SignedHeader) String() string {
  512. return sh.StringIndented("")
  513. }
  514. // StringIndented returns a string representation of the SignedHeader.
  515. func (sh SignedHeader) StringIndented(indent string) string {
  516. return fmt.Sprintf(`SignedHeader{
  517. %s %v
  518. %s %v
  519. %s}`,
  520. indent, sh.Header.StringIndented(indent+" "),
  521. indent, sh.Commit.StringIndented(indent+" "),
  522. indent)
  523. return ""
  524. }
  525. //-----------------------------------------------------------------------------
  526. // Data contains the set of transactions included in the block
  527. type Data struct {
  528. // Txs that will be applied by state @ block.Height+1.
  529. // NOTE: not all txs here are valid. We're just agreeing on the order first.
  530. // This means that block.AppHash does not include these txs.
  531. Txs Txs `json:"txs"`
  532. // Volatile
  533. hash cmn.HexBytes
  534. }
  535. // Hash returns the hash of the data
  536. func (data *Data) Hash() cmn.HexBytes {
  537. if data == nil {
  538. return (Txs{}).Hash()
  539. }
  540. if data.hash == nil {
  541. data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs
  542. }
  543. return data.hash
  544. }
  545. // StringIndented returns a string representation of the transactions
  546. func (data *Data) StringIndented(indent string) string {
  547. if data == nil {
  548. return "nil-Data"
  549. }
  550. txStrings := make([]string, cmn.MinInt(len(data.Txs), 21))
  551. for i, tx := range data.Txs {
  552. if i == 20 {
  553. txStrings[i] = fmt.Sprintf("... (%v total)", len(data.Txs))
  554. break
  555. }
  556. txStrings[i] = fmt.Sprintf("%X (%d bytes)", tx.Hash(), len(tx))
  557. }
  558. return fmt.Sprintf(`Data{
  559. %s %v
  560. %s}#%v`,
  561. indent, strings.Join(txStrings, "\n"+indent+" "),
  562. indent, data.hash)
  563. }
  564. //-----------------------------------------------------------------------------
  565. // EvidenceData contains any evidence of malicious wrong-doing by validators
  566. type EvidenceData struct {
  567. Evidence EvidenceList `json:"evidence"`
  568. // Volatile
  569. hash cmn.HexBytes
  570. }
  571. // Hash returns the hash of the data.
  572. func (data *EvidenceData) Hash() cmn.HexBytes {
  573. if data.hash == nil {
  574. data.hash = data.Evidence.Hash()
  575. }
  576. return data.hash
  577. }
  578. // StringIndented returns a string representation of the evidence.
  579. func (data *EvidenceData) StringIndented(indent string) string {
  580. if data == nil {
  581. return "nil-Evidence"
  582. }
  583. evStrings := make([]string, cmn.MinInt(len(data.Evidence), 21))
  584. for i, ev := range data.Evidence {
  585. if i == 20 {
  586. evStrings[i] = fmt.Sprintf("... (%v total)", len(data.Evidence))
  587. break
  588. }
  589. evStrings[i] = fmt.Sprintf("Evidence:%v", ev)
  590. }
  591. return fmt.Sprintf(`EvidenceData{
  592. %s %v
  593. %s}#%v`,
  594. indent, strings.Join(evStrings, "\n"+indent+" "),
  595. indent, data.hash)
  596. return ""
  597. }
  598. //--------------------------------------------------------------------------------
  599. // BlockID defines the unique ID of a block as its Hash and its PartSetHeader
  600. type BlockID struct {
  601. Hash cmn.HexBytes `json:"hash"`
  602. PartsHeader PartSetHeader `json:"parts"`
  603. }
  604. // IsZero returns true if this is the BlockID for a nil-block
  605. func (blockID BlockID) IsZero() bool {
  606. return len(blockID.Hash) == 0 && blockID.PartsHeader.IsZero()
  607. }
  608. // Equals returns true if the BlockID matches the given BlockID
  609. func (blockID BlockID) Equals(other BlockID) bool {
  610. return bytes.Equal(blockID.Hash, other.Hash) &&
  611. blockID.PartsHeader.Equals(other.PartsHeader)
  612. }
  613. // Key returns a machine-readable string representation of the BlockID
  614. func (blockID BlockID) Key() string {
  615. bz, err := cdc.MarshalBinaryBare(blockID.PartsHeader)
  616. if err != nil {
  617. panic(err)
  618. }
  619. return string(blockID.Hash) + string(bz)
  620. }
  621. // String returns a human readable string representation of the BlockID
  622. func (blockID BlockID) String() string {
  623. return fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartsHeader)
  624. }