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.

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