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.

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