You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

872 lines
25 KiB

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