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.

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