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.

595 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
  1. package types
  2. import (
  3. // it is ok to use math/rand here: we do not need a cryptographically secure random
  4. // number generator here and we can run the tests a bit faster
  5. "crypto/rand"
  6. "encoding/hex"
  7. "math"
  8. "os"
  9. "reflect"
  10. "testing"
  11. "time"
  12. "github.com/stretchr/testify/assert"
  13. "github.com/stretchr/testify/require"
  14. "github.com/tendermint/tendermint/crypto"
  15. "github.com/tendermint/tendermint/crypto/merkle"
  16. "github.com/tendermint/tendermint/crypto/tmhash"
  17. cmn "github.com/tendermint/tendermint/libs/common"
  18. tmtime "github.com/tendermint/tendermint/types/time"
  19. "github.com/tendermint/tendermint/version"
  20. )
  21. func TestMain(m *testing.M) {
  22. RegisterMockEvidences(cdc)
  23. code := m.Run()
  24. os.Exit(code)
  25. }
  26. func TestBlockAddEvidence(t *testing.T) {
  27. txs := []Tx{Tx("foo"), Tx("bar")}
  28. lastID := makeBlockIDRandom()
  29. h := int64(3)
  30. voteSet, valSet, vals := randVoteSet(h-1, 1, PrecommitType, 10, 1)
  31. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals)
  32. require.NoError(t, err)
  33. ev := NewMockGoodEvidence(h, 0, valSet.Validators[0].Address)
  34. evList := []Evidence{ev}
  35. block := MakeBlock(h, txs, commit, evList)
  36. require.NotNil(t, block)
  37. require.Equal(t, 1, len(block.Evidence.Evidence))
  38. require.NotNil(t, block.EvidenceHash)
  39. }
  40. func TestBlockValidateBasic(t *testing.T) {
  41. require.Error(t, (*Block)(nil).ValidateBasic())
  42. txs := []Tx{Tx("foo"), Tx("bar")}
  43. lastID := makeBlockIDRandom()
  44. h := int64(3)
  45. voteSet, valSet, vals := randVoteSet(h-1, 1, PrecommitType, 10, 1)
  46. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals)
  47. require.NoError(t, err)
  48. ev := NewMockGoodEvidence(h, 0, valSet.Validators[0].Address)
  49. evList := []Evidence{ev}
  50. testCases := []struct {
  51. testName string
  52. malleateBlock func(*Block)
  53. expErr bool
  54. }{
  55. {"Make Block", func(blk *Block) {}, false},
  56. {"Make Block w/ proposer Addr", func(blk *Block) { blk.ProposerAddress = valSet.GetProposer().Address }, false},
  57. {"Negative Height", func(blk *Block) { blk.Height = -1 }, true},
  58. {"Remove 1/2 the commits", func(blk *Block) {
  59. blk.LastCommit.Precommits = commit.Precommits[:commit.Size()/2]
  60. blk.LastCommit.hash = nil // clear hash or change wont be noticed
  61. }, true},
  62. {"Remove LastCommitHash", func(blk *Block) { blk.LastCommitHash = []byte("something else") }, true},
  63. {"Tampered Data", func(blk *Block) {
  64. blk.Data.Txs[0] = Tx("something else")
  65. blk.Data.hash = nil // clear hash or change wont be noticed
  66. }, true},
  67. {"Tampered DataHash", func(blk *Block) {
  68. blk.DataHash = cmn.RandBytes(len(blk.DataHash))
  69. }, true},
  70. {"Tampered EvidenceHash", func(blk *Block) {
  71. blk.EvidenceHash = []byte("something else")
  72. }, true},
  73. }
  74. for i, tc := range testCases {
  75. tc := tc
  76. i := i
  77. t.Run(tc.testName, func(t *testing.T) {
  78. block := MakeBlock(h, txs, commit, evList)
  79. block.ProposerAddress = valSet.GetProposer().Address
  80. tc.malleateBlock(block)
  81. err = block.ValidateBasic()
  82. assert.Equal(t, tc.expErr, err != nil, "#%d: %v", i, err)
  83. })
  84. }
  85. }
  86. func TestBlockHash(t *testing.T) {
  87. assert.Nil(t, (*Block)(nil).Hash())
  88. assert.Nil(t, MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil, nil).Hash())
  89. }
  90. func TestBlockMakePartSet(t *testing.T) {
  91. assert.Nil(t, (*Block)(nil).MakePartSet(2))
  92. partSet := MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil, nil).MakePartSet(1024)
  93. assert.NotNil(t, partSet)
  94. assert.Equal(t, 1, partSet.Total())
  95. }
  96. func TestBlockMakePartSetWithEvidence(t *testing.T) {
  97. assert.Nil(t, (*Block)(nil).MakePartSet(2))
  98. lastID := makeBlockIDRandom()
  99. h := int64(3)
  100. voteSet, valSet, vals := randVoteSet(h-1, 1, PrecommitType, 10, 1)
  101. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals)
  102. require.NoError(t, err)
  103. ev := NewMockGoodEvidence(h, 0, valSet.Validators[0].Address)
  104. evList := []Evidence{ev}
  105. partSet := MakeBlock(h, []Tx{Tx("Hello World")}, commit, evList).MakePartSet(1024)
  106. assert.NotNil(t, partSet)
  107. assert.Equal(t, 3, partSet.Total())
  108. }
  109. func TestBlockHashesTo(t *testing.T) {
  110. assert.False(t, (*Block)(nil).HashesTo(nil))
  111. lastID := makeBlockIDRandom()
  112. h := int64(3)
  113. voteSet, valSet, vals := randVoteSet(h-1, 1, PrecommitType, 10, 1)
  114. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals)
  115. require.NoError(t, err)
  116. ev := NewMockGoodEvidence(h, 0, valSet.Validators[0].Address)
  117. evList := []Evidence{ev}
  118. block := MakeBlock(h, []Tx{Tx("Hello World")}, commit, evList)
  119. block.ValidatorsHash = valSet.Hash()
  120. assert.False(t, block.HashesTo([]byte{}))
  121. assert.False(t, block.HashesTo([]byte("something else")))
  122. assert.True(t, block.HashesTo(block.Hash()))
  123. }
  124. func TestBlockSize(t *testing.T) {
  125. size := MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil, nil).Size()
  126. if size <= 0 {
  127. t.Fatal("Size of the block is zero or negative")
  128. }
  129. }
  130. func TestBlockString(t *testing.T) {
  131. assert.Equal(t, "nil-Block", (*Block)(nil).String())
  132. assert.Equal(t, "nil-Block", (*Block)(nil).StringIndented(""))
  133. assert.Equal(t, "nil-Block", (*Block)(nil).StringShort())
  134. block := MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil, nil)
  135. assert.NotEqual(t, "nil-Block", block.String())
  136. assert.NotEqual(t, "nil-Block", block.StringIndented(""))
  137. assert.NotEqual(t, "nil-Block", block.StringShort())
  138. }
  139. func makeBlockIDRandom() BlockID {
  140. blockHash := make([]byte, tmhash.Size)
  141. partSetHash := make([]byte, tmhash.Size)
  142. rand.Read(blockHash) //nolint: gosec
  143. rand.Read(partSetHash) //nolint: gosec
  144. blockPartsHeader := PartSetHeader{123, partSetHash}
  145. return BlockID{blockHash, blockPartsHeader}
  146. }
  147. func makeBlockID(hash []byte, partSetSize int, partSetHash []byte) BlockID {
  148. return BlockID{
  149. Hash: hash,
  150. PartsHeader: PartSetHeader{
  151. Total: partSetSize,
  152. Hash: partSetHash,
  153. },
  154. }
  155. }
  156. var nilBytes []byte
  157. func TestNilHeaderHashDoesntCrash(t *testing.T) {
  158. assert.Equal(t, []byte((*Header)(nil).Hash()), nilBytes)
  159. assert.Equal(t, []byte((new(Header)).Hash()), nilBytes)
  160. }
  161. func TestNilDataHashDoesntCrash(t *testing.T) {
  162. assert.Equal(t, []byte((*Data)(nil).Hash()), nilBytes)
  163. assert.Equal(t, []byte(new(Data).Hash()), nilBytes)
  164. }
  165. func TestCommit(t *testing.T) {
  166. lastID := makeBlockIDRandom()
  167. h := int64(3)
  168. voteSet, _, vals := randVoteSet(h-1, 1, PrecommitType, 10, 1)
  169. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals)
  170. require.NoError(t, err)
  171. assert.Equal(t, h-1, commit.Height())
  172. assert.Equal(t, 1, commit.Round())
  173. assert.Equal(t, PrecommitType, SignedMsgType(commit.Type()))
  174. if commit.Size() <= 0 {
  175. t.Fatalf("commit %v has a zero or negative size: %d", commit, commit.Size())
  176. }
  177. require.NotNil(t, commit.BitArray())
  178. assert.Equal(t, cmn.NewBitArray(10).Size(), commit.BitArray().Size())
  179. assert.Equal(t, voteSet.GetByIndex(0), commit.GetByIndex(0))
  180. assert.True(t, commit.IsCommit())
  181. }
  182. func TestCommitValidateBasic(t *testing.T) {
  183. testCases := []struct {
  184. testName string
  185. malleateCommit func(*Commit)
  186. expectErr bool
  187. }{
  188. {"Random Commit", func(com *Commit) {}, false},
  189. {"Nil precommit", func(com *Commit) { com.Precommits[0] = nil }, false},
  190. {"Incorrect signature", func(com *Commit) { com.Precommits[0].Signature = []byte{0} }, false},
  191. {"Incorrect type", func(com *Commit) { com.Precommits[0].Type = PrevoteType }, true},
  192. {"Incorrect height", func(com *Commit) { com.Precommits[0].Height = int64(100) }, true},
  193. {"Incorrect round", func(com *Commit) { com.Precommits[0].Round = 100 }, true},
  194. }
  195. for _, tc := range testCases {
  196. tc := tc
  197. t.Run(tc.testName, func(t *testing.T) {
  198. com := randCommit()
  199. tc.malleateCommit(com)
  200. assert.Equal(t, tc.expectErr, com.ValidateBasic() != nil, "Validate Basic had an unexpected result")
  201. })
  202. }
  203. }
  204. func TestHeaderHash(t *testing.T) {
  205. testCases := []struct {
  206. desc string
  207. header *Header
  208. expectHash cmn.HexBytes
  209. }{
  210. {"Generates expected hash", &Header{
  211. Version: version.Consensus{Block: 1, App: 2},
  212. ChainID: "chainId",
  213. Height: 3,
  214. Time: time.Date(2019, 10, 13, 16, 14, 44, 0, time.UTC),
  215. LastBlockID: makeBlockID(make([]byte, tmhash.Size), 6, make([]byte, tmhash.Size)),
  216. LastCommitHash: tmhash.Sum([]byte("last_commit_hash")),
  217. DataHash: tmhash.Sum([]byte("data_hash")),
  218. ValidatorsHash: tmhash.Sum([]byte("validators_hash")),
  219. NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")),
  220. ConsensusHash: tmhash.Sum([]byte("consensus_hash")),
  221. AppHash: tmhash.Sum([]byte("app_hash")),
  222. LastResultsHash: tmhash.Sum([]byte("last_results_hash")),
  223. EvidenceHash: tmhash.Sum([]byte("evidence_hash")),
  224. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  225. }, hexBytesFromString("ABDC78921B18A47EE6BEF5E31637BADB0F3E587E3C0F4DB2D1E93E9FF0533862")},
  226. {"nil header yields nil", nil, nil},
  227. {"nil ValidatorsHash yields nil", &Header{
  228. Version: version.Consensus{Block: 1, App: 2},
  229. ChainID: "chainId",
  230. Height: 3,
  231. Time: time.Date(2019, 10, 13, 16, 14, 44, 0, time.UTC),
  232. LastBlockID: makeBlockID(make([]byte, tmhash.Size), 6, make([]byte, tmhash.Size)),
  233. LastCommitHash: tmhash.Sum([]byte("last_commit_hash")),
  234. DataHash: tmhash.Sum([]byte("data_hash")),
  235. ValidatorsHash: nil,
  236. NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")),
  237. ConsensusHash: tmhash.Sum([]byte("consensus_hash")),
  238. AppHash: tmhash.Sum([]byte("app_hash")),
  239. LastResultsHash: tmhash.Sum([]byte("last_results_hash")),
  240. EvidenceHash: tmhash.Sum([]byte("evidence_hash")),
  241. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  242. }, nil},
  243. }
  244. for _, tc := range testCases {
  245. tc := tc
  246. t.Run(tc.desc, func(t *testing.T) {
  247. assert.Equal(t, tc.expectHash, tc.header.Hash())
  248. // We also make sure that all fields are hashed in struct order, and that all
  249. // fields in the test struct are non-zero.
  250. if tc.header != nil && tc.expectHash != nil {
  251. byteSlices := [][]byte{}
  252. s := reflect.ValueOf(*tc.header)
  253. for i := 0; i < s.NumField(); i++ {
  254. f := s.Field(i)
  255. assert.False(t, f.IsZero(), "Found zero-valued field %v",
  256. s.Type().Field(i).Name)
  257. byteSlices = append(byteSlices, cdcEncode(f.Interface()))
  258. }
  259. assert.Equal(t,
  260. cmn.HexBytes(merkle.SimpleHashFromByteSlices(byteSlices)), tc.header.Hash())
  261. }
  262. })
  263. }
  264. }
  265. func TestMaxHeaderBytes(t *testing.T) {
  266. // Construct a UTF-8 string of MaxChainIDLen length using the supplementary
  267. // characters.
  268. // Each supplementary character takes 4 bytes.
  269. // http://www.i18nguy.com/unicode/supplementary-test.html
  270. maxChainID := ""
  271. for i := 0; i < MaxChainIDLen; i++ {
  272. maxChainID += "𠜎"
  273. }
  274. // time is varint encoded so need to pick the max.
  275. // year int, month Month, day, hour, min, sec, nsec int, loc *Location
  276. timestamp := time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC)
  277. h := Header{
  278. Version: version.Consensus{Block: math.MaxInt64, App: math.MaxInt64},
  279. ChainID: maxChainID,
  280. Height: math.MaxInt64,
  281. Time: timestamp,
  282. LastBlockID: makeBlockID(make([]byte, tmhash.Size), math.MaxInt64, make([]byte, tmhash.Size)),
  283. LastCommitHash: tmhash.Sum([]byte("last_commit_hash")),
  284. DataHash: tmhash.Sum([]byte("data_hash")),
  285. ValidatorsHash: tmhash.Sum([]byte("validators_hash")),
  286. NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")),
  287. ConsensusHash: tmhash.Sum([]byte("consensus_hash")),
  288. AppHash: tmhash.Sum([]byte("app_hash")),
  289. LastResultsHash: tmhash.Sum([]byte("last_results_hash")),
  290. EvidenceHash: tmhash.Sum([]byte("evidence_hash")),
  291. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  292. }
  293. bz, err := cdc.MarshalBinaryLengthPrefixed(h)
  294. require.NoError(t, err)
  295. assert.EqualValues(t, MaxHeaderBytes, int64(len(bz)))
  296. }
  297. func randCommit() *Commit {
  298. lastID := makeBlockIDRandom()
  299. h := int64(3)
  300. voteSet, _, vals := randVoteSet(h-1, 1, PrecommitType, 10, 1)
  301. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals)
  302. if err != nil {
  303. panic(err)
  304. }
  305. return commit
  306. }
  307. func hexBytesFromString(s string) cmn.HexBytes {
  308. b, err := hex.DecodeString(s)
  309. if err != nil {
  310. panic(err)
  311. }
  312. return cmn.HexBytes(b)
  313. }
  314. func TestBlockMaxDataBytes(t *testing.T) {
  315. testCases := []struct {
  316. maxBytes int64
  317. valsCount int
  318. evidenceCount int
  319. panics bool
  320. result int64
  321. }{
  322. 0: {-10, 1, 0, true, 0},
  323. 1: {10, 1, 0, true, 0},
  324. 2: {865, 1, 0, true, 0},
  325. 3: {866, 1, 0, false, 0},
  326. 4: {867, 1, 0, false, 1},
  327. }
  328. for i, tc := range testCases {
  329. tc := tc
  330. if tc.panics {
  331. assert.Panics(t, func() {
  332. MaxDataBytes(tc.maxBytes, tc.valsCount, tc.evidenceCount)
  333. }, "#%v", i)
  334. } else {
  335. assert.Equal(t,
  336. tc.result,
  337. MaxDataBytes(tc.maxBytes, tc.valsCount, tc.evidenceCount),
  338. "#%v", i)
  339. }
  340. }
  341. }
  342. func TestBlockMaxDataBytesUnknownEvidence(t *testing.T) {
  343. testCases := []struct {
  344. maxBytes int64
  345. valsCount int
  346. panics bool
  347. result int64
  348. }{
  349. 0: {-10, 1, true, 0},
  350. 1: {10, 1, true, 0},
  351. 2: {961, 1, true, 0},
  352. 3: {962, 1, false, 0},
  353. 4: {963, 1, false, 1},
  354. }
  355. for i, tc := range testCases {
  356. tc := tc
  357. if tc.panics {
  358. assert.Panics(t, func() {
  359. MaxDataBytesUnknownEvidence(tc.maxBytes, tc.valsCount)
  360. }, "#%v", i)
  361. } else {
  362. assert.Equal(t,
  363. tc.result,
  364. MaxDataBytesUnknownEvidence(tc.maxBytes, tc.valsCount),
  365. "#%v", i)
  366. }
  367. }
  368. }
  369. func TestCommitToVoteSet(t *testing.T) {
  370. lastID := makeBlockIDRandom()
  371. h := int64(3)
  372. voteSet, valSet, vals := randVoteSet(h-1, 1, PrecommitType, 10, 1)
  373. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals)
  374. assert.NoError(t, err)
  375. chainID := voteSet.ChainID()
  376. voteSet2 := CommitToVoteSet(chainID, commit, valSet)
  377. for i := 0; i < len(vals); i++ {
  378. vote1 := voteSet.GetByIndex(i)
  379. vote2 := voteSet2.GetByIndex(i)
  380. vote3 := commit.GetVote(i)
  381. vote1bz := cdc.MustMarshalBinaryBare(vote1)
  382. vote2bz := cdc.MustMarshalBinaryBare(vote2)
  383. vote3bz := cdc.MustMarshalBinaryBare(vote3)
  384. assert.Equal(t, vote1bz, vote2bz)
  385. assert.Equal(t, vote1bz, vote3bz)
  386. }
  387. }
  388. func TestCommitToVoteSetWithVotesForAnotherBlockOrNilBlock(t *testing.T) {
  389. blockID := makeBlockID([]byte("blockhash"), 1000, []byte("partshash"))
  390. blockID2 := makeBlockID([]byte("blockhash2"), 1000, []byte("partshash"))
  391. blockID3 := makeBlockID([]byte("blockhash3"), 10000, []byte("partshash"))
  392. height := int64(3)
  393. round := 1
  394. type commitVoteTest struct {
  395. blockIDs []BlockID
  396. numVotes []int // must sum to numValidators
  397. numValidators int
  398. valid bool
  399. }
  400. testCases := []commitVoteTest{
  401. {[]BlockID{blockID, blockID2, blockID3}, []int{8, 1, 1}, 10, true},
  402. {[]BlockID{blockID, blockID2, blockID3}, []int{67, 20, 13}, 100, true},
  403. {[]BlockID{blockID, blockID2, blockID3}, []int{1, 1, 1}, 3, false},
  404. {[]BlockID{blockID, blockID2, blockID3}, []int{3, 1, 1}, 5, false},
  405. {[]BlockID{blockID, {}}, []int{67, 33}, 100, true},
  406. {[]BlockID{blockID, blockID2, {}}, []int{10, 5, 5}, 20, false},
  407. }
  408. for _, tc := range testCases {
  409. voteSet, valSet, vals := randVoteSet(height-1, 1, PrecommitType, tc.numValidators, 1)
  410. vi := 0
  411. for n := range tc.blockIDs {
  412. for i := 0; i < tc.numVotes[n]; i++ {
  413. addr := vals[vi].GetPubKey().Address()
  414. vote := &Vote{
  415. ValidatorAddress: addr,
  416. ValidatorIndex: vi,
  417. Height: height - 1,
  418. Round: round,
  419. Type: PrecommitType,
  420. BlockID: tc.blockIDs[n],
  421. Timestamp: tmtime.Now(),
  422. }
  423. _, err := signAddVote(vals[vi], vote, voteSet)
  424. assert.NoError(t, err)
  425. vi++
  426. }
  427. }
  428. if tc.valid {
  429. commit := voteSet.MakeCommit() // panics without > 2/3 valid votes
  430. assert.NotNil(t, commit)
  431. err := valSet.VerifyCommit(voteSet.ChainID(), blockID, height-1, commit)
  432. assert.Nil(t, err)
  433. } else {
  434. assert.Panics(t, func() { voteSet.MakeCommit() })
  435. }
  436. }
  437. }
  438. func TestSignedHeaderValidateBasic(t *testing.T) {
  439. commit := randCommit()
  440. chainID := "𠜎"
  441. timestamp := time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC)
  442. h := Header{
  443. Version: version.Consensus{Block: math.MaxInt64, App: math.MaxInt64},
  444. ChainID: chainID,
  445. Height: commit.Height(),
  446. Time: timestamp,
  447. LastBlockID: commit.BlockID,
  448. LastCommitHash: commit.Hash(),
  449. DataHash: commit.Hash(),
  450. ValidatorsHash: commit.Hash(),
  451. NextValidatorsHash: commit.Hash(),
  452. ConsensusHash: commit.Hash(),
  453. AppHash: commit.Hash(),
  454. LastResultsHash: commit.Hash(),
  455. EvidenceHash: commit.Hash(),
  456. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  457. }
  458. validSignedHeader := SignedHeader{Header: &h, Commit: commit}
  459. validSignedHeader.Commit.BlockID.Hash = validSignedHeader.Hash()
  460. invalidSignedHeader := SignedHeader{}
  461. testCases := []struct {
  462. testName string
  463. shHeader *Header
  464. shCommit *Commit
  465. expectErr bool
  466. }{
  467. {"Valid Signed Header", validSignedHeader.Header, validSignedHeader.Commit, false},
  468. {"Invalid Signed Header", invalidSignedHeader.Header, validSignedHeader.Commit, true},
  469. {"Invalid Signed Header", validSignedHeader.Header, invalidSignedHeader.Commit, true},
  470. }
  471. for _, tc := range testCases {
  472. tc := tc
  473. t.Run(tc.testName, func(t *testing.T) {
  474. sh := SignedHeader{
  475. Header: tc.shHeader,
  476. Commit: tc.shCommit,
  477. }
  478. assert.Equal(
  479. t,
  480. tc.expectErr,
  481. sh.ValidateBasic(validSignedHeader.Header.ChainID) != nil,
  482. "Validate Basic had an unexpected result",
  483. )
  484. })
  485. }
  486. }
  487. func TestBlockIDValidateBasic(t *testing.T) {
  488. validBlockID := BlockID{
  489. Hash: cmn.HexBytes{},
  490. PartsHeader: PartSetHeader{
  491. Total: 1,
  492. Hash: cmn.HexBytes{},
  493. },
  494. }
  495. invalidBlockID := BlockID{
  496. Hash: []byte{0},
  497. PartsHeader: PartSetHeader{
  498. Total: -1,
  499. Hash: cmn.HexBytes{},
  500. },
  501. }
  502. testCases := []struct {
  503. testName string
  504. blockIDHash cmn.HexBytes
  505. blockIDPartsHeader PartSetHeader
  506. expectErr bool
  507. }{
  508. {"Valid BlockID", validBlockID.Hash, validBlockID.PartsHeader, false},
  509. {"Invalid BlockID", invalidBlockID.Hash, validBlockID.PartsHeader, true},
  510. {"Invalid BlockID", validBlockID.Hash, invalidBlockID.PartsHeader, true},
  511. }
  512. for _, tc := range testCases {
  513. tc := tc
  514. t.Run(tc.testName, func(t *testing.T) {
  515. blockID := BlockID{
  516. Hash: tc.blockIDHash,
  517. PartsHeader: tc.blockIDPartsHeader,
  518. }
  519. assert.Equal(t, tc.expectErr, blockID.ValidateBasic() != nil, "Validate Basic had an unexpected result")
  520. })
  521. }
  522. }