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.

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