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.

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