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.

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