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.

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