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.

856 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 TestMaxCommitBytes(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: crypto.CRandBytes(MaxSignatureSize),
  229. }
  230. pbSig := cs.ToProto()
  231. // test that a single commit sig doesn't exceed max commit sig bytes
  232. assert.EqualValues(t, MaxCommitSigBytes, pbSig.Size())
  233. // check size with a single commit
  234. commit := &Commit{
  235. Height: math.MaxInt64,
  236. Round: math.MaxInt32,
  237. BlockID: BlockID{
  238. Hash: tmhash.Sum([]byte("blockID_hash")),
  239. PartSetHeader: PartSetHeader{
  240. Total: math.MaxInt32,
  241. Hash: tmhash.Sum([]byte("blockID_part_set_header_hash")),
  242. },
  243. },
  244. Signatures: []CommitSig{cs},
  245. }
  246. pb := commit.ToProto()
  247. assert.EqualValues(t, MaxCommitBytes(1), int64(pb.Size()))
  248. // check the upper bound of the commit size
  249. for i := 1; i < MaxVotesCount; i++ {
  250. commit.Signatures = append(commit.Signatures, cs)
  251. }
  252. pb = commit.ToProto()
  253. assert.EqualValues(t, MaxCommitBytes(MaxVotesCount), int64(pb.Size()))
  254. }
  255. func TestHeaderHash(t *testing.T) {
  256. testCases := []struct {
  257. desc string
  258. header *Header
  259. expectHash bytes.HexBytes
  260. }{
  261. {"Generates expected hash", &Header{
  262. Version: tmversion.Consensus{Block: 1, App: 2},
  263. ChainID: "chainId",
  264. Height: 3,
  265. Time: time.Date(2019, 10, 13, 16, 14, 44, 0, time.UTC),
  266. LastBlockID: makeBlockID(make([]byte, tmhash.Size), 6, make([]byte, tmhash.Size)),
  267. LastCommitHash: tmhash.Sum([]byte("last_commit_hash")),
  268. DataHash: tmhash.Sum([]byte("data_hash")),
  269. ValidatorsHash: tmhash.Sum([]byte("validators_hash")),
  270. NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")),
  271. ConsensusHash: tmhash.Sum([]byte("consensus_hash")),
  272. AppHash: tmhash.Sum([]byte("app_hash")),
  273. LastResultsHash: tmhash.Sum([]byte("last_results_hash")),
  274. EvidenceHash: tmhash.Sum([]byte("evidence_hash")),
  275. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  276. }, hexBytesFromString("F740121F553B5418C3EFBD343C2DBFE9E007BB67B0D020A0741374BAB65242A4")},
  277. {"nil header yields nil", nil, nil},
  278. {"nil ValidatorsHash yields nil", &Header{
  279. Version: tmversion.Consensus{Block: 1, App: 2},
  280. ChainID: "chainId",
  281. Height: 3,
  282. Time: time.Date(2019, 10, 13, 16, 14, 44, 0, time.UTC),
  283. LastBlockID: makeBlockID(make([]byte, tmhash.Size), 6, make([]byte, tmhash.Size)),
  284. LastCommitHash: tmhash.Sum([]byte("last_commit_hash")),
  285. DataHash: tmhash.Sum([]byte("data_hash")),
  286. ValidatorsHash: nil,
  287. NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")),
  288. ConsensusHash: tmhash.Sum([]byte("consensus_hash")),
  289. AppHash: tmhash.Sum([]byte("app_hash")),
  290. LastResultsHash: tmhash.Sum([]byte("last_results_hash")),
  291. EvidenceHash: tmhash.Sum([]byte("evidence_hash")),
  292. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  293. }, nil},
  294. }
  295. for _, tc := range testCases {
  296. tc := tc
  297. t.Run(tc.desc, func(t *testing.T) {
  298. assert.Equal(t, tc.expectHash, tc.header.Hash())
  299. // We also make sure that all fields are hashed in struct order, and that all
  300. // fields in the test struct are non-zero.
  301. if tc.header != nil && tc.expectHash != nil {
  302. byteSlices := [][]byte{}
  303. s := reflect.ValueOf(*tc.header)
  304. for i := 0; i < s.NumField(); i++ {
  305. f := s.Field(i)
  306. assert.False(t, f.IsZero(), "Found zero-valued field %v",
  307. s.Type().Field(i).Name)
  308. switch f := f.Interface().(type) {
  309. case int64, bytes.HexBytes, string:
  310. byteSlices = append(byteSlices, cdcEncode(f))
  311. case time.Time:
  312. bz, err := gogotypes.StdTimeMarshal(f)
  313. require.NoError(t, err)
  314. byteSlices = append(byteSlices, bz)
  315. case tmversion.Consensus:
  316. bz, err := f.Marshal()
  317. require.NoError(t, err)
  318. byteSlices = append(byteSlices, bz)
  319. case BlockID:
  320. pbbi := f.ToProto()
  321. bz, err := pbbi.Marshal()
  322. require.NoError(t, err)
  323. byteSlices = append(byteSlices, bz)
  324. default:
  325. t.Errorf("unknown type %T", f)
  326. }
  327. }
  328. assert.Equal(t,
  329. bytes.HexBytes(merkle.HashFromByteSlices(byteSlices)), tc.header.Hash())
  330. }
  331. })
  332. }
  333. }
  334. func TestMaxHeaderBytes(t *testing.T) {
  335. // Construct a UTF-8 string of MaxChainIDLen length using the supplementary
  336. // characters.
  337. // Each supplementary character takes 4 bytes.
  338. // http://www.i18nguy.com/unicode/supplementary-test.html
  339. maxChainID := ""
  340. for i := 0; i < MaxChainIDLen; i++ {
  341. maxChainID += "𠜎"
  342. }
  343. // time is varint encoded so need to pick the max.
  344. // year int, month Month, day, hour, min, sec, nsec int, loc *Location
  345. timestamp := time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC)
  346. h := Header{
  347. Version: tmversion.Consensus{Block: math.MaxInt64, App: math.MaxInt64},
  348. ChainID: maxChainID,
  349. Height: math.MaxInt64,
  350. Time: timestamp,
  351. LastBlockID: makeBlockID(make([]byte, tmhash.Size), math.MaxInt32, make([]byte, tmhash.Size)),
  352. LastCommitHash: tmhash.Sum([]byte("last_commit_hash")),
  353. DataHash: tmhash.Sum([]byte("data_hash")),
  354. ValidatorsHash: tmhash.Sum([]byte("validators_hash")),
  355. NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")),
  356. ConsensusHash: tmhash.Sum([]byte("consensus_hash")),
  357. AppHash: tmhash.Sum([]byte("app_hash")),
  358. LastResultsHash: tmhash.Sum([]byte("last_results_hash")),
  359. EvidenceHash: tmhash.Sum([]byte("evidence_hash")),
  360. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  361. }
  362. bz, err := h.ToProto().Marshal()
  363. require.NoError(t, err)
  364. assert.EqualValues(t, MaxHeaderBytes, int64(len(bz)))
  365. }
  366. func randCommit(now time.Time) *Commit {
  367. lastID := makeBlockIDRandom()
  368. h := int64(3)
  369. voteSet, _, vals := randVoteSet(h-1, 1, tmproto.PrecommitType, 10, 1)
  370. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, now)
  371. if err != nil {
  372. panic(err)
  373. }
  374. return commit
  375. }
  376. func hexBytesFromString(s string) bytes.HexBytes {
  377. b, err := hex.DecodeString(s)
  378. if err != nil {
  379. panic(err)
  380. }
  381. return bytes.HexBytes(b)
  382. }
  383. func TestBlockMaxDataBytes(t *testing.T) {
  384. testCases := []struct {
  385. maxBytes int64
  386. valsCount int
  387. evidenceBytes int64
  388. panics bool
  389. result int64
  390. }{
  391. 0: {-10, 1, 0, true, 0},
  392. 1: {10, 1, 0, true, 0},
  393. 2: {841, 1, 0, true, 0},
  394. 3: {842, 1, 0, false, 0},
  395. 4: {843, 1, 0, false, 1},
  396. 5: {954, 2, 0, false, 1},
  397. 6: {1053, 2, 100, false, 0},
  398. }
  399. for i, tc := range testCases {
  400. tc := tc
  401. if tc.panics {
  402. assert.Panics(t, func() {
  403. MaxDataBytes(tc.maxBytes, tc.evidenceBytes, tc.valsCount)
  404. }, "#%v", i)
  405. } else {
  406. assert.Equal(t,
  407. tc.result,
  408. MaxDataBytes(tc.maxBytes, tc.evidenceBytes, tc.valsCount),
  409. "#%v", i)
  410. }
  411. }
  412. }
  413. func TestBlockMaxDataBytesNoEvidence(t *testing.T) {
  414. testCases := []struct {
  415. maxBytes int64
  416. valsCount int
  417. panics bool
  418. result int64
  419. }{
  420. 0: {-10, 1, true, 0},
  421. 1: {10, 1, true, 0},
  422. 2: {841, 1, true, 0},
  423. 3: {842, 1, false, 0},
  424. 4: {843, 1, false, 1},
  425. }
  426. for i, tc := range testCases {
  427. tc := tc
  428. if tc.panics {
  429. assert.Panics(t, func() {
  430. MaxDataBytesNoEvidence(tc.maxBytes, tc.valsCount)
  431. }, "#%v", i)
  432. } else {
  433. assert.Equal(t,
  434. tc.result,
  435. MaxDataBytesNoEvidence(tc.maxBytes, tc.valsCount),
  436. "#%v", i)
  437. }
  438. }
  439. }
  440. func TestCommitToVoteSet(t *testing.T) {
  441. lastID := makeBlockIDRandom()
  442. h := int64(3)
  443. voteSet, valSet, vals := randVoteSet(h-1, 1, tmproto.PrecommitType, 10, 1)
  444. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, time.Now())
  445. assert.NoError(t, err)
  446. chainID := voteSet.ChainID()
  447. voteSet2 := CommitToVoteSet(chainID, commit, valSet)
  448. for i := int32(0); int(i) < len(vals); i++ {
  449. vote1 := voteSet.GetByIndex(i)
  450. vote2 := voteSet2.GetByIndex(i)
  451. vote3 := commit.GetVote(i)
  452. vote1bz, err := vote1.ToProto().Marshal()
  453. require.NoError(t, err)
  454. vote2bz, err := vote2.ToProto().Marshal()
  455. require.NoError(t, err)
  456. vote3bz, err := vote3.ToProto().Marshal()
  457. require.NoError(t, err)
  458. assert.Equal(t, vote1bz, vote2bz)
  459. assert.Equal(t, vote1bz, vote3bz)
  460. }
  461. }
  462. func TestCommitToVoteSetWithVotesForNilBlock(t *testing.T) {
  463. blockID := makeBlockID([]byte("blockhash"), 1000, []byte("partshash"))
  464. const (
  465. height = int64(3)
  466. round = 0
  467. )
  468. type commitVoteTest struct {
  469. blockIDs []BlockID
  470. numVotes []int // must sum to numValidators
  471. numValidators int
  472. valid bool
  473. }
  474. testCases := []commitVoteTest{
  475. {[]BlockID{blockID, {}}, []int{67, 33}, 100, true},
  476. }
  477. for _, tc := range testCases {
  478. voteSet, valSet, vals := randVoteSet(height-1, round, tmproto.PrecommitType, tc.numValidators, 1)
  479. vi := int32(0)
  480. for n := range tc.blockIDs {
  481. for i := 0; i < tc.numVotes[n]; i++ {
  482. pubKey, err := vals[vi].GetPubKey()
  483. require.NoError(t, err)
  484. vote := &Vote{
  485. ValidatorAddress: pubKey.Address(),
  486. ValidatorIndex: vi,
  487. Height: height - 1,
  488. Round: round,
  489. Type: tmproto.PrecommitType,
  490. BlockID: tc.blockIDs[n],
  491. Timestamp: tmtime.Now(),
  492. }
  493. added, err := signAddVote(vals[vi], vote, voteSet)
  494. assert.NoError(t, err)
  495. assert.True(t, added)
  496. vi++
  497. }
  498. }
  499. if tc.valid {
  500. commit := voteSet.MakeCommit() // panics without > 2/3 valid votes
  501. assert.NotNil(t, commit)
  502. err := valSet.VerifyCommit(voteSet.ChainID(), blockID, height-1, commit)
  503. assert.Nil(t, err)
  504. } else {
  505. assert.Panics(t, func() { voteSet.MakeCommit() })
  506. }
  507. }
  508. }
  509. func TestBlockIDValidateBasic(t *testing.T) {
  510. validBlockID := BlockID{
  511. Hash: bytes.HexBytes{},
  512. PartSetHeader: PartSetHeader{
  513. Total: 1,
  514. Hash: bytes.HexBytes{},
  515. },
  516. }
  517. invalidBlockID := BlockID{
  518. Hash: []byte{0},
  519. PartSetHeader: PartSetHeader{
  520. Total: 1,
  521. Hash: []byte{0},
  522. },
  523. }
  524. testCases := []struct {
  525. testName string
  526. blockIDHash bytes.HexBytes
  527. blockIDPartSetHeader PartSetHeader
  528. expectErr bool
  529. }{
  530. {"Valid BlockID", validBlockID.Hash, validBlockID.PartSetHeader, false},
  531. {"Invalid BlockID", invalidBlockID.Hash, validBlockID.PartSetHeader, true},
  532. {"Invalid BlockID", validBlockID.Hash, invalidBlockID.PartSetHeader, true},
  533. }
  534. for _, tc := range testCases {
  535. tc := tc
  536. t.Run(tc.testName, func(t *testing.T) {
  537. blockID := BlockID{
  538. Hash: tc.blockIDHash,
  539. PartSetHeader: tc.blockIDPartSetHeader,
  540. }
  541. assert.Equal(t, tc.expectErr, blockID.ValidateBasic() != nil, "Validate Basic had an unexpected result")
  542. })
  543. }
  544. }
  545. func TestBlockProtoBuf(t *testing.T) {
  546. h := tmrand.Int63()
  547. c1 := randCommit(time.Now())
  548. b1 := MakeBlock(h, []Tx{Tx([]byte{1})}, &Commit{Signatures: []CommitSig{}}, []Evidence{})
  549. b1.ProposerAddress = tmrand.Bytes(crypto.AddressSize)
  550. b2 := MakeBlock(h, []Tx{Tx([]byte{1})}, c1, []Evidence{})
  551. b2.ProposerAddress = tmrand.Bytes(crypto.AddressSize)
  552. evidenceTime := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
  553. evi := NewMockDuplicateVoteEvidence(h, evidenceTime, "block-test-chain")
  554. b2.Evidence = EvidenceData{Evidence: EvidenceList{evi}}
  555. b2.EvidenceHash = b2.Evidence.Hash()
  556. b3 := MakeBlock(h, []Tx{}, c1, []Evidence{})
  557. b3.ProposerAddress = tmrand.Bytes(crypto.AddressSize)
  558. testCases := []struct {
  559. msg string
  560. b1 *Block
  561. expPass bool
  562. expPass2 bool
  563. }{
  564. {"nil block", nil, false, false},
  565. {"b1", b1, true, true},
  566. {"b2", b2, true, true},
  567. {"b3", b3, true, true},
  568. }
  569. for _, tc := range testCases {
  570. pb, err := tc.b1.ToProto()
  571. if tc.expPass {
  572. require.NoError(t, err, tc.msg)
  573. } else {
  574. require.Error(t, err, tc.msg)
  575. }
  576. block, err := BlockFromProto(pb)
  577. if tc.expPass2 {
  578. require.NoError(t, err, tc.msg)
  579. require.EqualValues(t, tc.b1.Header, block.Header, tc.msg)
  580. require.EqualValues(t, tc.b1.Data, block.Data, tc.msg)
  581. require.EqualValues(t, tc.b1.Evidence.Evidence, block.Evidence.Evidence, tc.msg)
  582. require.EqualValues(t, *tc.b1.LastCommit, *block.LastCommit, tc.msg)
  583. } else {
  584. require.Error(t, err, tc.msg)
  585. }
  586. }
  587. }
  588. func TestDataProtoBuf(t *testing.T) {
  589. data := &Data{Txs: Txs{Tx([]byte{1}), Tx([]byte{2}), Tx([]byte{3})}}
  590. data2 := &Data{Txs: Txs{}}
  591. testCases := []struct {
  592. msg string
  593. data1 *Data
  594. expPass bool
  595. }{
  596. {"success", data, true},
  597. {"success data2", data2, true},
  598. }
  599. for _, tc := range testCases {
  600. protoData := tc.data1.ToProto()
  601. d, err := DataFromProto(&protoData)
  602. if tc.expPass {
  603. require.NoError(t, err, tc.msg)
  604. require.EqualValues(t, tc.data1, &d, tc.msg)
  605. } else {
  606. require.Error(t, err, tc.msg)
  607. }
  608. }
  609. }
  610. // TestEvidenceDataProtoBuf ensures parity in converting to and from proto.
  611. func TestEvidenceDataProtoBuf(t *testing.T) {
  612. const chainID = "mychain"
  613. ev := NewMockDuplicateVoteEvidence(math.MaxInt64, time.Now(), chainID)
  614. data := &EvidenceData{Evidence: EvidenceList{ev}}
  615. _ = data.ByteSize()
  616. testCases := []struct {
  617. msg string
  618. data1 *EvidenceData
  619. expPass1 bool
  620. expPass2 bool
  621. }{
  622. {"success", data, true, true},
  623. {"empty evidenceData", &EvidenceData{Evidence: EvidenceList{}}, true, true},
  624. {"fail nil Data", nil, false, false},
  625. }
  626. for _, tc := range testCases {
  627. protoData, err := tc.data1.ToProto()
  628. if tc.expPass1 {
  629. require.NoError(t, err, tc.msg)
  630. } else {
  631. require.Error(t, err, tc.msg)
  632. }
  633. eviD := new(EvidenceData)
  634. err = eviD.FromProto(protoData)
  635. if tc.expPass2 {
  636. require.NoError(t, err, tc.msg)
  637. require.Equal(t, tc.data1, eviD, tc.msg)
  638. } else {
  639. require.Error(t, err, tc.msg)
  640. }
  641. }
  642. }
  643. func makeRandHeader() Header {
  644. chainID := "test"
  645. t := time.Now()
  646. height := tmrand.Int63()
  647. randBytes := tmrand.Bytes(tmhash.Size)
  648. randAddress := tmrand.Bytes(crypto.AddressSize)
  649. h := Header{
  650. Version: tmversion.Consensus{Block: version.BlockProtocol, App: 1},
  651. ChainID: chainID,
  652. Height: height,
  653. Time: t,
  654. LastBlockID: BlockID{},
  655. LastCommitHash: randBytes,
  656. DataHash: randBytes,
  657. ValidatorsHash: randBytes,
  658. NextValidatorsHash: randBytes,
  659. ConsensusHash: randBytes,
  660. AppHash: randBytes,
  661. LastResultsHash: randBytes,
  662. EvidenceHash: randBytes,
  663. ProposerAddress: randAddress,
  664. }
  665. return h
  666. }
  667. func TestHeaderProto(t *testing.T) {
  668. h1 := makeRandHeader()
  669. tc := []struct {
  670. msg string
  671. h1 *Header
  672. expPass bool
  673. }{
  674. {"success", &h1, true},
  675. {"failure empty Header", &Header{}, false},
  676. }
  677. for _, tt := range tc {
  678. tt := tt
  679. t.Run(tt.msg, func(t *testing.T) {
  680. pb := tt.h1.ToProto()
  681. h, err := HeaderFromProto(pb)
  682. if tt.expPass {
  683. require.NoError(t, err, tt.msg)
  684. require.Equal(t, tt.h1, &h, tt.msg)
  685. } else {
  686. require.Error(t, err, tt.msg)
  687. }
  688. })
  689. }
  690. }
  691. func TestBlockIDProtoBuf(t *testing.T) {
  692. blockID := makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))
  693. testCases := []struct {
  694. msg string
  695. bid1 *BlockID
  696. expPass bool
  697. }{
  698. {"success", &blockID, true},
  699. {"success empty", &BlockID{}, true},
  700. {"failure BlockID nil", nil, false},
  701. }
  702. for _, tc := range testCases {
  703. protoBlockID := tc.bid1.ToProto()
  704. bi, err := BlockIDFromProto(&protoBlockID)
  705. if tc.expPass {
  706. require.NoError(t, err)
  707. require.Equal(t, tc.bid1, bi, tc.msg)
  708. } else {
  709. require.NotEqual(t, tc.bid1, bi, tc.msg)
  710. }
  711. }
  712. }
  713. func TestSignedHeaderProtoBuf(t *testing.T) {
  714. commit := randCommit(time.Now())
  715. h := makeRandHeader()
  716. sh := SignedHeader{Header: &h, Commit: commit}
  717. testCases := []struct {
  718. msg string
  719. sh1 *SignedHeader
  720. expPass bool
  721. }{
  722. {"empty SignedHeader 2", &SignedHeader{}, true},
  723. {"success", &sh, true},
  724. {"failure nil", nil, false},
  725. }
  726. for _, tc := range testCases {
  727. protoSignedHeader := tc.sh1.ToProto()
  728. sh, err := SignedHeaderFromProto(protoSignedHeader)
  729. if tc.expPass {
  730. require.NoError(t, err, tc.msg)
  731. require.Equal(t, tc.sh1, sh, tc.msg)
  732. } else {
  733. require.Error(t, err, tc.msg)
  734. }
  735. }
  736. }
  737. func TestBlockIDEquals(t *testing.T) {
  738. var (
  739. blockID = makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))
  740. blockIDDuplicate = makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))
  741. blockIDDifferent = makeBlockID([]byte("different_hash"), 2, []byte("part_set_hash"))
  742. blockIDEmpty = BlockID{}
  743. )
  744. assert.True(t, blockID.Equals(blockIDDuplicate))
  745. assert.False(t, blockID.Equals(blockIDDifferent))
  746. assert.False(t, blockID.Equals(blockIDEmpty))
  747. assert.True(t, blockIDEmpty.Equals(blockIDEmpty))
  748. assert.False(t, blockIDEmpty.Equals(blockIDDifferent))
  749. }