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.

828 lines
24 KiB

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