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.

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