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.

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