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.

813 lines
24 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
  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. gogotypes "github.com/gogo/protobuf/types"
  13. "github.com/stretchr/testify/assert"
  14. "github.com/stretchr/testify/require"
  15. "github.com/tendermint/tendermint/crypto"
  16. "github.com/tendermint/tendermint/crypto/merkle"
  17. "github.com/tendermint/tendermint/crypto/tmhash"
  18. "github.com/tendermint/tendermint/libs/bits"
  19. "github.com/tendermint/tendermint/libs/bytes"
  20. tmrand "github.com/tendermint/tendermint/libs/rand"
  21. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  22. "github.com/tendermint/tendermint/proto/tendermint/version"
  23. tmtime "github.com/tendermint/tendermint/types/time"
  24. )
  25. func TestMain(m *testing.M) {
  26. code := m.Run()
  27. os.Exit(code)
  28. }
  29. func TestBlockAddEvidence(t *testing.T) {
  30. txs := []Tx{Tx("foo"), Tx("bar")}
  31. lastID := makeBlockIDRandom()
  32. h := int64(3)
  33. voteSet, _, vals := randVoteSet(h-1, 1, tmproto.PrecommitType, 10, 1)
  34. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, time.Now())
  35. require.NoError(t, err)
  36. ev := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain")
  37. evList := []Evidence{ev}
  38. block := MakeBlock(h, txs, commit, evList)
  39. require.NotNil(t, block)
  40. require.Equal(t, 1, len(block.Evidence.Evidence))
  41. require.NotNil(t, block.EvidenceHash)
  42. }
  43. func TestBlockValidateBasic(t *testing.T) {
  44. require.Error(t, (*Block)(nil).ValidateBasic())
  45. txs := []Tx{Tx("foo"), Tx("bar")}
  46. lastID := makeBlockIDRandom()
  47. h := int64(3)
  48. voteSet, valSet, vals := randVoteSet(h-1, 1, tmproto.PrecommitType, 10, 1)
  49. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, time.Now())
  50. require.NoError(t, err)
  51. ev := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain")
  52. evList := []Evidence{ev}
  53. testCases := []struct {
  54. testName string
  55. malleateBlock func(*Block)
  56. expErr bool
  57. }{
  58. {"Make Block", func(blk *Block) {}, false},
  59. {"Make Block w/ proposer Addr", func(blk *Block) { blk.ProposerAddress = valSet.GetProposer().Address }, false},
  60. {"Negative Height", func(blk *Block) { blk.Height = -1 }, true},
  61. {"Remove 1/2 the commits", func(blk *Block) {
  62. blk.LastCommit.Signatures = commit.Signatures[:commit.Size()/2]
  63. blk.LastCommit.hash = nil // clear hash or change wont be noticed
  64. }, true},
  65. {"Remove LastCommitHash", func(blk *Block) { blk.LastCommitHash = []byte("something else") }, true},
  66. {"Tampered Data", func(blk *Block) {
  67. blk.Data.Txs[0] = Tx("something else")
  68. blk.Data.hash = nil // clear hash or change wont be noticed
  69. }, true},
  70. {"Tampered DataHash", func(blk *Block) {
  71. blk.DataHash = tmrand.Bytes(len(blk.DataHash))
  72. }, true},
  73. {"Tampered EvidenceHash", func(blk *Block) {
  74. blk.EvidenceHash = []byte("something else")
  75. }, true},
  76. }
  77. for i, tc := range testCases {
  78. tc := tc
  79. i := i
  80. t.Run(tc.testName, func(t *testing.T) {
  81. block := MakeBlock(h, txs, commit, evList)
  82. block.ProposerAddress = valSet.GetProposer().Address
  83. tc.malleateBlock(block)
  84. err = block.ValidateBasic()
  85. assert.Equal(t, tc.expErr, err != nil, "#%d: %v", i, err)
  86. })
  87. }
  88. }
  89. func TestBlockHash(t *testing.T) {
  90. assert.Nil(t, (*Block)(nil).Hash())
  91. assert.Nil(t, MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil, nil).Hash())
  92. }
  93. func TestBlockMakePartSet(t *testing.T) {
  94. assert.Nil(t, (*Block)(nil).MakePartSet(2))
  95. partSet := MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil, nil).MakePartSet(1024)
  96. assert.NotNil(t, partSet)
  97. assert.EqualValues(t, 1, partSet.Total())
  98. }
  99. func TestBlockMakePartSetWithEvidence(t *testing.T) {
  100. assert.Nil(t, (*Block)(nil).MakePartSet(2))
  101. lastID := makeBlockIDRandom()
  102. h := int64(3)
  103. voteSet, _, vals := randVoteSet(h-1, 1, tmproto.PrecommitType, 10, 1)
  104. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, time.Now())
  105. require.NoError(t, err)
  106. ev := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain")
  107. evList := []Evidence{ev}
  108. partSet := MakeBlock(h, []Tx{Tx("Hello World")}, commit, evList).MakePartSet(512)
  109. assert.NotNil(t, partSet)
  110. assert.EqualValues(t, 4, partSet.Total())
  111. }
  112. func TestBlockHashesTo(t *testing.T) {
  113. assert.False(t, (*Block)(nil).HashesTo(nil))
  114. lastID := makeBlockIDRandom()
  115. h := int64(3)
  116. voteSet, valSet, vals := randVoteSet(h-1, 1, tmproto.PrecommitType, 10, 1)
  117. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, time.Now())
  118. require.NoError(t, err)
  119. ev := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain")
  120. evList := []Evidence{ev}
  121. block := MakeBlock(h, []Tx{Tx("Hello World")}, commit, evList)
  122. block.ValidatorsHash = valSet.Hash()
  123. assert.False(t, block.HashesTo([]byte{}))
  124. assert.False(t, block.HashesTo([]byte("something else")))
  125. assert.True(t, block.HashesTo(block.Hash()))
  126. }
  127. func TestBlockSize(t *testing.T) {
  128. size := MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil, nil).Size()
  129. if size <= 0 {
  130. t.Fatal("Size of the block is zero or negative")
  131. }
  132. }
  133. func TestBlockString(t *testing.T) {
  134. assert.Equal(t, "nil-Block", (*Block)(nil).String())
  135. assert.Equal(t, "nil-Block", (*Block)(nil).StringIndented(""))
  136. assert.Equal(t, "nil-Block", (*Block)(nil).StringShort())
  137. block := MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil, nil)
  138. assert.NotEqual(t, "nil-Block", block.String())
  139. assert.NotEqual(t, "nil-Block", block.StringIndented(""))
  140. assert.NotEqual(t, "nil-Block", block.StringShort())
  141. }
  142. func makeBlockIDRandom() BlockID {
  143. var (
  144. blockHash = make([]byte, tmhash.Size)
  145. partSetHash = make([]byte, tmhash.Size)
  146. )
  147. rand.Read(blockHash) //nolint: errcheck // ignore errcheck for read
  148. rand.Read(partSetHash) //nolint: errcheck // ignore errcheck for read
  149. return BlockID{blockHash, PartSetHeader{123, partSetHash}}
  150. }
  151. func makeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) BlockID {
  152. var (
  153. h = make([]byte, tmhash.Size)
  154. psH = make([]byte, tmhash.Size)
  155. )
  156. copy(h, hash)
  157. copy(psH, partSetHash)
  158. return BlockID{
  159. Hash: h,
  160. PartSetHeader: PartSetHeader{
  161. Total: partSetSize,
  162. Hash: psH,
  163. },
  164. }
  165. }
  166. var nilBytes []byte
  167. // This follows RFC-6962, i.e. `echo -n '' | sha256sum`
  168. var emptyBytes = []byte{0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8,
  169. 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b,
  170. 0x78, 0x52, 0xb8, 0x55}
  171. func TestNilHeaderHashDoesntCrash(t *testing.T) {
  172. assert.Equal(t, nilBytes, []byte((*Header)(nil).Hash()))
  173. assert.Equal(t, nilBytes, []byte((new(Header)).Hash()))
  174. }
  175. func TestNilDataHashDoesntCrash(t *testing.T) {
  176. assert.Equal(t, emptyBytes, []byte((*Data)(nil).Hash()))
  177. assert.Equal(t, emptyBytes, []byte(new(Data).Hash()))
  178. }
  179. func TestCommit(t *testing.T) {
  180. lastID := makeBlockIDRandom()
  181. h := int64(3)
  182. voteSet, _, vals := randVoteSet(h-1, 1, tmproto.PrecommitType, 10, 1)
  183. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, time.Now())
  184. require.NoError(t, err)
  185. assert.Equal(t, h-1, commit.Height)
  186. assert.EqualValues(t, 1, commit.Round)
  187. assert.Equal(t, tmproto.PrecommitType, tmproto.SignedMsgType(commit.Type()))
  188. if commit.Size() <= 0 {
  189. t.Fatalf("commit %v has a zero or negative size: %d", commit, commit.Size())
  190. }
  191. require.NotNil(t, commit.BitArray())
  192. assert.Equal(t, bits.NewBitArray(10).Size(), commit.BitArray().Size())
  193. assert.Equal(t, voteSet.GetByIndex(0), commit.GetByIndex(0))
  194. assert.True(t, commit.IsCommit())
  195. }
  196. func TestCommitValidateBasic(t *testing.T) {
  197. testCases := []struct {
  198. testName string
  199. malleateCommit func(*Commit)
  200. expectErr bool
  201. }{
  202. {"Random Commit", func(com *Commit) {}, false},
  203. {"Incorrect signature", func(com *Commit) { com.Signatures[0].Signature = []byte{0} }, false},
  204. {"Incorrect height", func(com *Commit) { com.Height = int64(-100) }, true},
  205. {"Incorrect round", func(com *Commit) { com.Round = -100 }, true},
  206. }
  207. for _, tc := range testCases {
  208. tc := tc
  209. t.Run(tc.testName, func(t *testing.T) {
  210. com := randCommit(time.Now())
  211. tc.malleateCommit(com)
  212. assert.Equal(t, tc.expectErr, com.ValidateBasic() != nil, "Validate Basic had an unexpected result")
  213. })
  214. }
  215. }
  216. func TestHeaderHash(t *testing.T) {
  217. testCases := []struct {
  218. desc string
  219. header *Header
  220. expectHash bytes.HexBytes
  221. }{
  222. {"Generates expected hash", &Header{
  223. Version: version.Consensus{Block: 1, App: 2},
  224. ChainID: "chainId",
  225. Height: 3,
  226. Time: time.Date(2019, 10, 13, 16, 14, 44, 0, time.UTC),
  227. LastBlockID: makeBlockID(make([]byte, tmhash.Size), 6, make([]byte, tmhash.Size)),
  228. LastCommitHash: tmhash.Sum([]byte("last_commit_hash")),
  229. DataHash: tmhash.Sum([]byte("data_hash")),
  230. ValidatorsHash: tmhash.Sum([]byte("validators_hash")),
  231. NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")),
  232. ConsensusHash: tmhash.Sum([]byte("consensus_hash")),
  233. AppHash: tmhash.Sum([]byte("app_hash")),
  234. LastResultsHash: tmhash.Sum([]byte("last_results_hash")),
  235. EvidenceHash: tmhash.Sum([]byte("evidence_hash")),
  236. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  237. }, hexBytesFromString("F740121F553B5418C3EFBD343C2DBFE9E007BB67B0D020A0741374BAB65242A4")},
  238. {"nil header yields nil", nil, nil},
  239. {"nil ValidatorsHash yields nil", &Header{
  240. Version: version.Consensus{Block: 1, App: 2},
  241. ChainID: "chainId",
  242. Height: 3,
  243. Time: time.Date(2019, 10, 13, 16, 14, 44, 0, time.UTC),
  244. LastBlockID: makeBlockID(make([]byte, tmhash.Size), 6, make([]byte, tmhash.Size)),
  245. LastCommitHash: tmhash.Sum([]byte("last_commit_hash")),
  246. DataHash: tmhash.Sum([]byte("data_hash")),
  247. ValidatorsHash: nil,
  248. NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")),
  249. ConsensusHash: tmhash.Sum([]byte("consensus_hash")),
  250. AppHash: tmhash.Sum([]byte("app_hash")),
  251. LastResultsHash: tmhash.Sum([]byte("last_results_hash")),
  252. EvidenceHash: tmhash.Sum([]byte("evidence_hash")),
  253. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  254. }, nil},
  255. }
  256. for _, tc := range testCases {
  257. tc := tc
  258. t.Run(tc.desc, func(t *testing.T) {
  259. assert.Equal(t, tc.expectHash, tc.header.Hash())
  260. // We also make sure that all fields are hashed in struct order, and that all
  261. // fields in the test struct are non-zero.
  262. if tc.header != nil && tc.expectHash != nil {
  263. byteSlices := [][]byte{}
  264. s := reflect.ValueOf(*tc.header)
  265. for i := 0; i < s.NumField(); i++ {
  266. f := s.Field(i)
  267. assert.False(t, f.IsZero(), "Found zero-valued field %v",
  268. s.Type().Field(i).Name)
  269. switch f := f.Interface().(type) {
  270. case int64, bytes.HexBytes, string:
  271. byteSlices = append(byteSlices, cdcEncode(f))
  272. case time.Time:
  273. bz, err := gogotypes.StdTimeMarshal(f)
  274. require.NoError(t, err)
  275. byteSlices = append(byteSlices, bz)
  276. case version.Consensus:
  277. bz, err := f.Marshal()
  278. require.NoError(t, err)
  279. byteSlices = append(byteSlices, bz)
  280. case BlockID:
  281. pbbi := f.ToProto()
  282. bz, err := pbbi.Marshal()
  283. require.NoError(t, err)
  284. byteSlices = append(byteSlices, bz)
  285. default:
  286. t.Errorf("unknown type %T", f)
  287. }
  288. }
  289. assert.Equal(t,
  290. bytes.HexBytes(merkle.HashFromByteSlices(byteSlices)), tc.header.Hash())
  291. }
  292. })
  293. }
  294. }
  295. func TestMaxHeaderBytes(t *testing.T) {
  296. // Construct a UTF-8 string of MaxChainIDLen length using the supplementary
  297. // characters.
  298. // Each supplementary character takes 4 bytes.
  299. // http://www.i18nguy.com/unicode/supplementary-test.html
  300. maxChainID := ""
  301. for i := 0; i < MaxChainIDLen; i++ {
  302. maxChainID += "𠜎"
  303. }
  304. // time is varint encoded so need to pick the max.
  305. // year int, month Month, day, hour, min, sec, nsec int, loc *Location
  306. timestamp := time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC)
  307. h := Header{
  308. Version: version.Consensus{Block: math.MaxInt64, App: math.MaxInt64},
  309. ChainID: maxChainID,
  310. Height: math.MaxInt64,
  311. Time: timestamp,
  312. LastBlockID: makeBlockID(make([]byte, tmhash.Size), math.MaxInt32, make([]byte, tmhash.Size)),
  313. LastCommitHash: tmhash.Sum([]byte("last_commit_hash")),
  314. DataHash: tmhash.Sum([]byte("data_hash")),
  315. ValidatorsHash: tmhash.Sum([]byte("validators_hash")),
  316. NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")),
  317. ConsensusHash: tmhash.Sum([]byte("consensus_hash")),
  318. AppHash: tmhash.Sum([]byte("app_hash")),
  319. LastResultsHash: tmhash.Sum([]byte("last_results_hash")),
  320. EvidenceHash: tmhash.Sum([]byte("evidence_hash")),
  321. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  322. }
  323. bz, err := h.ToProto().Marshal()
  324. require.NoError(t, err)
  325. assert.EqualValues(t, MaxHeaderBytes, int64(len(bz)))
  326. }
  327. func randCommit(now time.Time) *Commit {
  328. lastID := makeBlockIDRandom()
  329. h := int64(3)
  330. voteSet, _, vals := randVoteSet(h-1, 1, tmproto.PrecommitType, 10, 1)
  331. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, now)
  332. if err != nil {
  333. panic(err)
  334. }
  335. return commit
  336. }
  337. func hexBytesFromString(s string) bytes.HexBytes {
  338. b, err := hex.DecodeString(s)
  339. if err != nil {
  340. panic(err)
  341. }
  342. return bytes.HexBytes(b)
  343. }
  344. func TestBlockMaxDataBytes(t *testing.T) {
  345. testCases := []struct {
  346. maxBytes int64
  347. valsCount int
  348. evidenceCount int
  349. panics bool
  350. result int64
  351. }{
  352. 0: {-10, 1, 0, true, 0},
  353. 1: {10, 1, 0, true, 0},
  354. 2: {844, 1, 0, true, 0},
  355. 3: {846, 1, 0, false, 0},
  356. 4: {847, 1, 0, false, 1},
  357. }
  358. for i, tc := range testCases {
  359. tc := tc
  360. if tc.panics {
  361. assert.Panics(t, func() {
  362. MaxDataBytes(tc.maxBytes, tc.valsCount, tc.evidenceCount)
  363. }, "#%v", i)
  364. } else {
  365. assert.Equal(t,
  366. tc.result,
  367. MaxDataBytes(tc.maxBytes, tc.valsCount, tc.evidenceCount),
  368. "#%v", i)
  369. }
  370. }
  371. }
  372. func TestBlockMaxDataBytesUnknownEvidence(t *testing.T) {
  373. testCases := []struct {
  374. maxBytes int64
  375. maxEvidence uint32
  376. valsCount int
  377. panics bool
  378. result int64
  379. }{
  380. 0: {-10, 0, 1, true, 0},
  381. 1: {10, 0, 1, true, 0},
  382. 2: {845, 0, 1, true, 0},
  383. 3: {846, 0, 1, false, 0},
  384. 4: {1290, 1, 1, false, 0},
  385. 5: {1291, 1, 1, false, 1},
  386. }
  387. for i, tc := range testCases {
  388. tc := tc
  389. if tc.panics {
  390. assert.Panics(t, func() {
  391. MaxDataBytesUnknownEvidence(tc.maxBytes, tc.valsCount, tc.maxEvidence)
  392. }, "#%v", i)
  393. } else {
  394. assert.Equal(t,
  395. tc.result,
  396. MaxDataBytesUnknownEvidence(tc.maxBytes, tc.valsCount, tc.maxEvidence),
  397. "#%v", i)
  398. }
  399. }
  400. }
  401. func TestCommitToVoteSet(t *testing.T) {
  402. lastID := makeBlockIDRandom()
  403. h := int64(3)
  404. voteSet, valSet, vals := randVoteSet(h-1, 1, tmproto.PrecommitType, 10, 1)
  405. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, time.Now())
  406. assert.NoError(t, err)
  407. chainID := voteSet.ChainID()
  408. voteSet2 := CommitToVoteSet(chainID, commit, valSet)
  409. for i := int32(0); int(i) < len(vals); i++ {
  410. vote1 := voteSet.GetByIndex(i)
  411. vote2 := voteSet2.GetByIndex(i)
  412. vote3 := commit.GetVote(i)
  413. vote1bz, err := vote1.ToProto().Marshal()
  414. require.NoError(t, err)
  415. vote2bz, err := vote2.ToProto().Marshal()
  416. require.NoError(t, err)
  417. vote3bz, err := vote3.ToProto().Marshal()
  418. require.NoError(t, err)
  419. assert.Equal(t, vote1bz, vote2bz)
  420. assert.Equal(t, vote1bz, vote3bz)
  421. }
  422. }
  423. func TestCommitToVoteSetWithVotesForNilBlock(t *testing.T) {
  424. blockID := makeBlockID([]byte("blockhash"), 1000, []byte("partshash"))
  425. const (
  426. height = int64(3)
  427. round = 0
  428. )
  429. type commitVoteTest struct {
  430. blockIDs []BlockID
  431. numVotes []int // must sum to numValidators
  432. numValidators int
  433. valid bool
  434. }
  435. testCases := []commitVoteTest{
  436. {[]BlockID{blockID, {}}, []int{67, 33}, 100, true},
  437. }
  438. for _, tc := range testCases {
  439. voteSet, valSet, vals := randVoteSet(height-1, round, tmproto.PrecommitType, tc.numValidators, 1)
  440. vi := int32(0)
  441. for n := range tc.blockIDs {
  442. for i := 0; i < tc.numVotes[n]; i++ {
  443. pubKey, err := vals[vi].GetPubKey()
  444. require.NoError(t, err)
  445. vote := &Vote{
  446. ValidatorAddress: pubKey.Address(),
  447. ValidatorIndex: vi,
  448. Height: height - 1,
  449. Round: round,
  450. Type: tmproto.PrecommitType,
  451. BlockID: tc.blockIDs[n],
  452. Timestamp: tmtime.Now(),
  453. }
  454. added, err := signAddVote(vals[vi], vote, voteSet)
  455. assert.NoError(t, err)
  456. assert.True(t, added)
  457. vi++
  458. }
  459. }
  460. if tc.valid {
  461. commit := voteSet.MakeCommit() // panics without > 2/3 valid votes
  462. assert.NotNil(t, commit)
  463. err := valSet.VerifyCommit(voteSet.ChainID(), blockID, height-1, commit)
  464. assert.Nil(t, err)
  465. } else {
  466. assert.Panics(t, func() { voteSet.MakeCommit() })
  467. }
  468. }
  469. }
  470. func TestBlockIDValidateBasic(t *testing.T) {
  471. validBlockID := BlockID{
  472. Hash: bytes.HexBytes{},
  473. PartSetHeader: PartSetHeader{
  474. Total: 1,
  475. Hash: bytes.HexBytes{},
  476. },
  477. }
  478. invalidBlockID := BlockID{
  479. Hash: []byte{0},
  480. PartSetHeader: PartSetHeader{
  481. Total: 1,
  482. Hash: []byte{0},
  483. },
  484. }
  485. testCases := []struct {
  486. testName string
  487. blockIDHash bytes.HexBytes
  488. blockIDPartSetHeader PartSetHeader
  489. expectErr bool
  490. }{
  491. {"Valid BlockID", validBlockID.Hash, validBlockID.PartSetHeader, false},
  492. {"Invalid BlockID", invalidBlockID.Hash, validBlockID.PartSetHeader, true},
  493. {"Invalid BlockID", validBlockID.Hash, invalidBlockID.PartSetHeader, true},
  494. }
  495. for _, tc := range testCases {
  496. tc := tc
  497. t.Run(tc.testName, func(t *testing.T) {
  498. blockID := BlockID{
  499. Hash: tc.blockIDHash,
  500. PartSetHeader: tc.blockIDPartSetHeader,
  501. }
  502. assert.Equal(t, tc.expectErr, blockID.ValidateBasic() != nil, "Validate Basic had an unexpected result")
  503. })
  504. }
  505. }
  506. func TestBlockProtoBuf(t *testing.T) {
  507. h := tmrand.Int63()
  508. c1 := randCommit(time.Now())
  509. b1 := MakeBlock(h, []Tx{Tx([]byte{1})}, &Commit{Signatures: []CommitSig{}}, []Evidence{})
  510. b1.ProposerAddress = tmrand.Bytes(crypto.AddressSize)
  511. b2 := MakeBlock(h, []Tx{Tx([]byte{1})}, c1, []Evidence{})
  512. b2.ProposerAddress = tmrand.Bytes(crypto.AddressSize)
  513. evidenceTime := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
  514. evi := NewMockDuplicateVoteEvidence(h, evidenceTime, "block-test-chain")
  515. b2.Evidence = EvidenceData{Evidence: EvidenceList{evi}}
  516. b2.EvidenceHash = b2.Evidence.Hash()
  517. b3 := MakeBlock(h, []Tx{}, c1, []Evidence{})
  518. b3.ProposerAddress = tmrand.Bytes(crypto.AddressSize)
  519. testCases := []struct {
  520. msg string
  521. b1 *Block
  522. expPass bool
  523. expPass2 bool
  524. }{
  525. {"nil block", nil, false, false},
  526. {"b1", b1, true, true},
  527. {"b2", b2, true, true},
  528. {"b3", b3, true, true},
  529. }
  530. for _, tc := range testCases {
  531. pb, err := tc.b1.ToProto()
  532. if tc.expPass {
  533. require.NoError(t, err, tc.msg)
  534. } else {
  535. require.Error(t, err, tc.msg)
  536. }
  537. block, err := BlockFromProto(pb)
  538. if tc.expPass2 {
  539. require.NoError(t, err, tc.msg)
  540. require.EqualValues(t, tc.b1.Header, block.Header, tc.msg)
  541. require.EqualValues(t, tc.b1.Data, block.Data, tc.msg)
  542. require.EqualValues(t, tc.b1.Evidence, block.Evidence, tc.msg)
  543. require.EqualValues(t, *tc.b1.LastCommit, *block.LastCommit, tc.msg)
  544. } else {
  545. require.Error(t, err, tc.msg)
  546. }
  547. }
  548. }
  549. func TestDataProtoBuf(t *testing.T) {
  550. data := &Data{Txs: Txs{Tx([]byte{1}), Tx([]byte{2}), Tx([]byte{3})}}
  551. _ = data.Hash()
  552. data2 := &Data{Txs: Txs{}}
  553. _ = data2.Hash()
  554. testCases := []struct {
  555. msg string
  556. data1 *Data
  557. expPass bool
  558. }{
  559. {"success", data, true},
  560. {"success data2", data2, true},
  561. }
  562. for _, tc := range testCases {
  563. protoData := tc.data1.ToProto()
  564. d, err := DataFromProto(&protoData)
  565. if tc.expPass {
  566. require.NoError(t, err, tc.msg)
  567. require.EqualValues(t, tc.data1, &d, tc.msg)
  568. } else {
  569. require.Error(t, err, tc.msg)
  570. }
  571. }
  572. }
  573. func TestEvidenceDataProtoBuf(t *testing.T) {
  574. val := NewMockPV()
  575. blockID := makeBlockID(tmhash.Sum([]byte("blockhash")), math.MaxInt32, tmhash.Sum([]byte("partshash")))
  576. blockID2 := makeBlockID(tmhash.Sum([]byte("blockhash2")), math.MaxInt32, tmhash.Sum([]byte("partshash")))
  577. const chainID = "mychain"
  578. v := makeVote(t, val, chainID, math.MaxInt32, math.MaxInt64, 1, 0x01, blockID, time.Now())
  579. v2 := makeVote(t, val, chainID, math.MaxInt32, math.MaxInt64, 2, 0x01, blockID2, time.Now())
  580. ev := NewDuplicateVoteEvidence(v2, v, v2.Timestamp)
  581. data := &EvidenceData{Evidence: EvidenceList{ev}}
  582. _ = data.Hash()
  583. testCases := []struct {
  584. msg string
  585. data1 *EvidenceData
  586. expPass1 bool
  587. expPass2 bool
  588. }{
  589. {"success", data, true, true},
  590. {"empty evidenceData", &EvidenceData{Evidence: EvidenceList{}}, true, true},
  591. {"fail nil Data", nil, false, false},
  592. }
  593. for _, tc := range testCases {
  594. protoData, err := tc.data1.ToProto()
  595. if tc.expPass1 {
  596. require.NoError(t, err, tc.msg)
  597. } else {
  598. require.Error(t, err, tc.msg)
  599. }
  600. eviD := new(EvidenceData)
  601. err = eviD.FromProto(protoData)
  602. if tc.expPass2 {
  603. require.NoError(t, err, tc.msg)
  604. require.Equal(t, tc.data1, eviD, tc.msg)
  605. } else {
  606. require.Error(t, err, tc.msg)
  607. }
  608. }
  609. }
  610. func makeRandHeader() Header {
  611. chainID := "test"
  612. t := time.Now()
  613. height := tmrand.Int63()
  614. randBytes := tmrand.Bytes(tmhash.Size)
  615. randAddress := tmrand.Bytes(crypto.AddressSize)
  616. h := Header{
  617. Version: version.Consensus{Block: 1, App: 1},
  618. ChainID: chainID,
  619. Height: height,
  620. Time: t,
  621. LastBlockID: BlockID{},
  622. LastCommitHash: randBytes,
  623. DataHash: randBytes,
  624. ValidatorsHash: randBytes,
  625. NextValidatorsHash: randBytes,
  626. ConsensusHash: randBytes,
  627. AppHash: randBytes,
  628. LastResultsHash: randBytes,
  629. EvidenceHash: randBytes,
  630. ProposerAddress: randAddress,
  631. }
  632. return h
  633. }
  634. func TestHeaderProto(t *testing.T) {
  635. h1 := makeRandHeader()
  636. tc := []struct {
  637. msg string
  638. h1 *Header
  639. expPass bool
  640. }{
  641. {"success", &h1, true},
  642. {"failure empty Header", &Header{}, false},
  643. }
  644. for _, tt := range tc {
  645. tt := tt
  646. t.Run(tt.msg, func(t *testing.T) {
  647. pb := tt.h1.ToProto()
  648. h, err := HeaderFromProto(pb)
  649. if tt.expPass {
  650. require.NoError(t, err, tt.msg)
  651. require.Equal(t, tt.h1, &h, tt.msg)
  652. } else {
  653. require.Error(t, err, tt.msg)
  654. }
  655. })
  656. }
  657. }
  658. func TestBlockIDProtoBuf(t *testing.T) {
  659. blockID := makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))
  660. testCases := []struct {
  661. msg string
  662. bid1 *BlockID
  663. expPass bool
  664. }{
  665. {"success", &blockID, true},
  666. {"success empty", &BlockID{}, true},
  667. {"failure BlockID nil", nil, false},
  668. }
  669. for _, tc := range testCases {
  670. protoBlockID := tc.bid1.ToProto()
  671. bi, err := BlockIDFromProto(&protoBlockID)
  672. if tc.expPass {
  673. require.NoError(t, err)
  674. require.Equal(t, tc.bid1, bi, tc.msg)
  675. } else {
  676. require.NotEqual(t, tc.bid1, bi, tc.msg)
  677. }
  678. }
  679. }
  680. func TestSignedHeaderProtoBuf(t *testing.T) {
  681. commit := randCommit(time.Now())
  682. h := makeRandHeader()
  683. sh := SignedHeader{Header: &h, Commit: commit}
  684. testCases := []struct {
  685. msg string
  686. sh1 *SignedHeader
  687. expPass bool
  688. }{
  689. {"empty SignedHeader 2", &SignedHeader{}, true},
  690. {"success", &sh, true},
  691. {"failure nil", nil, false},
  692. }
  693. for _, tc := range testCases {
  694. protoSignedHeader := tc.sh1.ToProto()
  695. sh, err := SignedHeaderFromProto(protoSignedHeader)
  696. if tc.expPass {
  697. require.NoError(t, err, tc.msg)
  698. require.Equal(t, tc.sh1, sh, tc.msg)
  699. } else {
  700. require.Error(t, err, tc.msg)
  701. }
  702. }
  703. }
  704. func TestBlockIDEquals(t *testing.T) {
  705. var (
  706. blockID = makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))
  707. blockIDDuplicate = makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))
  708. blockIDDifferent = makeBlockID([]byte("different_hash"), 2, []byte("part_set_hash"))
  709. blockIDEmpty = BlockID{}
  710. )
  711. assert.True(t, blockID.Equals(blockIDDuplicate))
  712. assert.False(t, blockID.Equals(blockIDDifferent))
  713. assert.False(t, blockID.Equals(blockIDEmpty))
  714. assert.True(t, blockIDEmpty.Equals(blockIDEmpty))
  715. assert.False(t, blockIDEmpty.Equals(blockIDDifferent))
  716. }