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.

604 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. {"Increase NumTxs", func(blk *Block) { blk.NumTxs++ }, true},
  59. {"Remove 1/2 the commits", func(blk *Block) {
  60. blk.LastCommit.Precommits = commit.Precommits[: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 = cmn.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(1024)
  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. blockHash := make([]byte, tmhash.Size)
  142. partSetHash := make([]byte, tmhash.Size)
  143. rand.Read(blockHash) //nolint: gosec
  144. rand.Read(partSetHash) //nolint: gosec
  145. blockPartsHeader := PartSetHeader{123, partSetHash}
  146. return BlockID{blockHash, blockPartsHeader}
  147. }
  148. func makeBlockID(hash []byte, partSetSize int, partSetHash []byte) BlockID {
  149. return BlockID{
  150. Hash: hash,
  151. PartsHeader: PartSetHeader{
  152. Total: partSetSize,
  153. Hash: partSetHash,
  154. },
  155. }
  156. }
  157. var nilBytes []byte
  158. func TestNilHeaderHashDoesntCrash(t *testing.T) {
  159. assert.Equal(t, []byte((*Header)(nil).Hash()), nilBytes)
  160. assert.Equal(t, []byte((new(Header)).Hash()), nilBytes)
  161. }
  162. func TestNilDataHashDoesntCrash(t *testing.T) {
  163. assert.Equal(t, []byte((*Data)(nil).Hash()), nilBytes)
  164. assert.Equal(t, []byte(new(Data).Hash()), nilBytes)
  165. }
  166. func TestCommit(t *testing.T) {
  167. lastID := makeBlockIDRandom()
  168. h := int64(3)
  169. voteSet, _, vals := randVoteSet(h-1, 1, PrecommitType, 10, 1)
  170. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals)
  171. require.NoError(t, err)
  172. assert.Equal(t, h-1, commit.Height())
  173. assert.Equal(t, 1, commit.Round())
  174. assert.Equal(t, PrecommitType, SignedMsgType(commit.Type()))
  175. if commit.Size() <= 0 {
  176. t.Fatalf("commit %v has a zero or negative size: %d", commit, commit.Size())
  177. }
  178. require.NotNil(t, commit.BitArray())
  179. assert.Equal(t, cmn.NewBitArray(10).Size(), commit.BitArray().Size())
  180. assert.Equal(t, voteSet.GetByIndex(0), commit.GetByIndex(0))
  181. assert.True(t, commit.IsCommit())
  182. }
  183. func TestCommitValidateBasic(t *testing.T) {
  184. testCases := []struct {
  185. testName string
  186. malleateCommit func(*Commit)
  187. expectErr bool
  188. }{
  189. {"Random Commit", func(com *Commit) {}, false},
  190. {"Nil precommit", func(com *Commit) { com.Precommits[0] = nil }, false},
  191. {"Incorrect signature", func(com *Commit) { com.Precommits[0].Signature = []byte{0} }, false},
  192. {"Incorrect type", func(com *Commit) { com.Precommits[0].Type = PrevoteType }, true},
  193. {"Incorrect height", func(com *Commit) { com.Precommits[0].Height = int64(100) }, true},
  194. {"Incorrect round", func(com *Commit) { com.Precommits[0].Round = 100 }, true},
  195. }
  196. for _, tc := range testCases {
  197. tc := tc
  198. t.Run(tc.testName, func(t *testing.T) {
  199. com := randCommit()
  200. tc.malleateCommit(com)
  201. assert.Equal(t, tc.expectErr, com.ValidateBasic() != nil, "Validate Basic had an unexpected result")
  202. })
  203. }
  204. }
  205. func TestHeaderHash(t *testing.T) {
  206. testCases := []struct {
  207. desc string
  208. header *Header
  209. expectHash cmn.HexBytes
  210. }{
  211. {"Generates expected hash", &Header{
  212. Version: version.Consensus{Block: 1, App: 2},
  213. ChainID: "chainId",
  214. Height: 3,
  215. Time: time.Date(2019, 10, 13, 16, 14, 44, 0, time.UTC),
  216. NumTxs: 4,
  217. TotalTxs: 5,
  218. LastBlockID: makeBlockID(make([]byte, tmhash.Size), 6, make([]byte, tmhash.Size)),
  219. LastCommitHash: tmhash.Sum([]byte("last_commit_hash")),
  220. DataHash: tmhash.Sum([]byte("data_hash")),
  221. ValidatorsHash: tmhash.Sum([]byte("validators_hash")),
  222. NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")),
  223. ConsensusHash: tmhash.Sum([]byte("consensus_hash")),
  224. AppHash: tmhash.Sum([]byte("app_hash")),
  225. LastResultsHash: tmhash.Sum([]byte("last_results_hash")),
  226. EvidenceHash: tmhash.Sum([]byte("evidence_hash")),
  227. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  228. }, hexBytesFromString("A37A7A69D89D3A66D599B0914A53F959EFE490EE9B449C95852F6FB331D58D07")},
  229. {"nil header yields nil", nil, nil},
  230. {"nil ValidatorsHash yields nil", &Header{
  231. Version: version.Consensus{Block: 1, App: 2},
  232. ChainID: "chainId",
  233. Height: 3,
  234. Time: time.Date(2019, 10, 13, 16, 14, 44, 0, time.UTC),
  235. NumTxs: 4,
  236. TotalTxs: 5,
  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. NumTxs: math.MaxInt64,
  288. TotalTxs: math.MaxInt64,
  289. LastBlockID: makeBlockID(make([]byte, tmhash.Size), math.MaxInt64, make([]byte, tmhash.Size)),
  290. LastCommitHash: tmhash.Sum([]byte("last_commit_hash")),
  291. DataHash: tmhash.Sum([]byte("data_hash")),
  292. ValidatorsHash: tmhash.Sum([]byte("validators_hash")),
  293. NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")),
  294. ConsensusHash: tmhash.Sum([]byte("consensus_hash")),
  295. AppHash: tmhash.Sum([]byte("app_hash")),
  296. LastResultsHash: tmhash.Sum([]byte("last_results_hash")),
  297. EvidenceHash: tmhash.Sum([]byte("evidence_hash")),
  298. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  299. }
  300. bz, err := cdc.MarshalBinaryLengthPrefixed(h)
  301. require.NoError(t, err)
  302. assert.EqualValues(t, MaxHeaderBytes, len(bz))
  303. }
  304. func randCommit() *Commit {
  305. lastID := makeBlockIDRandom()
  306. h := int64(3)
  307. voteSet, _, vals := randVoteSet(h-1, 1, PrecommitType, 10, 1)
  308. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals)
  309. if err != nil {
  310. panic(err)
  311. }
  312. return commit
  313. }
  314. func hexBytesFromString(s string) cmn.HexBytes {
  315. b, err := hex.DecodeString(s)
  316. if err != nil {
  317. panic(err)
  318. }
  319. return cmn.HexBytes(b)
  320. }
  321. func TestBlockMaxDataBytes(t *testing.T) {
  322. testCases := []struct {
  323. maxBytes int64
  324. valsCount int
  325. evidenceCount int
  326. panics bool
  327. result int64
  328. }{
  329. 0: {-10, 1, 0, true, 0},
  330. 1: {10, 1, 0, true, 0},
  331. 2: {886, 1, 0, true, 0},
  332. 3: {887, 1, 0, false, 0},
  333. 4: {888, 1, 0, false, 1},
  334. }
  335. for i, tc := range testCases {
  336. tc := tc
  337. if tc.panics {
  338. assert.Panics(t, func() {
  339. MaxDataBytes(tc.maxBytes, tc.valsCount, tc.evidenceCount)
  340. }, "#%v", i)
  341. } else {
  342. assert.Equal(t,
  343. tc.result,
  344. MaxDataBytes(tc.maxBytes, tc.valsCount, tc.evidenceCount),
  345. "#%v", i)
  346. }
  347. }
  348. }
  349. func TestBlockMaxDataBytesUnknownEvidence(t *testing.T) {
  350. testCases := []struct {
  351. maxBytes int64
  352. valsCount int
  353. panics bool
  354. result int64
  355. }{
  356. 0: {-10, 1, true, 0},
  357. 1: {10, 1, true, 0},
  358. 2: {984, 1, true, 0},
  359. 3: {985, 1, false, 0},
  360. 4: {986, 1, false, 1},
  361. }
  362. for i, tc := range testCases {
  363. tc := tc
  364. if tc.panics {
  365. assert.Panics(t, func() {
  366. MaxDataBytesUnknownEvidence(tc.maxBytes, tc.valsCount)
  367. }, "#%v", i)
  368. } else {
  369. assert.Equal(t,
  370. tc.result,
  371. MaxDataBytesUnknownEvidence(tc.maxBytes, tc.valsCount),
  372. "#%v", i)
  373. }
  374. }
  375. }
  376. func TestCommitToVoteSet(t *testing.T) {
  377. lastID := makeBlockIDRandom()
  378. h := int64(3)
  379. voteSet, valSet, vals := randVoteSet(h-1, 1, PrecommitType, 10, 1)
  380. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals)
  381. assert.NoError(t, err)
  382. chainID := voteSet.ChainID()
  383. voteSet2 := CommitToVoteSet(chainID, commit, valSet)
  384. for i := 0; i < len(vals); i++ {
  385. vote1 := voteSet.GetByIndex(i)
  386. vote2 := voteSet2.GetByIndex(i)
  387. vote3 := commit.GetVote(i)
  388. vote1bz := cdc.MustMarshalBinaryBare(vote1)
  389. vote2bz := cdc.MustMarshalBinaryBare(vote2)
  390. vote3bz := cdc.MustMarshalBinaryBare(vote3)
  391. assert.Equal(t, vote1bz, vote2bz)
  392. assert.Equal(t, vote1bz, vote3bz)
  393. }
  394. }
  395. func TestCommitToVoteSetWithVotesForAnotherBlockOrNilBlock(t *testing.T) {
  396. blockID := makeBlockID([]byte("blockhash"), 1000, []byte("partshash"))
  397. blockID2 := makeBlockID([]byte("blockhash2"), 1000, []byte("partshash"))
  398. blockID3 := makeBlockID([]byte("blockhash3"), 10000, []byte("partshash"))
  399. height := int64(3)
  400. round := 1
  401. type commitVoteTest struct {
  402. blockIDs []BlockID
  403. numVotes []int // must sum to numValidators
  404. numValidators int
  405. valid bool
  406. }
  407. testCases := []commitVoteTest{
  408. {[]BlockID{blockID, blockID2, blockID3}, []int{8, 1, 1}, 10, true},
  409. {[]BlockID{blockID, blockID2, blockID3}, []int{67, 20, 13}, 100, true},
  410. {[]BlockID{blockID, blockID2, blockID3}, []int{1, 1, 1}, 3, false},
  411. {[]BlockID{blockID, blockID2, blockID3}, []int{3, 1, 1}, 5, false},
  412. {[]BlockID{blockID, {}}, []int{67, 33}, 100, true},
  413. {[]BlockID{blockID, blockID2, {}}, []int{10, 5, 5}, 20, false},
  414. }
  415. for _, tc := range testCases {
  416. voteSet, valSet, vals := randVoteSet(height-1, 1, PrecommitType, tc.numValidators, 1)
  417. vi := 0
  418. for n := range tc.blockIDs {
  419. for i := 0; i < tc.numVotes[n]; i++ {
  420. addr := vals[vi].GetPubKey().Address()
  421. vote := &Vote{
  422. ValidatorAddress: addr,
  423. ValidatorIndex: vi,
  424. Height: height - 1,
  425. Round: round,
  426. Type: PrecommitType,
  427. BlockID: tc.blockIDs[n],
  428. Timestamp: tmtime.Now(),
  429. }
  430. _, err := signAddVote(vals[vi], vote, voteSet)
  431. assert.NoError(t, err)
  432. vi++
  433. }
  434. }
  435. if tc.valid {
  436. commit := voteSet.MakeCommit() // panics without > 2/3 valid votes
  437. assert.NotNil(t, commit)
  438. err := valSet.VerifyCommit(voteSet.ChainID(), blockID, height-1, commit)
  439. assert.Nil(t, err)
  440. } else {
  441. assert.Panics(t, func() { voteSet.MakeCommit() })
  442. }
  443. }
  444. }
  445. func TestSignedHeaderValidateBasic(t *testing.T) {
  446. commit := randCommit()
  447. chainID := "𠜎"
  448. timestamp := time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC)
  449. h := Header{
  450. Version: version.Consensus{Block: math.MaxInt64, App: math.MaxInt64},
  451. ChainID: chainID,
  452. Height: commit.Height(),
  453. Time: timestamp,
  454. NumTxs: math.MaxInt64,
  455. TotalTxs: math.MaxInt64,
  456. LastBlockID: commit.BlockID,
  457. LastCommitHash: commit.Hash(),
  458. DataHash: commit.Hash(),
  459. ValidatorsHash: commit.Hash(),
  460. NextValidatorsHash: commit.Hash(),
  461. ConsensusHash: commit.Hash(),
  462. AppHash: commit.Hash(),
  463. LastResultsHash: commit.Hash(),
  464. EvidenceHash: commit.Hash(),
  465. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  466. }
  467. validSignedHeader := SignedHeader{Header: &h, Commit: commit}
  468. validSignedHeader.Commit.BlockID.Hash = validSignedHeader.Hash()
  469. invalidSignedHeader := SignedHeader{}
  470. testCases := []struct {
  471. testName string
  472. shHeader *Header
  473. shCommit *Commit
  474. expectErr bool
  475. }{
  476. {"Valid Signed Header", validSignedHeader.Header, validSignedHeader.Commit, false},
  477. {"Invalid Signed Header", invalidSignedHeader.Header, validSignedHeader.Commit, true},
  478. {"Invalid Signed Header", validSignedHeader.Header, invalidSignedHeader.Commit, true},
  479. }
  480. for _, tc := range testCases {
  481. tc := tc
  482. t.Run(tc.testName, func(t *testing.T) {
  483. sh := SignedHeader{
  484. Header: tc.shHeader,
  485. Commit: tc.shCommit,
  486. }
  487. assert.Equal(
  488. t,
  489. tc.expectErr,
  490. sh.ValidateBasic(validSignedHeader.Header.ChainID) != nil,
  491. "Validate Basic had an unexpected result",
  492. )
  493. })
  494. }
  495. }
  496. func TestBlockIDValidateBasic(t *testing.T) {
  497. validBlockID := BlockID{
  498. Hash: cmn.HexBytes{},
  499. PartsHeader: PartSetHeader{
  500. Total: 1,
  501. Hash: cmn.HexBytes{},
  502. },
  503. }
  504. invalidBlockID := BlockID{
  505. Hash: []byte{0},
  506. PartsHeader: PartSetHeader{
  507. Total: -1,
  508. Hash: cmn.HexBytes{},
  509. },
  510. }
  511. testCases := []struct {
  512. testName string
  513. blockIDHash cmn.HexBytes
  514. blockIDPartsHeader PartSetHeader
  515. expectErr bool
  516. }{
  517. {"Valid BlockID", validBlockID.Hash, validBlockID.PartsHeader, false},
  518. {"Invalid BlockID", invalidBlockID.Hash, validBlockID.PartsHeader, true},
  519. {"Invalid BlockID", validBlockID.Hash, invalidBlockID.PartsHeader, true},
  520. }
  521. for _, tc := range testCases {
  522. tc := tc
  523. t.Run(tc.testName, func(t *testing.T) {
  524. blockID := BlockID{
  525. Hash: tc.blockIDHash,
  526. PartsHeader: tc.blockIDPartsHeader,
  527. }
  528. assert.Equal(t, tc.expectErr, blockID.ValidateBasic() != nil, "Validate Basic had an unexpected result")
  529. })
  530. }
  531. }