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.

597 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.Signatures = commit.Signatures[: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(512)
  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. var (
  141. blockHash = make([]byte, tmhash.Size)
  142. partSetHash = make([]byte, tmhash.Size)
  143. )
  144. rand.Read(blockHash) //nolint: gosec
  145. rand.Read(partSetHash) //nolint: gosec
  146. return BlockID{blockHash, PartSetHeader{123, partSetHash}}
  147. }
  148. func makeBlockID(hash []byte, partSetSize int, partSetHash []byte) BlockID {
  149. var (
  150. h = make([]byte, tmhash.Size)
  151. psH = make([]byte, tmhash.Size)
  152. )
  153. copy(h, hash)
  154. copy(psH, partSetHash)
  155. return BlockID{
  156. Hash: h,
  157. PartsHeader: PartSetHeader{
  158. Total: partSetSize,
  159. Hash: psH,
  160. },
  161. }
  162. }
  163. var nilBytes []byte
  164. func TestNilHeaderHashDoesntCrash(t *testing.T) {
  165. assert.Equal(t, []byte((*Header)(nil).Hash()), nilBytes)
  166. assert.Equal(t, []byte((new(Header)).Hash()), nilBytes)
  167. }
  168. func TestNilDataHashDoesntCrash(t *testing.T) {
  169. assert.Equal(t, []byte((*Data)(nil).Hash()), nilBytes)
  170. assert.Equal(t, []byte(new(Data).Hash()), nilBytes)
  171. }
  172. func TestCommit(t *testing.T) {
  173. lastID := makeBlockIDRandom()
  174. h := int64(3)
  175. voteSet, _, vals := randVoteSet(h-1, 1, PrecommitType, 10, 1)
  176. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals)
  177. require.NoError(t, err)
  178. assert.Equal(t, h-1, commit.Height)
  179. assert.Equal(t, 1, commit.Round)
  180. assert.Equal(t, PrecommitType, SignedMsgType(commit.Type()))
  181. if commit.Size() <= 0 {
  182. t.Fatalf("commit %v has a zero or negative size: %d", commit, commit.Size())
  183. }
  184. require.NotNil(t, commit.BitArray())
  185. assert.Equal(t, cmn.NewBitArray(10).Size(), commit.BitArray().Size())
  186. assert.Equal(t, voteSet.GetByIndex(0), commit.GetByIndex(0))
  187. assert.True(t, commit.IsCommit())
  188. }
  189. func TestCommitValidateBasic(t *testing.T) {
  190. testCases := []struct {
  191. testName string
  192. malleateCommit func(*Commit)
  193. expectErr bool
  194. }{
  195. {"Random Commit", func(com *Commit) {}, false},
  196. {"Incorrect signature", func(com *Commit) { com.Signatures[0].Signature = []byte{0} }, false},
  197. {"Incorrect height", func(com *Commit) { com.Height = int64(-100) }, true},
  198. {"Incorrect round", func(com *Commit) { com.Round = -100 }, true},
  199. }
  200. for _, tc := range testCases {
  201. tc := tc
  202. t.Run(tc.testName, func(t *testing.T) {
  203. com := randCommit()
  204. tc.malleateCommit(com)
  205. assert.Equal(t, tc.expectErr, com.ValidateBasic() != nil, "Validate Basic had an unexpected result")
  206. })
  207. }
  208. }
  209. func TestHeaderHash(t *testing.T) {
  210. testCases := []struct {
  211. desc string
  212. header *Header
  213. expectHash cmn.HexBytes
  214. }{
  215. {"Generates expected hash", &Header{
  216. Version: version.Consensus{Block: 1, App: 2},
  217. ChainID: "chainId",
  218. Height: 3,
  219. Time: time.Date(2019, 10, 13, 16, 14, 44, 0, time.UTC),
  220. LastBlockID: makeBlockID(make([]byte, tmhash.Size), 6, make([]byte, tmhash.Size)),
  221. LastCommitHash: tmhash.Sum([]byte("last_commit_hash")),
  222. DataHash: tmhash.Sum([]byte("data_hash")),
  223. ValidatorsHash: tmhash.Sum([]byte("validators_hash")),
  224. NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")),
  225. ConsensusHash: tmhash.Sum([]byte("consensus_hash")),
  226. AppHash: tmhash.Sum([]byte("app_hash")),
  227. LastResultsHash: tmhash.Sum([]byte("last_results_hash")),
  228. EvidenceHash: tmhash.Sum([]byte("evidence_hash")),
  229. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  230. }, hexBytesFromString("ABDC78921B18A47EE6BEF5E31637BADB0F3E587E3C0F4DB2D1E93E9FF0533862")},
  231. {"nil header yields nil", nil, nil},
  232. {"nil ValidatorsHash yields nil", &Header{
  233. Version: version.Consensus{Block: 1, App: 2},
  234. ChainID: "chainId",
  235. Height: 3,
  236. Time: time.Date(2019, 10, 13, 16, 14, 44, 0, time.UTC),
  237. LastBlockID: makeBlockID(make([]byte, tmhash.Size), 6, make([]byte, tmhash.Size)),
  238. LastCommitHash: tmhash.Sum([]byte("last_commit_hash")),
  239. DataHash: tmhash.Sum([]byte("data_hash")),
  240. ValidatorsHash: nil,
  241. NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")),
  242. ConsensusHash: tmhash.Sum([]byte("consensus_hash")),
  243. AppHash: tmhash.Sum([]byte("app_hash")),
  244. LastResultsHash: tmhash.Sum([]byte("last_results_hash")),
  245. EvidenceHash: tmhash.Sum([]byte("evidence_hash")),
  246. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  247. }, nil},
  248. }
  249. for _, tc := range testCases {
  250. tc := tc
  251. t.Run(tc.desc, func(t *testing.T) {
  252. assert.Equal(t, tc.expectHash, tc.header.Hash())
  253. // We also make sure that all fields are hashed in struct order, and that all
  254. // fields in the test struct are non-zero.
  255. if tc.header != nil && tc.expectHash != nil {
  256. byteSlices := [][]byte{}
  257. s := reflect.ValueOf(*tc.header)
  258. for i := 0; i < s.NumField(); i++ {
  259. f := s.Field(i)
  260. assert.False(t, f.IsZero(), "Found zero-valued field %v",
  261. s.Type().Field(i).Name)
  262. byteSlices = append(byteSlices, cdcEncode(f.Interface()))
  263. }
  264. assert.Equal(t,
  265. cmn.HexBytes(merkle.SimpleHashFromByteSlices(byteSlices)), tc.header.Hash())
  266. }
  267. })
  268. }
  269. }
  270. func TestMaxHeaderBytes(t *testing.T) {
  271. // Construct a UTF-8 string of MaxChainIDLen length using the supplementary
  272. // characters.
  273. // Each supplementary character takes 4 bytes.
  274. // http://www.i18nguy.com/unicode/supplementary-test.html
  275. maxChainID := ""
  276. for i := 0; i < MaxChainIDLen; i++ {
  277. maxChainID += "𠜎"
  278. }
  279. // time is varint encoded so need to pick the max.
  280. // year int, month Month, day, hour, min, sec, nsec int, loc *Location
  281. timestamp := time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC)
  282. h := Header{
  283. Version: version.Consensus{Block: math.MaxInt64, App: math.MaxInt64},
  284. ChainID: maxChainID,
  285. Height: math.MaxInt64,
  286. Time: timestamp,
  287. LastBlockID: makeBlockID(make([]byte, tmhash.Size), math.MaxInt64, make([]byte, tmhash.Size)),
  288. LastCommitHash: tmhash.Sum([]byte("last_commit_hash")),
  289. DataHash: tmhash.Sum([]byte("data_hash")),
  290. ValidatorsHash: tmhash.Sum([]byte("validators_hash")),
  291. NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")),
  292. ConsensusHash: tmhash.Sum([]byte("consensus_hash")),
  293. AppHash: tmhash.Sum([]byte("app_hash")),
  294. LastResultsHash: tmhash.Sum([]byte("last_results_hash")),
  295. EvidenceHash: tmhash.Sum([]byte("evidence_hash")),
  296. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  297. }
  298. bz, err := cdc.MarshalBinaryLengthPrefixed(h)
  299. require.NoError(t, err)
  300. assert.EqualValues(t, MaxHeaderBytes, int64(len(bz)))
  301. }
  302. func randCommit() *Commit {
  303. lastID := makeBlockIDRandom()
  304. h := int64(3)
  305. voteSet, _, vals := randVoteSet(h-1, 1, PrecommitType, 10, 1)
  306. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals)
  307. if err != nil {
  308. panic(err)
  309. }
  310. return commit
  311. }
  312. func hexBytesFromString(s string) cmn.HexBytes {
  313. b, err := hex.DecodeString(s)
  314. if err != nil {
  315. panic(err)
  316. }
  317. return cmn.HexBytes(b)
  318. }
  319. func TestBlockMaxDataBytes(t *testing.T) {
  320. testCases := []struct {
  321. maxBytes int64
  322. valsCount int
  323. evidenceCount int
  324. panics bool
  325. result int64
  326. }{
  327. 0: {-10, 1, 0, true, 0},
  328. 1: {10, 1, 0, true, 0},
  329. 2: {865, 1, 0, true, 0},
  330. 3: {866, 1, 0, false, 0},
  331. 4: {867, 1, 0, false, 1},
  332. }
  333. for i, tc := range testCases {
  334. tc := tc
  335. if tc.panics {
  336. assert.Panics(t, func() {
  337. MaxDataBytes(tc.maxBytes, tc.valsCount, tc.evidenceCount)
  338. }, "#%v", i)
  339. } else {
  340. assert.Equal(t,
  341. tc.result,
  342. MaxDataBytes(tc.maxBytes, tc.valsCount, tc.evidenceCount),
  343. "#%v", i)
  344. }
  345. }
  346. }
  347. func TestBlockMaxDataBytesUnknownEvidence(t *testing.T) {
  348. testCases := []struct {
  349. maxBytes int64
  350. valsCount int
  351. panics bool
  352. result int64
  353. }{
  354. 0: {-10, 1, true, 0},
  355. 1: {10, 1, true, 0},
  356. 2: {961, 1, true, 0},
  357. 3: {962, 1, false, 0},
  358. 4: {963, 1, false, 1},
  359. }
  360. for i, tc := range testCases {
  361. tc := tc
  362. if tc.panics {
  363. assert.Panics(t, func() {
  364. MaxDataBytesUnknownEvidence(tc.maxBytes, tc.valsCount)
  365. }, "#%v", i)
  366. } else {
  367. assert.Equal(t,
  368. tc.result,
  369. MaxDataBytesUnknownEvidence(tc.maxBytes, tc.valsCount),
  370. "#%v", i)
  371. }
  372. }
  373. }
  374. func TestCommitToVoteSet(t *testing.T) {
  375. lastID := makeBlockIDRandom()
  376. h := int64(3)
  377. voteSet, valSet, vals := randVoteSet(h-1, 1, PrecommitType, 10, 1)
  378. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals)
  379. assert.NoError(t, err)
  380. chainID := voteSet.ChainID()
  381. voteSet2 := CommitToVoteSet(chainID, commit, valSet)
  382. for i := 0; i < len(vals); i++ {
  383. vote1 := voteSet.GetByIndex(i)
  384. vote2 := voteSet2.GetByIndex(i)
  385. vote3 := commit.GetVote(i)
  386. vote1bz := cdc.MustMarshalBinaryBare(vote1)
  387. vote2bz := cdc.MustMarshalBinaryBare(vote2)
  388. vote3bz := cdc.MustMarshalBinaryBare(vote3)
  389. assert.Equal(t, vote1bz, vote2bz)
  390. assert.Equal(t, vote1bz, vote3bz)
  391. }
  392. }
  393. func TestCommitToVoteSetWithVotesForNilBlock(t *testing.T) {
  394. blockID := makeBlockID([]byte("blockhash"), 1000, []byte("partshash"))
  395. const (
  396. height = int64(3)
  397. round = 0
  398. )
  399. type commitVoteTest struct {
  400. blockIDs []BlockID
  401. numVotes []int // must sum to numValidators
  402. numValidators int
  403. valid bool
  404. }
  405. testCases := []commitVoteTest{
  406. {[]BlockID{blockID, {}}, []int{67, 33}, 100, true},
  407. }
  408. for _, tc := range testCases {
  409. voteSet, valSet, vals := randVoteSet(height-1, round, 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. added, err := signAddVote(vals[vi], vote, voteSet)
  424. assert.NoError(t, err)
  425. assert.True(t, added)
  426. vi++
  427. }
  428. }
  429. if tc.valid {
  430. commit := voteSet.MakeCommit() // panics without > 2/3 valid votes
  431. assert.NotNil(t, commit)
  432. err := valSet.VerifyCommit(voteSet.ChainID(), blockID, height-1, commit)
  433. assert.Nil(t, err)
  434. } else {
  435. assert.Panics(t, func() { voteSet.MakeCommit() })
  436. }
  437. }
  438. }
  439. func TestSignedHeaderValidateBasic(t *testing.T) {
  440. commit := randCommit()
  441. chainID := "𠜎"
  442. timestamp := time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC)
  443. h := Header{
  444. Version: version.Consensus{Block: math.MaxInt64, App: math.MaxInt64},
  445. ChainID: chainID,
  446. Height: commit.Height,
  447. Time: timestamp,
  448. LastBlockID: commit.BlockID,
  449. LastCommitHash: commit.Hash(),
  450. DataHash: commit.Hash(),
  451. ValidatorsHash: commit.Hash(),
  452. NextValidatorsHash: commit.Hash(),
  453. ConsensusHash: commit.Hash(),
  454. AppHash: commit.Hash(),
  455. LastResultsHash: commit.Hash(),
  456. EvidenceHash: commit.Hash(),
  457. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  458. }
  459. validSignedHeader := SignedHeader{Header: &h, Commit: commit}
  460. validSignedHeader.Commit.BlockID.Hash = validSignedHeader.Hash()
  461. invalidSignedHeader := SignedHeader{}
  462. testCases := []struct {
  463. testName string
  464. shHeader *Header
  465. shCommit *Commit
  466. expectErr bool
  467. }{
  468. {"Valid Signed Header", validSignedHeader.Header, validSignedHeader.Commit, false},
  469. {"Invalid Signed Header", invalidSignedHeader.Header, validSignedHeader.Commit, true},
  470. {"Invalid Signed Header", validSignedHeader.Header, invalidSignedHeader.Commit, true},
  471. }
  472. for _, tc := range testCases {
  473. tc := tc
  474. t.Run(tc.testName, func(t *testing.T) {
  475. sh := SignedHeader{
  476. Header: tc.shHeader,
  477. Commit: tc.shCommit,
  478. }
  479. assert.Equal(
  480. t,
  481. tc.expectErr,
  482. sh.ValidateBasic(validSignedHeader.Header.ChainID) != nil,
  483. "Validate Basic had an unexpected result",
  484. )
  485. })
  486. }
  487. }
  488. func TestBlockIDValidateBasic(t *testing.T) {
  489. validBlockID := BlockID{
  490. Hash: cmn.HexBytes{},
  491. PartsHeader: PartSetHeader{
  492. Total: 1,
  493. Hash: cmn.HexBytes{},
  494. },
  495. }
  496. invalidBlockID := BlockID{
  497. Hash: []byte{0},
  498. PartsHeader: PartSetHeader{
  499. Total: -1,
  500. Hash: cmn.HexBytes{},
  501. },
  502. }
  503. testCases := []struct {
  504. testName string
  505. blockIDHash cmn.HexBytes
  506. blockIDPartsHeader PartSetHeader
  507. expectErr bool
  508. }{
  509. {"Valid BlockID", validBlockID.Hash, validBlockID.PartsHeader, false},
  510. {"Invalid BlockID", invalidBlockID.Hash, validBlockID.PartsHeader, true},
  511. {"Invalid BlockID", validBlockID.Hash, invalidBlockID.PartsHeader, true},
  512. }
  513. for _, tc := range testCases {
  514. tc := tc
  515. t.Run(tc.testName, func(t *testing.T) {
  516. blockID := BlockID{
  517. Hash: tc.blockIDHash,
  518. PartsHeader: tc.blockIDPartsHeader,
  519. }
  520. assert.Equal(t, tc.expectErr, blockID.ValidateBasic() != nil, "Validate Basic had an unexpected result")
  521. })
  522. }
  523. }