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.

738 lines
21 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, time.Now())
  34. require.NoError(t, err)
  35. ev := NewMockEvidence(h, time.Now(), 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, time.Now())
  49. require.NoError(t, err)
  50. ev := NewMockEvidence(h, time.Now(), 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, time.Now())
  104. require.NoError(t, err)
  105. ev := NewMockEvidence(h, time.Now(), 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, time.Now())
  117. require.NoError(t, err)
  118. ev := NewMockEvidence(h, time.Now(), 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)
  147. rand.Read(partSetHash)
  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, time.Now())
  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(time.Now())
  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(now time.Time) *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, now)
  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. maxEvidence uint32
  353. valsCount int
  354. panics bool
  355. result int64
  356. }{
  357. 0: {-10, 0, 1, true, 0},
  358. 1: {10, 0, 1, true, 0},
  359. 2: {865, 0, 1, true, 0},
  360. 3: {866, 0, 1, false, 0},
  361. 4: {1310, 1, 1, false, 0},
  362. 5: {1311, 1, 1, false, 1},
  363. }
  364. for i, tc := range testCases {
  365. tc := tc
  366. if tc.panics {
  367. assert.Panics(t, func() {
  368. MaxDataBytesUnknownEvidence(tc.maxBytes, tc.valsCount, tc.maxEvidence)
  369. }, "#%v", i)
  370. } else {
  371. assert.Equal(t,
  372. tc.result,
  373. MaxDataBytesUnknownEvidence(tc.maxBytes, tc.valsCount, tc.maxEvidence),
  374. "#%v", i)
  375. }
  376. }
  377. }
  378. func TestCommitToVoteSet(t *testing.T) {
  379. lastID := makeBlockIDRandom()
  380. h := int64(3)
  381. voteSet, valSet, vals := randVoteSet(h-1, 1, PrecommitType, 10, 1)
  382. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, time.Now())
  383. assert.NoError(t, err)
  384. chainID := voteSet.ChainID()
  385. voteSet2 := CommitToVoteSet(chainID, commit, valSet)
  386. for i := 0; i < len(vals); i++ {
  387. vote1 := voteSet.GetByIndex(i)
  388. vote2 := voteSet2.GetByIndex(i)
  389. vote3 := commit.GetVote(i)
  390. vote1bz := cdc.MustMarshalBinaryBare(vote1)
  391. vote2bz := cdc.MustMarshalBinaryBare(vote2)
  392. vote3bz := cdc.MustMarshalBinaryBare(vote3)
  393. assert.Equal(t, vote1bz, vote2bz)
  394. assert.Equal(t, vote1bz, vote3bz)
  395. }
  396. }
  397. func TestCommitToVoteSetWithVotesForNilBlock(t *testing.T) {
  398. blockID := makeBlockID([]byte("blockhash"), 1000, []byte("partshash"))
  399. const (
  400. height = int64(3)
  401. round = 0
  402. )
  403. type commitVoteTest struct {
  404. blockIDs []BlockID
  405. numVotes []int // must sum to numValidators
  406. numValidators int
  407. valid bool
  408. }
  409. testCases := []commitVoteTest{
  410. {[]BlockID{blockID, {}}, []int{67, 33}, 100, true},
  411. }
  412. for _, tc := range testCases {
  413. voteSet, valSet, vals := randVoteSet(height-1, round, PrecommitType, tc.numValidators, 1)
  414. vi := 0
  415. for n := range tc.blockIDs {
  416. for i := 0; i < tc.numVotes[n]; i++ {
  417. pubKey, err := vals[vi].GetPubKey()
  418. require.NoError(t, err)
  419. vote := &Vote{
  420. ValidatorAddress: pubKey.Address(),
  421. ValidatorIndex: vi,
  422. Height: height - 1,
  423. Round: round,
  424. Type: PrecommitType,
  425. BlockID: tc.blockIDs[n],
  426. Timestamp: tmtime.Now(),
  427. }
  428. added, err := signAddVote(vals[vi], vote, voteSet)
  429. assert.NoError(t, err)
  430. assert.True(t, added)
  431. vi++
  432. }
  433. }
  434. if tc.valid {
  435. commit := voteSet.MakeCommit() // panics without > 2/3 valid votes
  436. assert.NotNil(t, commit)
  437. err := valSet.VerifyCommit(voteSet.ChainID(), blockID, height-1, commit)
  438. assert.Nil(t, err)
  439. } else {
  440. assert.Panics(t, func() { voteSet.MakeCommit() })
  441. }
  442. }
  443. }
  444. func TestSignedHeaderValidateBasic(t *testing.T) {
  445. commit := randCommit(time.Now())
  446. chainID := "𠜎"
  447. timestamp := time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC)
  448. h := Header{
  449. Version: version.Consensus{Block: math.MaxInt64, App: math.MaxInt64},
  450. ChainID: chainID,
  451. Height: commit.Height,
  452. Time: timestamp,
  453. LastBlockID: commit.BlockID,
  454. LastCommitHash: commit.Hash(),
  455. DataHash: commit.Hash(),
  456. ValidatorsHash: commit.Hash(),
  457. NextValidatorsHash: commit.Hash(),
  458. ConsensusHash: commit.Hash(),
  459. AppHash: commit.Hash(),
  460. LastResultsHash: commit.Hash(),
  461. EvidenceHash: commit.Hash(),
  462. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  463. }
  464. validSignedHeader := SignedHeader{Header: &h, Commit: commit}
  465. validSignedHeader.Commit.BlockID.Hash = validSignedHeader.Hash()
  466. invalidSignedHeader := SignedHeader{}
  467. testCases := []struct {
  468. testName string
  469. shHeader *Header
  470. shCommit *Commit
  471. expectErr bool
  472. }{
  473. {"Valid Signed Header", validSignedHeader.Header, validSignedHeader.Commit, false},
  474. {"Invalid Signed Header", invalidSignedHeader.Header, validSignedHeader.Commit, true},
  475. {"Invalid Signed Header", validSignedHeader.Header, invalidSignedHeader.Commit, true},
  476. }
  477. for _, tc := range testCases {
  478. tc := tc
  479. t.Run(tc.testName, func(t *testing.T) {
  480. sh := SignedHeader{
  481. Header: tc.shHeader,
  482. Commit: tc.shCommit,
  483. }
  484. assert.Equal(
  485. t,
  486. tc.expectErr,
  487. sh.ValidateBasic(validSignedHeader.Header.ChainID) != nil,
  488. "Validate Basic had an unexpected result",
  489. )
  490. })
  491. }
  492. }
  493. func TestBlockIDValidateBasic(t *testing.T) {
  494. validBlockID := BlockID{
  495. Hash: bytes.HexBytes{},
  496. PartsHeader: PartSetHeader{
  497. Total: 1,
  498. Hash: bytes.HexBytes{},
  499. },
  500. }
  501. invalidBlockID := BlockID{
  502. Hash: []byte{0},
  503. PartsHeader: PartSetHeader{
  504. Total: -1,
  505. Hash: bytes.HexBytes{},
  506. },
  507. }
  508. testCases := []struct {
  509. testName string
  510. blockIDHash bytes.HexBytes
  511. blockIDPartsHeader PartSetHeader
  512. expectErr bool
  513. }{
  514. {"Valid BlockID", validBlockID.Hash, validBlockID.PartsHeader, false},
  515. {"Invalid BlockID", invalidBlockID.Hash, validBlockID.PartsHeader, true},
  516. {"Invalid BlockID", validBlockID.Hash, invalidBlockID.PartsHeader, true},
  517. }
  518. for _, tc := range testCases {
  519. tc := tc
  520. t.Run(tc.testName, func(t *testing.T) {
  521. blockID := BlockID{
  522. Hash: tc.blockIDHash,
  523. PartsHeader: tc.blockIDPartsHeader,
  524. }
  525. assert.Equal(t, tc.expectErr, blockID.ValidateBasic() != nil, "Validate Basic had an unexpected result")
  526. })
  527. }
  528. }
  529. func makeRandHeader() Header {
  530. chainID := "test"
  531. t := time.Now()
  532. height := tmrand.Int63()
  533. randBytes := tmrand.Bytes(tmhash.Size)
  534. randAddress := tmrand.Bytes(crypto.AddressSize)
  535. h := Header{
  536. Version: version.Consensus{Block: 1, App: 1},
  537. ChainID: chainID,
  538. Height: height,
  539. Time: t,
  540. LastBlockID: BlockID{},
  541. LastCommitHash: randBytes,
  542. DataHash: randBytes,
  543. ValidatorsHash: randBytes,
  544. NextValidatorsHash: randBytes,
  545. ConsensusHash: randBytes,
  546. AppHash: randBytes,
  547. LastResultsHash: randBytes,
  548. EvidenceHash: randBytes,
  549. ProposerAddress: randAddress,
  550. }
  551. return h
  552. }
  553. func TestHeaderProto(t *testing.T) {
  554. h1 := makeRandHeader()
  555. tc := []struct {
  556. msg string
  557. h1 *Header
  558. expPass bool
  559. }{
  560. {"success", &h1, true},
  561. {"failure empty Header", &Header{}, false},
  562. }
  563. for _, tt := range tc {
  564. tt := tt
  565. t.Run(tt.msg, func(t *testing.T) {
  566. pb := tt.h1.ToProto()
  567. h, err := HeaderFromProto(pb)
  568. if tt.expPass {
  569. require.NoError(t, err, tt.msg)
  570. require.Equal(t, tt.h1, &h, tt.msg)
  571. } else {
  572. require.Error(t, err, tt.msg)
  573. }
  574. })
  575. }
  576. }
  577. func TestBlockIDProtoBuf(t *testing.T) {
  578. blockID := makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))
  579. testCases := []struct {
  580. msg string
  581. bid1 *BlockID
  582. expPass bool
  583. }{
  584. {"success", &blockID, true},
  585. {"success empty", &BlockID{}, true},
  586. {"failure BlockID nil", nil, false},
  587. }
  588. for _, tc := range testCases {
  589. protoBlockID := tc.bid1.ToProto()
  590. bi, err := BlockIDFromProto(&protoBlockID)
  591. if tc.expPass {
  592. require.NoError(t, err)
  593. require.Equal(t, tc.bid1, bi, tc.msg)
  594. } else {
  595. require.NotEqual(t, tc.bid1, bi, tc.msg)
  596. }
  597. }
  598. }
  599. func TestSignedHeaderProtoBuf(t *testing.T) {
  600. commit := randCommit(time.Now())
  601. h := makeRandHeader()
  602. sh := SignedHeader{Header: &h, Commit: commit}
  603. testCases := []struct {
  604. msg string
  605. sh1 *SignedHeader
  606. expPass bool
  607. }{
  608. {"empty SignedHeader 2", &SignedHeader{}, true},
  609. {"success", &sh, true},
  610. {"failure nil", nil, false},
  611. }
  612. for _, tc := range testCases {
  613. protoSignedHeader := tc.sh1.ToProto()
  614. sh, err := SignedHeaderFromProto(protoSignedHeader)
  615. if tc.expPass {
  616. require.NoError(t, err, tc.msg)
  617. require.Equal(t, tc.sh1, sh, tc.msg)
  618. } else {
  619. require.Error(t, err, tc.msg)
  620. }
  621. }
  622. }
  623. func TestCommitProtoBuf(t *testing.T) {
  624. commit := randCommit(time.Now())
  625. testCases := []struct {
  626. msg string
  627. c1 *Commit
  628. expPass bool
  629. }{
  630. {"success", commit, true},
  631. // Empty value sets signatures to nil, signatures should not be nillable
  632. {"empty commit", &Commit{Signatures: []CommitSig{}}, true},
  633. {"fail Commit nil", nil, false},
  634. }
  635. for _, tc := range testCases {
  636. tc := tc
  637. protoCommit := tc.c1.ToProto()
  638. c, err := CommitFromProto(protoCommit)
  639. if tc.expPass {
  640. require.NoError(t, err, tc.msg)
  641. require.Equal(t, tc.c1, c, tc.msg)
  642. } else {
  643. require.Error(t, err, tc.msg)
  644. }
  645. }
  646. }