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.

1308 lines
36 KiB

max-bytes PR follow-up (#2318) * ReapMaxTxs: return all txs if max is negative this mirrors ReapMaxBytes behavior See https://github.com/tendermint/tendermint/pull/2184#discussion_r214439950 * increase MaxAminoOverheadForBlock tested with: ``` func TestMaxAminoOverheadForBlock(t *testing.T) { maxChainID := "" for i := 0; i < MaxChainIDLen; i++ { maxChainID += "𠜎" } h := Header{ ChainID: maxChainID, Height: 10, Time: time.Now().UTC(), NumTxs: 100, TotalTxs: 200, LastBlockID: makeBlockID(make([]byte, 20), 300, make([]byte, 20)), LastCommitHash: tmhash.Sum([]byte("last_commit_hash")), DataHash: tmhash.Sum([]byte("data_hash")), ValidatorsHash: tmhash.Sum([]byte("validators_hash")), NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")), ConsensusHash: tmhash.Sum([]byte("consensus_hash")), AppHash: tmhash.Sum([]byte("app_hash")), LastResultsHash: tmhash.Sum([]byte("last_results_hash")), EvidenceHash: tmhash.Sum([]byte("evidence_hash")), ProposerAddress: tmhash.Sum([]byte("proposer_address")), } b := Block{ Header: h, Data: Data{Txs: makeTxs(10000, 100)}, Evidence: EvidenceData{}, LastCommit: &Commit{}, } bz, err := cdc.MarshalBinary(b) require.NoError(t, err) assert.Equal(t, MaxHeaderBytes+MaxAminoOverheadForBlock-2, len(bz)-1000000-20000-1) } ``` * fix MaxYYY constants calculation by using math.MaxInt64 See https://github.com/tendermint/tendermint/pull/2184#discussion_r214444244 * pass mempool filter as an option See https://github.com/tendermint/tendermint/pull/2184#discussion_r214445869 * fixes after Dev's comments
6 years ago
max-bytes PR follow-up (#2318) * ReapMaxTxs: return all txs if max is negative this mirrors ReapMaxBytes behavior See https://github.com/tendermint/tendermint/pull/2184#discussion_r214439950 * increase MaxAminoOverheadForBlock tested with: ``` func TestMaxAminoOverheadForBlock(t *testing.T) { maxChainID := "" for i := 0; i < MaxChainIDLen; i++ { maxChainID += "𠜎" } h := Header{ ChainID: maxChainID, Height: 10, Time: time.Now().UTC(), NumTxs: 100, TotalTxs: 200, LastBlockID: makeBlockID(make([]byte, 20), 300, make([]byte, 20)), LastCommitHash: tmhash.Sum([]byte("last_commit_hash")), DataHash: tmhash.Sum([]byte("data_hash")), ValidatorsHash: tmhash.Sum([]byte("validators_hash")), NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")), ConsensusHash: tmhash.Sum([]byte("consensus_hash")), AppHash: tmhash.Sum([]byte("app_hash")), LastResultsHash: tmhash.Sum([]byte("last_results_hash")), EvidenceHash: tmhash.Sum([]byte("evidence_hash")), ProposerAddress: tmhash.Sum([]byte("proposer_address")), } b := Block{ Header: h, Data: Data{Txs: makeTxs(10000, 100)}, Evidence: EvidenceData{}, LastCommit: &Commit{}, } bz, err := cdc.MarshalBinary(b) require.NoError(t, err) assert.Equal(t, MaxHeaderBytes+MaxAminoOverheadForBlock-2, len(bz)-1000000-20000-1) } ``` * fix MaxYYY constants calculation by using math.MaxInt64 See https://github.com/tendermint/tendermint/pull/2184#discussion_r214444244 * pass mempool filter as an option See https://github.com/tendermint/tendermint/pull/2184#discussion_r214445869 * fixes after Dev's comments
6 years ago
  1. package types
  2. import (
  3. // it is ok to use math/rand here: we do not need a cryptographically secure random
  4. // number generator here and we can run the tests a bit faster
  5. "crypto/rand"
  6. "encoding/hex"
  7. "math"
  8. "os"
  9. "reflect"
  10. "testing"
  11. "time"
  12. gogotypes "github.com/gogo/protobuf/types"
  13. "github.com/stretchr/testify/assert"
  14. "github.com/stretchr/testify/require"
  15. "github.com/tendermint/tendermint/crypto"
  16. "github.com/tendermint/tendermint/crypto/merkle"
  17. "github.com/tendermint/tendermint/crypto/tmhash"
  18. "github.com/tendermint/tendermint/libs/bits"
  19. "github.com/tendermint/tendermint/libs/bytes"
  20. tmrand "github.com/tendermint/tendermint/libs/rand"
  21. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  22. tmversion "github.com/tendermint/tendermint/proto/tendermint/version"
  23. tmtime "github.com/tendermint/tendermint/types/time"
  24. "github.com/tendermint/tendermint/version"
  25. )
  26. func TestMain(m *testing.M) {
  27. code := m.Run()
  28. os.Exit(code)
  29. }
  30. func TestBlockAddEvidence(t *testing.T) {
  31. txs := []Tx{Tx("foo"), Tx("bar")}
  32. lastID := makeBlockIDRandom()
  33. h := int64(3)
  34. voteSet, _, vals := randVoteSet(h-1, 1, tmproto.PrecommitType, 10, 1)
  35. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, time.Now())
  36. require.NoError(t, err)
  37. ev := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain")
  38. evList := []Evidence{ev}
  39. block := MakeBlock(h, txs, commit, evList)
  40. require.NotNil(t, block)
  41. require.Equal(t, 1, len(block.Evidence.Evidence))
  42. require.NotNil(t, block.EvidenceHash)
  43. }
  44. func TestBlockValidateBasic(t *testing.T) {
  45. require.Error(t, (*Block)(nil).ValidateBasic())
  46. txs := []Tx{Tx("foo"), Tx("bar")}
  47. lastID := makeBlockIDRandom()
  48. h := int64(3)
  49. voteSet, valSet, vals := randVoteSet(h-1, 1, tmproto.PrecommitType, 10, 1)
  50. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, time.Now())
  51. require.NoError(t, err)
  52. ev := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain")
  53. evList := []Evidence{ev}
  54. testCases := []struct {
  55. testName string
  56. malleateBlock func(*Block)
  57. expErr bool
  58. }{
  59. {"Make Block", func(blk *Block) {}, false},
  60. {"Make Block w/ proposer Addr", func(blk *Block) { blk.ProposerAddress = valSet.GetProposer().Address }, false},
  61. {"Negative Height", func(blk *Block) { blk.Height = -1 }, true},
  62. {"Remove 1/2 the commits", func(blk *Block) {
  63. blk.LastCommit.Signatures = commit.Signatures[:commit.Size()/2]
  64. blk.LastCommit.hash = nil // clear hash or change wont be noticed
  65. }, true},
  66. {"Remove LastCommitHash", func(blk *Block) { blk.LastCommitHash = []byte("something else") }, true},
  67. {"Tampered Data", func(blk *Block) {
  68. blk.Data.Txs[0] = Tx("something else")
  69. blk.Data.hash = nil // clear hash or change wont be noticed
  70. }, true},
  71. {"Tampered DataHash", func(blk *Block) {
  72. blk.DataHash = tmrand.Bytes(len(blk.DataHash))
  73. }, true},
  74. {"Tampered EvidenceHash", func(blk *Block) {
  75. blk.EvidenceHash = tmrand.Bytes(len(blk.EvidenceHash))
  76. }, true},
  77. {"Incorrect block protocol version", func(blk *Block) {
  78. blk.Version.Block = 1
  79. }, true},
  80. {"Missing LastCommit", func(blk *Block) {
  81. blk.LastCommit = nil
  82. }, true},
  83. {"Invalid LastCommit", func(blk *Block) {
  84. blk.LastCommit = NewCommit(-1, 0, *voteSet.maj23, nil)
  85. }, true},
  86. {"Invalid Evidence", func(blk *Block) {
  87. emptyEv := &DuplicateVoteEvidence{}
  88. blk.Evidence = EvidenceData{Evidence: []Evidence{emptyEv}}
  89. }, true},
  90. }
  91. for i, tc := range testCases {
  92. tc := tc
  93. i := i
  94. t.Run(tc.testName, func(t *testing.T) {
  95. block := MakeBlock(h, txs, commit, evList)
  96. block.ProposerAddress = valSet.GetProposer().Address
  97. tc.malleateBlock(block)
  98. err = block.ValidateBasic()
  99. t.Log(err)
  100. assert.Equal(t, tc.expErr, err != nil, "#%d: %v", i, err)
  101. })
  102. }
  103. }
  104. func TestBlockHash(t *testing.T) {
  105. assert.Nil(t, (*Block)(nil).Hash())
  106. assert.Nil(t, MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil, nil).Hash())
  107. }
  108. func TestBlockMakePartSet(t *testing.T) {
  109. assert.Nil(t, (*Block)(nil).MakePartSet(2))
  110. partSet := MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil, nil).MakePartSet(1024)
  111. assert.NotNil(t, partSet)
  112. assert.EqualValues(t, 1, partSet.Total())
  113. }
  114. func TestBlockMakePartSetWithEvidence(t *testing.T) {
  115. assert.Nil(t, (*Block)(nil).MakePartSet(2))
  116. lastID := makeBlockIDRandom()
  117. h := int64(3)
  118. voteSet, _, vals := randVoteSet(h-1, 1, tmproto.PrecommitType, 10, 1)
  119. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, time.Now())
  120. require.NoError(t, err)
  121. ev := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain")
  122. evList := []Evidence{ev}
  123. partSet := MakeBlock(h, []Tx{Tx("Hello World")}, commit, evList).MakePartSet(512)
  124. assert.NotNil(t, partSet)
  125. assert.EqualValues(t, 4, partSet.Total())
  126. }
  127. func TestBlockHashesTo(t *testing.T) {
  128. assert.False(t, (*Block)(nil).HashesTo(nil))
  129. lastID := makeBlockIDRandom()
  130. h := int64(3)
  131. voteSet, valSet, vals := randVoteSet(h-1, 1, tmproto.PrecommitType, 10, 1)
  132. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, time.Now())
  133. require.NoError(t, err)
  134. ev := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain")
  135. evList := []Evidence{ev}
  136. block := MakeBlock(h, []Tx{Tx("Hello World")}, commit, evList)
  137. block.ValidatorsHash = valSet.Hash()
  138. assert.False(t, block.HashesTo([]byte{}))
  139. assert.False(t, block.HashesTo([]byte("something else")))
  140. assert.True(t, block.HashesTo(block.Hash()))
  141. }
  142. func TestBlockSize(t *testing.T) {
  143. size := MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil, nil).Size()
  144. if size <= 0 {
  145. t.Fatal("Size of the block is zero or negative")
  146. }
  147. }
  148. func TestBlockString(t *testing.T) {
  149. assert.Equal(t, "nil-Block", (*Block)(nil).String())
  150. assert.Equal(t, "nil-Block", (*Block)(nil).StringIndented(""))
  151. assert.Equal(t, "nil-Block", (*Block)(nil).StringShort())
  152. block := MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil, nil)
  153. assert.NotEqual(t, "nil-Block", block.String())
  154. assert.NotEqual(t, "nil-Block", block.StringIndented(""))
  155. assert.NotEqual(t, "nil-Block", block.StringShort())
  156. }
  157. func makeBlockIDRandom() BlockID {
  158. var (
  159. blockHash = make([]byte, tmhash.Size)
  160. partSetHash = make([]byte, tmhash.Size)
  161. )
  162. rand.Read(blockHash) //nolint: errcheck // ignore errcheck for read
  163. rand.Read(partSetHash) //nolint: errcheck // ignore errcheck for read
  164. return BlockID{blockHash, PartSetHeader{123, partSetHash}}
  165. }
  166. func makeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) BlockID {
  167. var (
  168. h = make([]byte, tmhash.Size)
  169. psH = make([]byte, tmhash.Size)
  170. )
  171. copy(h, hash)
  172. copy(psH, partSetHash)
  173. return BlockID{
  174. Hash: h,
  175. PartSetHeader: PartSetHeader{
  176. Total: partSetSize,
  177. Hash: psH,
  178. },
  179. }
  180. }
  181. var nilBytes []byte
  182. // This follows RFC-6962, i.e. `echo -n '' | sha256sum`
  183. var emptyBytes = []byte{0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8,
  184. 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b,
  185. 0x78, 0x52, 0xb8, 0x55}
  186. func TestNilHeaderHashDoesntCrash(t *testing.T) {
  187. assert.Equal(t, nilBytes, []byte((*Header)(nil).Hash()))
  188. assert.Equal(t, nilBytes, []byte((new(Header)).Hash()))
  189. }
  190. func TestNilDataHashDoesntCrash(t *testing.T) {
  191. assert.Equal(t, emptyBytes, []byte((*Data)(nil).Hash()))
  192. assert.Equal(t, emptyBytes, []byte(new(Data).Hash()))
  193. }
  194. func TestCommit(t *testing.T) {
  195. lastID := makeBlockIDRandom()
  196. h := int64(3)
  197. voteSet, _, vals := randVoteSet(h-1, 1, tmproto.PrecommitType, 10, 1)
  198. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, time.Now())
  199. require.NoError(t, err)
  200. assert.Equal(t, h-1, commit.Height)
  201. assert.EqualValues(t, 1, commit.Round)
  202. assert.Equal(t, tmproto.PrecommitType, tmproto.SignedMsgType(commit.Type()))
  203. if commit.Size() <= 0 {
  204. t.Fatalf("commit %v has a zero or negative size: %d", commit, commit.Size())
  205. }
  206. require.NotNil(t, commit.BitArray())
  207. assert.Equal(t, bits.NewBitArray(10).Size(), commit.BitArray().Size())
  208. assert.Equal(t, voteSet.GetByIndex(0), commit.GetByIndex(0))
  209. assert.True(t, commit.IsCommit())
  210. }
  211. func TestCommitValidateBasic(t *testing.T) {
  212. testCases := []struct {
  213. testName string
  214. malleateCommit func(*Commit)
  215. expectErr bool
  216. }{
  217. {"Random Commit", func(com *Commit) {}, false},
  218. {"Incorrect signature", func(com *Commit) { com.Signatures[0].Signature = []byte{0} }, false},
  219. {"Incorrect height", func(com *Commit) { com.Height = int64(-100) }, true},
  220. {"Incorrect round", func(com *Commit) { com.Round = -100 }, true},
  221. }
  222. for _, tc := range testCases {
  223. tc := tc
  224. t.Run(tc.testName, func(t *testing.T) {
  225. com := randCommit(time.Now())
  226. tc.malleateCommit(com)
  227. assert.Equal(t, tc.expectErr, com.ValidateBasic() != nil, "Validate Basic had an unexpected result")
  228. })
  229. }
  230. }
  231. func TestMaxCommitBytes(t *testing.T) {
  232. // time is varint encoded so need to pick the max.
  233. // year int, month Month, day, hour, min, sec, nsec int, loc *Location
  234. timestamp := time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC)
  235. cs := CommitSig{
  236. BlockIDFlag: BlockIDFlagNil,
  237. ValidatorAddress: crypto.AddressHash([]byte("validator_address")),
  238. Timestamp: timestamp,
  239. Signature: crypto.CRandBytes(MaxSignatureSize),
  240. }
  241. pbSig := cs.ToProto()
  242. // test that a single commit sig doesn't exceed max commit sig bytes
  243. assert.EqualValues(t, MaxCommitSigBytes, pbSig.Size())
  244. // check size with a single commit
  245. commit := &Commit{
  246. Height: math.MaxInt64,
  247. Round: math.MaxInt32,
  248. BlockID: BlockID{
  249. Hash: tmhash.Sum([]byte("blockID_hash")),
  250. PartSetHeader: PartSetHeader{
  251. Total: math.MaxInt32,
  252. Hash: tmhash.Sum([]byte("blockID_part_set_header_hash")),
  253. },
  254. },
  255. Signatures: []CommitSig{cs},
  256. }
  257. pb := commit.ToProto()
  258. assert.EqualValues(t, MaxCommitBytes(1), int64(pb.Size()))
  259. // check the upper bound of the commit size
  260. for i := 1; i < MaxVotesCount; i++ {
  261. commit.Signatures = append(commit.Signatures, cs)
  262. }
  263. pb = commit.ToProto()
  264. assert.EqualValues(t, MaxCommitBytes(MaxVotesCount), int64(pb.Size()))
  265. }
  266. func TestHeaderHash(t *testing.T) {
  267. testCases := []struct {
  268. desc string
  269. header *Header
  270. expectHash bytes.HexBytes
  271. }{
  272. {"Generates expected hash", &Header{
  273. Version: tmversion.Consensus{Block: 1, App: 2},
  274. ChainID: "chainId",
  275. Height: 3,
  276. Time: time.Date(2019, 10, 13, 16, 14, 44, 0, time.UTC),
  277. LastBlockID: makeBlockID(make([]byte, tmhash.Size), 6, make([]byte, tmhash.Size)),
  278. LastCommitHash: tmhash.Sum([]byte("last_commit_hash")),
  279. DataHash: tmhash.Sum([]byte("data_hash")),
  280. ValidatorsHash: tmhash.Sum([]byte("validators_hash")),
  281. NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")),
  282. ConsensusHash: tmhash.Sum([]byte("consensus_hash")),
  283. AppHash: tmhash.Sum([]byte("app_hash")),
  284. LastResultsHash: tmhash.Sum([]byte("last_results_hash")),
  285. EvidenceHash: tmhash.Sum([]byte("evidence_hash")),
  286. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  287. }, hexBytesFromString("F740121F553B5418C3EFBD343C2DBFE9E007BB67B0D020A0741374BAB65242A4")},
  288. {"nil header yields nil", nil, nil},
  289. {"nil ValidatorsHash yields nil", &Header{
  290. Version: tmversion.Consensus{Block: 1, App: 2},
  291. ChainID: "chainId",
  292. Height: 3,
  293. Time: time.Date(2019, 10, 13, 16, 14, 44, 0, time.UTC),
  294. LastBlockID: makeBlockID(make([]byte, tmhash.Size), 6, make([]byte, tmhash.Size)),
  295. LastCommitHash: tmhash.Sum([]byte("last_commit_hash")),
  296. DataHash: tmhash.Sum([]byte("data_hash")),
  297. ValidatorsHash: nil,
  298. NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")),
  299. ConsensusHash: tmhash.Sum([]byte("consensus_hash")),
  300. AppHash: tmhash.Sum([]byte("app_hash")),
  301. LastResultsHash: tmhash.Sum([]byte("last_results_hash")),
  302. EvidenceHash: tmhash.Sum([]byte("evidence_hash")),
  303. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  304. }, nil},
  305. }
  306. for _, tc := range testCases {
  307. tc := tc
  308. t.Run(tc.desc, func(t *testing.T) {
  309. assert.Equal(t, tc.expectHash, tc.header.Hash())
  310. // We also make sure that all fields are hashed in struct order, and that all
  311. // fields in the test struct are non-zero.
  312. if tc.header != nil && tc.expectHash != nil {
  313. byteSlices := [][]byte{}
  314. s := reflect.ValueOf(*tc.header)
  315. for i := 0; i < s.NumField(); i++ {
  316. f := s.Field(i)
  317. assert.False(t, f.IsZero(), "Found zero-valued field %v",
  318. s.Type().Field(i).Name)
  319. switch f := f.Interface().(type) {
  320. case int64, bytes.HexBytes, string:
  321. byteSlices = append(byteSlices, cdcEncode(f))
  322. case time.Time:
  323. bz, err := gogotypes.StdTimeMarshal(f)
  324. require.NoError(t, err)
  325. byteSlices = append(byteSlices, bz)
  326. case tmversion.Consensus:
  327. bz, err := f.Marshal()
  328. require.NoError(t, err)
  329. byteSlices = append(byteSlices, bz)
  330. case BlockID:
  331. pbbi := f.ToProto()
  332. bz, err := pbbi.Marshal()
  333. require.NoError(t, err)
  334. byteSlices = append(byteSlices, bz)
  335. default:
  336. t.Errorf("unknown type %T", f)
  337. }
  338. }
  339. assert.Equal(t,
  340. bytes.HexBytes(merkle.HashFromByteSlices(byteSlices)), tc.header.Hash())
  341. }
  342. })
  343. }
  344. }
  345. func TestMaxHeaderBytes(t *testing.T) {
  346. // Construct a UTF-8 string of MaxChainIDLen length using the supplementary
  347. // characters.
  348. // Each supplementary character takes 4 bytes.
  349. // http://www.i18nguy.com/unicode/supplementary-test.html
  350. maxChainID := ""
  351. for i := 0; i < MaxChainIDLen; i++ {
  352. maxChainID += "𠜎"
  353. }
  354. // time is varint encoded so need to pick the max.
  355. // year int, month Month, day, hour, min, sec, nsec int, loc *Location
  356. timestamp := time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC)
  357. h := Header{
  358. Version: tmversion.Consensus{Block: math.MaxInt64, App: math.MaxInt64},
  359. ChainID: maxChainID,
  360. Height: math.MaxInt64,
  361. Time: timestamp,
  362. LastBlockID: makeBlockID(make([]byte, tmhash.Size), math.MaxInt32, make([]byte, tmhash.Size)),
  363. LastCommitHash: tmhash.Sum([]byte("last_commit_hash")),
  364. DataHash: tmhash.Sum([]byte("data_hash")),
  365. ValidatorsHash: tmhash.Sum([]byte("validators_hash")),
  366. NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")),
  367. ConsensusHash: tmhash.Sum([]byte("consensus_hash")),
  368. AppHash: tmhash.Sum([]byte("app_hash")),
  369. LastResultsHash: tmhash.Sum([]byte("last_results_hash")),
  370. EvidenceHash: tmhash.Sum([]byte("evidence_hash")),
  371. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  372. }
  373. bz, err := h.ToProto().Marshal()
  374. require.NoError(t, err)
  375. assert.EqualValues(t, MaxHeaderBytes, int64(len(bz)))
  376. }
  377. func randCommit(now time.Time) *Commit {
  378. lastID := makeBlockIDRandom()
  379. h := int64(3)
  380. voteSet, _, vals := randVoteSet(h-1, 1, tmproto.PrecommitType, 10, 1)
  381. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, now)
  382. if err != nil {
  383. panic(err)
  384. }
  385. return commit
  386. }
  387. func hexBytesFromString(s string) bytes.HexBytes {
  388. b, err := hex.DecodeString(s)
  389. if err != nil {
  390. panic(err)
  391. }
  392. return bytes.HexBytes(b)
  393. }
  394. func TestBlockMaxDataBytes(t *testing.T) {
  395. testCases := []struct {
  396. maxBytes int64
  397. valsCount int
  398. evidenceBytes int64
  399. panics bool
  400. result int64
  401. }{
  402. 0: {-10, 1, 0, true, 0},
  403. 1: {10, 1, 0, true, 0},
  404. 2: {841, 1, 0, true, 0},
  405. 3: {842, 1, 0, false, 0},
  406. 4: {843, 1, 0, false, 1},
  407. 5: {954, 2, 0, false, 1},
  408. 6: {1053, 2, 100, false, 0},
  409. }
  410. for i, tc := range testCases {
  411. tc := tc
  412. if tc.panics {
  413. assert.Panics(t, func() {
  414. MaxDataBytes(tc.maxBytes, tc.evidenceBytes, tc.valsCount)
  415. }, "#%v", i)
  416. } else {
  417. assert.Equal(t,
  418. tc.result,
  419. MaxDataBytes(tc.maxBytes, tc.evidenceBytes, tc.valsCount),
  420. "#%v", i)
  421. }
  422. }
  423. }
  424. func TestBlockMaxDataBytesNoEvidence(t *testing.T) {
  425. testCases := []struct {
  426. maxBytes int64
  427. valsCount int
  428. panics bool
  429. result int64
  430. }{
  431. 0: {-10, 1, true, 0},
  432. 1: {10, 1, true, 0},
  433. 2: {841, 1, true, 0},
  434. 3: {842, 1, false, 0},
  435. 4: {843, 1, false, 1},
  436. }
  437. for i, tc := range testCases {
  438. tc := tc
  439. if tc.panics {
  440. assert.Panics(t, func() {
  441. MaxDataBytesNoEvidence(tc.maxBytes, tc.valsCount)
  442. }, "#%v", i)
  443. } else {
  444. assert.Equal(t,
  445. tc.result,
  446. MaxDataBytesNoEvidence(tc.maxBytes, tc.valsCount),
  447. "#%v", i)
  448. }
  449. }
  450. }
  451. func TestCommitToVoteSet(t *testing.T) {
  452. lastID := makeBlockIDRandom()
  453. h := int64(3)
  454. voteSet, valSet, vals := randVoteSet(h-1, 1, tmproto.PrecommitType, 10, 1)
  455. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, time.Now())
  456. assert.NoError(t, err)
  457. chainID := voteSet.ChainID()
  458. voteSet2 := CommitToVoteSet(chainID, commit, valSet)
  459. for i := int32(0); int(i) < len(vals); i++ {
  460. vote1 := voteSet.GetByIndex(i)
  461. vote2 := voteSet2.GetByIndex(i)
  462. vote3 := commit.GetVote(i)
  463. vote1bz, err := vote1.ToProto().Marshal()
  464. require.NoError(t, err)
  465. vote2bz, err := vote2.ToProto().Marshal()
  466. require.NoError(t, err)
  467. vote3bz, err := vote3.ToProto().Marshal()
  468. require.NoError(t, err)
  469. assert.Equal(t, vote1bz, vote2bz)
  470. assert.Equal(t, vote1bz, vote3bz)
  471. }
  472. }
  473. func TestCommitToVoteSetWithVotesForNilBlock(t *testing.T) {
  474. blockID := makeBlockID([]byte("blockhash"), 1000, []byte("partshash"))
  475. const (
  476. height = int64(3)
  477. round = 0
  478. )
  479. type commitVoteTest struct {
  480. blockIDs []BlockID
  481. numVotes []int // must sum to numValidators
  482. numValidators int
  483. valid bool
  484. }
  485. testCases := []commitVoteTest{
  486. {[]BlockID{blockID, {}}, []int{67, 33}, 100, true},
  487. }
  488. for _, tc := range testCases {
  489. voteSet, valSet, vals := randVoteSet(height-1, round, tmproto.PrecommitType, tc.numValidators, 1)
  490. vi := int32(0)
  491. for n := range tc.blockIDs {
  492. for i := 0; i < tc.numVotes[n]; i++ {
  493. pubKey, err := vals[vi].GetPubKey()
  494. require.NoError(t, err)
  495. vote := &Vote{
  496. ValidatorAddress: pubKey.Address(),
  497. ValidatorIndex: vi,
  498. Height: height - 1,
  499. Round: round,
  500. Type: tmproto.PrecommitType,
  501. BlockID: tc.blockIDs[n],
  502. Timestamp: tmtime.Now(),
  503. }
  504. added, err := signAddVote(vals[vi], vote, voteSet)
  505. assert.NoError(t, err)
  506. assert.True(t, added)
  507. vi++
  508. }
  509. }
  510. if tc.valid {
  511. commit := voteSet.MakeCommit() // panics without > 2/3 valid votes
  512. assert.NotNil(t, commit)
  513. err := valSet.VerifyCommit(voteSet.ChainID(), blockID, height-1, commit)
  514. assert.Nil(t, err)
  515. } else {
  516. assert.Panics(t, func() { voteSet.MakeCommit() })
  517. }
  518. }
  519. }
  520. func TestBlockIDValidateBasic(t *testing.T) {
  521. validBlockID := BlockID{
  522. Hash: bytes.HexBytes{},
  523. PartSetHeader: PartSetHeader{
  524. Total: 1,
  525. Hash: bytes.HexBytes{},
  526. },
  527. }
  528. invalidBlockID := BlockID{
  529. Hash: []byte{0},
  530. PartSetHeader: PartSetHeader{
  531. Total: 1,
  532. Hash: []byte{0},
  533. },
  534. }
  535. testCases := []struct {
  536. testName string
  537. blockIDHash bytes.HexBytes
  538. blockIDPartSetHeader PartSetHeader
  539. expectErr bool
  540. }{
  541. {"Valid BlockID", validBlockID.Hash, validBlockID.PartSetHeader, false},
  542. {"Invalid BlockID", invalidBlockID.Hash, validBlockID.PartSetHeader, true},
  543. {"Invalid BlockID", validBlockID.Hash, invalidBlockID.PartSetHeader, true},
  544. }
  545. for _, tc := range testCases {
  546. tc := tc
  547. t.Run(tc.testName, func(t *testing.T) {
  548. blockID := BlockID{
  549. Hash: tc.blockIDHash,
  550. PartSetHeader: tc.blockIDPartSetHeader,
  551. }
  552. assert.Equal(t, tc.expectErr, blockID.ValidateBasic() != nil, "Validate Basic had an unexpected result")
  553. })
  554. }
  555. }
  556. func TestBlockProtoBuf(t *testing.T) {
  557. h := tmrand.Int63()
  558. c1 := randCommit(time.Now())
  559. b1 := MakeBlock(h, []Tx{Tx([]byte{1})}, &Commit{Signatures: []CommitSig{}}, []Evidence{})
  560. b1.ProposerAddress = tmrand.Bytes(crypto.AddressSize)
  561. b2 := MakeBlock(h, []Tx{Tx([]byte{1})}, c1, []Evidence{})
  562. b2.ProposerAddress = tmrand.Bytes(crypto.AddressSize)
  563. evidenceTime := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
  564. evi := NewMockDuplicateVoteEvidence(h, evidenceTime, "block-test-chain")
  565. b2.Evidence = EvidenceData{Evidence: EvidenceList{evi}}
  566. b2.EvidenceHash = b2.Evidence.Hash()
  567. b3 := MakeBlock(h, []Tx{}, c1, []Evidence{})
  568. b3.ProposerAddress = tmrand.Bytes(crypto.AddressSize)
  569. testCases := []struct {
  570. msg string
  571. b1 *Block
  572. expPass bool
  573. expPass2 bool
  574. }{
  575. {"nil block", nil, false, false},
  576. {"b1", b1, true, true},
  577. {"b2", b2, true, true},
  578. {"b3", b3, true, true},
  579. }
  580. for _, tc := range testCases {
  581. pb, err := tc.b1.ToProto()
  582. if tc.expPass {
  583. require.NoError(t, err, tc.msg)
  584. } else {
  585. require.Error(t, err, tc.msg)
  586. }
  587. block, err := BlockFromProto(pb)
  588. if tc.expPass2 {
  589. require.NoError(t, err, tc.msg)
  590. require.EqualValues(t, tc.b1.Header, block.Header, tc.msg)
  591. require.EqualValues(t, tc.b1.Data, block.Data, tc.msg)
  592. require.EqualValues(t, tc.b1.Evidence.Evidence, block.Evidence.Evidence, tc.msg)
  593. require.EqualValues(t, *tc.b1.LastCommit, *block.LastCommit, tc.msg)
  594. } else {
  595. require.Error(t, err, tc.msg)
  596. }
  597. }
  598. }
  599. func TestDataProtoBuf(t *testing.T) {
  600. data := &Data{Txs: Txs{Tx([]byte{1}), Tx([]byte{2}), Tx([]byte{3})}}
  601. data2 := &Data{Txs: Txs{}}
  602. testCases := []struct {
  603. msg string
  604. data1 *Data
  605. expPass bool
  606. }{
  607. {"success", data, true},
  608. {"success data2", data2, true},
  609. }
  610. for _, tc := range testCases {
  611. protoData := tc.data1.ToProto()
  612. d, err := DataFromProto(&protoData)
  613. if tc.expPass {
  614. require.NoError(t, err, tc.msg)
  615. require.EqualValues(t, tc.data1, &d, tc.msg)
  616. } else {
  617. require.Error(t, err, tc.msg)
  618. }
  619. }
  620. }
  621. // TestEvidenceDataProtoBuf ensures parity in converting to and from proto.
  622. func TestEvidenceDataProtoBuf(t *testing.T) {
  623. const chainID = "mychain"
  624. ev := NewMockDuplicateVoteEvidence(math.MaxInt64, time.Now(), chainID)
  625. data := &EvidenceData{Evidence: EvidenceList{ev}}
  626. _ = data.ByteSize()
  627. testCases := []struct {
  628. msg string
  629. data1 *EvidenceData
  630. expPass1 bool
  631. expPass2 bool
  632. }{
  633. {"success", data, true, true},
  634. {"empty evidenceData", &EvidenceData{Evidence: EvidenceList{}}, true, true},
  635. {"fail nil Data", nil, false, false},
  636. }
  637. for _, tc := range testCases {
  638. protoData, err := tc.data1.ToProto()
  639. if tc.expPass1 {
  640. require.NoError(t, err, tc.msg)
  641. } else {
  642. require.Error(t, err, tc.msg)
  643. }
  644. eviD := new(EvidenceData)
  645. err = eviD.FromProto(protoData)
  646. if tc.expPass2 {
  647. require.NoError(t, err, tc.msg)
  648. require.Equal(t, tc.data1, eviD, tc.msg)
  649. } else {
  650. require.Error(t, err, tc.msg)
  651. }
  652. }
  653. }
  654. func makeRandHeader() Header {
  655. chainID := "test"
  656. t := time.Now()
  657. height := tmrand.Int63()
  658. randBytes := tmrand.Bytes(tmhash.Size)
  659. randAddress := tmrand.Bytes(crypto.AddressSize)
  660. h := Header{
  661. Version: tmversion.Consensus{Block: version.BlockProtocol, App: 1},
  662. ChainID: chainID,
  663. Height: height,
  664. Time: t,
  665. LastBlockID: BlockID{},
  666. LastCommitHash: randBytes,
  667. DataHash: randBytes,
  668. ValidatorsHash: randBytes,
  669. NextValidatorsHash: randBytes,
  670. ConsensusHash: randBytes,
  671. AppHash: randBytes,
  672. LastResultsHash: randBytes,
  673. EvidenceHash: randBytes,
  674. ProposerAddress: randAddress,
  675. }
  676. return h
  677. }
  678. func TestHeaderProto(t *testing.T) {
  679. h1 := makeRandHeader()
  680. tc := []struct {
  681. msg string
  682. h1 *Header
  683. expPass bool
  684. }{
  685. {"success", &h1, true},
  686. {"failure empty Header", &Header{}, false},
  687. }
  688. for _, tt := range tc {
  689. tt := tt
  690. t.Run(tt.msg, func(t *testing.T) {
  691. pb := tt.h1.ToProto()
  692. h, err := HeaderFromProto(pb)
  693. if tt.expPass {
  694. require.NoError(t, err, tt.msg)
  695. require.Equal(t, tt.h1, &h, tt.msg)
  696. } else {
  697. require.Error(t, err, tt.msg)
  698. }
  699. })
  700. }
  701. }
  702. func TestBlockIDProtoBuf(t *testing.T) {
  703. blockID := makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))
  704. testCases := []struct {
  705. msg string
  706. bid1 *BlockID
  707. expPass bool
  708. }{
  709. {"success", &blockID, true},
  710. {"success empty", &BlockID{}, true},
  711. {"failure BlockID nil", nil, false},
  712. }
  713. for _, tc := range testCases {
  714. protoBlockID := tc.bid1.ToProto()
  715. bi, err := BlockIDFromProto(&protoBlockID)
  716. if tc.expPass {
  717. require.NoError(t, err)
  718. require.Equal(t, tc.bid1, bi, tc.msg)
  719. } else {
  720. require.NotEqual(t, tc.bid1, bi, tc.msg)
  721. }
  722. }
  723. }
  724. func TestSignedHeaderProtoBuf(t *testing.T) {
  725. commit := randCommit(time.Now())
  726. h := makeRandHeader()
  727. sh := SignedHeader{Header: &h, Commit: commit}
  728. testCases := []struct {
  729. msg string
  730. sh1 *SignedHeader
  731. expPass bool
  732. }{
  733. {"empty SignedHeader 2", &SignedHeader{}, true},
  734. {"success", &sh, true},
  735. {"failure nil", nil, false},
  736. }
  737. for _, tc := range testCases {
  738. protoSignedHeader := tc.sh1.ToProto()
  739. sh, err := SignedHeaderFromProto(protoSignedHeader)
  740. if tc.expPass {
  741. require.NoError(t, err, tc.msg)
  742. require.Equal(t, tc.sh1, sh, tc.msg)
  743. } else {
  744. require.Error(t, err, tc.msg)
  745. }
  746. }
  747. }
  748. func TestBlockIDEquals(t *testing.T) {
  749. var (
  750. blockID = makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))
  751. blockIDDuplicate = makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))
  752. blockIDDifferent = makeBlockID([]byte("different_hash"), 2, []byte("part_set_hash"))
  753. blockIDEmpty = BlockID{}
  754. )
  755. assert.True(t, blockID.Equals(blockIDDuplicate))
  756. assert.False(t, blockID.Equals(blockIDDifferent))
  757. assert.False(t, blockID.Equals(blockIDEmpty))
  758. assert.True(t, blockIDEmpty.Equals(blockIDEmpty))
  759. assert.False(t, blockIDEmpty.Equals(blockIDDifferent))
  760. }
  761. func TestCommitSig_ValidateBasic(t *testing.T) {
  762. testCases := []struct {
  763. name string
  764. cs CommitSig
  765. expectErr bool
  766. errString string
  767. }{
  768. {
  769. "invalid ID flag",
  770. CommitSig{BlockIDFlag: BlockIDFlag(0xFF)},
  771. true, "unknown BlockIDFlag",
  772. },
  773. {
  774. "BlockIDFlagAbsent validator address present",
  775. CommitSig{BlockIDFlag: BlockIDFlagAbsent, ValidatorAddress: crypto.Address("testaddr")},
  776. true, "validator address is present",
  777. },
  778. {
  779. "BlockIDFlagAbsent timestamp present",
  780. CommitSig{BlockIDFlag: BlockIDFlagAbsent, Timestamp: time.Now().UTC()},
  781. true, "time is present",
  782. },
  783. {
  784. "BlockIDFlagAbsent signatures present",
  785. CommitSig{BlockIDFlag: BlockIDFlagAbsent, Signature: []byte{0xAA}},
  786. true, "signature is present",
  787. },
  788. {
  789. "BlockIDFlagAbsent valid BlockIDFlagAbsent",
  790. CommitSig{BlockIDFlag: BlockIDFlagAbsent},
  791. false, "",
  792. },
  793. {
  794. "non-BlockIDFlagAbsent invalid validator address",
  795. CommitSig{BlockIDFlag: BlockIDFlagCommit, ValidatorAddress: make([]byte, 1)},
  796. true, "expected ValidatorAddress size",
  797. },
  798. {
  799. "non-BlockIDFlagAbsent invalid signature (zero)",
  800. CommitSig{
  801. BlockIDFlag: BlockIDFlagCommit,
  802. ValidatorAddress: make([]byte, crypto.AddressSize),
  803. Signature: make([]byte, 0),
  804. },
  805. true, "signature is missing",
  806. },
  807. {
  808. "non-BlockIDFlagAbsent invalid signature (too large)",
  809. CommitSig{
  810. BlockIDFlag: BlockIDFlagCommit,
  811. ValidatorAddress: make([]byte, crypto.AddressSize),
  812. Signature: make([]byte, MaxSignatureSize+1),
  813. },
  814. true, "signature is too big",
  815. },
  816. {
  817. "non-BlockIDFlagAbsent valid",
  818. CommitSig{
  819. BlockIDFlag: BlockIDFlagCommit,
  820. ValidatorAddress: make([]byte, crypto.AddressSize),
  821. Signature: make([]byte, MaxSignatureSize),
  822. },
  823. false, "",
  824. },
  825. }
  826. for _, tc := range testCases {
  827. tc := tc
  828. t.Run(tc.name, func(t *testing.T) {
  829. err := tc.cs.ValidateBasic()
  830. if tc.expectErr {
  831. require.Error(t, err)
  832. require.Contains(t, err.Error(), tc.errString)
  833. } else {
  834. require.NoError(t, err)
  835. }
  836. })
  837. }
  838. }
  839. func TestHeader_ValidateBasic(t *testing.T) {
  840. testCases := []struct {
  841. name string
  842. header Header
  843. expectErr bool
  844. errString string
  845. }{
  846. {
  847. "invalid version block",
  848. Header{Version: tmversion.Consensus{Block: version.BlockProtocol + 1}},
  849. true, "block protocol is incorrect",
  850. },
  851. {
  852. "invalid chain ID length",
  853. Header{
  854. Version: tmversion.Consensus{Block: version.BlockProtocol},
  855. ChainID: string(make([]byte, MaxChainIDLen+1)),
  856. },
  857. true, "chainID is too long",
  858. },
  859. {
  860. "invalid height (negative)",
  861. Header{
  862. Version: tmversion.Consensus{Block: version.BlockProtocol},
  863. ChainID: string(make([]byte, MaxChainIDLen)),
  864. Height: -1,
  865. },
  866. true, "negative Height",
  867. },
  868. {
  869. "invalid height (zero)",
  870. Header{
  871. Version: tmversion.Consensus{Block: version.BlockProtocol},
  872. ChainID: string(make([]byte, MaxChainIDLen)),
  873. Height: 0,
  874. },
  875. true, "zero Height",
  876. },
  877. {
  878. "invalid block ID hash",
  879. Header{
  880. Version: tmversion.Consensus{Block: version.BlockProtocol},
  881. ChainID: string(make([]byte, MaxChainIDLen)),
  882. Height: 1,
  883. LastBlockID: BlockID{
  884. Hash: make([]byte, tmhash.Size+1),
  885. },
  886. },
  887. true, "wrong Hash",
  888. },
  889. {
  890. "invalid block ID parts header hash",
  891. Header{
  892. Version: tmversion.Consensus{Block: version.BlockProtocol},
  893. ChainID: string(make([]byte, MaxChainIDLen)),
  894. Height: 1,
  895. LastBlockID: BlockID{
  896. Hash: make([]byte, tmhash.Size),
  897. PartSetHeader: PartSetHeader{
  898. Hash: make([]byte, tmhash.Size+1),
  899. },
  900. },
  901. },
  902. true, "wrong PartSetHeader",
  903. },
  904. {
  905. "invalid last commit hash",
  906. Header{
  907. Version: tmversion.Consensus{Block: version.BlockProtocol},
  908. ChainID: string(make([]byte, MaxChainIDLen)),
  909. Height: 1,
  910. LastBlockID: BlockID{
  911. Hash: make([]byte, tmhash.Size),
  912. PartSetHeader: PartSetHeader{
  913. Hash: make([]byte, tmhash.Size),
  914. },
  915. },
  916. LastCommitHash: make([]byte, tmhash.Size+1),
  917. },
  918. true, "wrong LastCommitHash",
  919. },
  920. {
  921. "invalid data hash",
  922. Header{
  923. Version: tmversion.Consensus{Block: version.BlockProtocol},
  924. ChainID: string(make([]byte, MaxChainIDLen)),
  925. Height: 1,
  926. LastBlockID: BlockID{
  927. Hash: make([]byte, tmhash.Size),
  928. PartSetHeader: PartSetHeader{
  929. Hash: make([]byte, tmhash.Size),
  930. },
  931. },
  932. LastCommitHash: make([]byte, tmhash.Size),
  933. DataHash: make([]byte, tmhash.Size+1),
  934. },
  935. true, "wrong DataHash",
  936. },
  937. {
  938. "invalid evidence hash",
  939. Header{
  940. Version: tmversion.Consensus{Block: version.BlockProtocol},
  941. ChainID: string(make([]byte, MaxChainIDLen)),
  942. Height: 1,
  943. LastBlockID: BlockID{
  944. Hash: make([]byte, tmhash.Size),
  945. PartSetHeader: PartSetHeader{
  946. Hash: make([]byte, tmhash.Size),
  947. },
  948. },
  949. LastCommitHash: make([]byte, tmhash.Size),
  950. DataHash: make([]byte, tmhash.Size),
  951. EvidenceHash: make([]byte, tmhash.Size+1),
  952. },
  953. true, "wrong EvidenceHash",
  954. },
  955. {
  956. "invalid proposer address",
  957. Header{
  958. Version: tmversion.Consensus{Block: version.BlockProtocol},
  959. ChainID: string(make([]byte, MaxChainIDLen)),
  960. Height: 1,
  961. LastBlockID: BlockID{
  962. Hash: make([]byte, tmhash.Size),
  963. PartSetHeader: PartSetHeader{
  964. Hash: make([]byte, tmhash.Size),
  965. },
  966. },
  967. LastCommitHash: make([]byte, tmhash.Size),
  968. DataHash: make([]byte, tmhash.Size),
  969. EvidenceHash: make([]byte, tmhash.Size),
  970. ProposerAddress: make([]byte, crypto.AddressSize+1),
  971. },
  972. true, "invalid ProposerAddress length",
  973. },
  974. {
  975. "invalid validator hash",
  976. Header{
  977. Version: tmversion.Consensus{Block: version.BlockProtocol},
  978. ChainID: string(make([]byte, MaxChainIDLen)),
  979. Height: 1,
  980. LastBlockID: BlockID{
  981. Hash: make([]byte, tmhash.Size),
  982. PartSetHeader: PartSetHeader{
  983. Hash: make([]byte, tmhash.Size),
  984. },
  985. },
  986. LastCommitHash: make([]byte, tmhash.Size),
  987. DataHash: make([]byte, tmhash.Size),
  988. EvidenceHash: make([]byte, tmhash.Size),
  989. ProposerAddress: make([]byte, crypto.AddressSize),
  990. ValidatorsHash: make([]byte, tmhash.Size+1),
  991. },
  992. true, "wrong ValidatorsHash",
  993. },
  994. {
  995. "invalid next validator hash",
  996. Header{
  997. Version: tmversion.Consensus{Block: version.BlockProtocol},
  998. ChainID: string(make([]byte, MaxChainIDLen)),
  999. Height: 1,
  1000. LastBlockID: BlockID{
  1001. Hash: make([]byte, tmhash.Size),
  1002. PartSetHeader: PartSetHeader{
  1003. Hash: make([]byte, tmhash.Size),
  1004. },
  1005. },
  1006. LastCommitHash: make([]byte, tmhash.Size),
  1007. DataHash: make([]byte, tmhash.Size),
  1008. EvidenceHash: make([]byte, tmhash.Size),
  1009. ProposerAddress: make([]byte, crypto.AddressSize),
  1010. ValidatorsHash: make([]byte, tmhash.Size),
  1011. NextValidatorsHash: make([]byte, tmhash.Size+1),
  1012. },
  1013. true, "wrong NextValidatorsHash",
  1014. },
  1015. {
  1016. "invalid consensus hash",
  1017. Header{
  1018. Version: tmversion.Consensus{Block: version.BlockProtocol},
  1019. ChainID: string(make([]byte, MaxChainIDLen)),
  1020. Height: 1,
  1021. LastBlockID: BlockID{
  1022. Hash: make([]byte, tmhash.Size),
  1023. PartSetHeader: PartSetHeader{
  1024. Hash: make([]byte, tmhash.Size),
  1025. },
  1026. },
  1027. LastCommitHash: make([]byte, tmhash.Size),
  1028. DataHash: make([]byte, tmhash.Size),
  1029. EvidenceHash: make([]byte, tmhash.Size),
  1030. ProposerAddress: make([]byte, crypto.AddressSize),
  1031. ValidatorsHash: make([]byte, tmhash.Size),
  1032. NextValidatorsHash: make([]byte, tmhash.Size),
  1033. ConsensusHash: make([]byte, tmhash.Size+1),
  1034. },
  1035. true, "wrong ConsensusHash",
  1036. },
  1037. {
  1038. "invalid last results hash",
  1039. Header{
  1040. Version: tmversion.Consensus{Block: version.BlockProtocol},
  1041. ChainID: string(make([]byte, MaxChainIDLen)),
  1042. Height: 1,
  1043. LastBlockID: BlockID{
  1044. Hash: make([]byte, tmhash.Size),
  1045. PartSetHeader: PartSetHeader{
  1046. Hash: make([]byte, tmhash.Size),
  1047. },
  1048. },
  1049. LastCommitHash: make([]byte, tmhash.Size),
  1050. DataHash: make([]byte, tmhash.Size),
  1051. EvidenceHash: make([]byte, tmhash.Size),
  1052. ProposerAddress: make([]byte, crypto.AddressSize),
  1053. ValidatorsHash: make([]byte, tmhash.Size),
  1054. NextValidatorsHash: make([]byte, tmhash.Size),
  1055. ConsensusHash: make([]byte, tmhash.Size),
  1056. LastResultsHash: make([]byte, tmhash.Size+1),
  1057. },
  1058. true, "wrong LastResultsHash",
  1059. },
  1060. {
  1061. "valid header",
  1062. Header{
  1063. Version: tmversion.Consensus{Block: version.BlockProtocol},
  1064. ChainID: string(make([]byte, MaxChainIDLen)),
  1065. Height: 1,
  1066. LastBlockID: BlockID{
  1067. Hash: make([]byte, tmhash.Size),
  1068. PartSetHeader: PartSetHeader{
  1069. Hash: make([]byte, tmhash.Size),
  1070. },
  1071. },
  1072. LastCommitHash: make([]byte, tmhash.Size),
  1073. DataHash: make([]byte, tmhash.Size),
  1074. EvidenceHash: make([]byte, tmhash.Size),
  1075. ProposerAddress: make([]byte, crypto.AddressSize),
  1076. ValidatorsHash: make([]byte, tmhash.Size),
  1077. NextValidatorsHash: make([]byte, tmhash.Size),
  1078. ConsensusHash: make([]byte, tmhash.Size),
  1079. LastResultsHash: make([]byte, tmhash.Size),
  1080. },
  1081. false, "",
  1082. },
  1083. }
  1084. for _, tc := range testCases {
  1085. tc := tc
  1086. t.Run(tc.name, func(t *testing.T) {
  1087. err := tc.header.ValidateBasic()
  1088. if tc.expectErr {
  1089. require.Error(t, err)
  1090. require.Contains(t, err.Error(), tc.errString)
  1091. } else {
  1092. require.NoError(t, err)
  1093. }
  1094. })
  1095. }
  1096. }
  1097. func TestCommit_ValidateBasic(t *testing.T) {
  1098. testCases := []struct {
  1099. name string
  1100. commit *Commit
  1101. expectErr bool
  1102. errString string
  1103. }{
  1104. {
  1105. "invalid height",
  1106. &Commit{Height: -1},
  1107. true, "negative Height",
  1108. },
  1109. {
  1110. "invalid round",
  1111. &Commit{Height: 1, Round: -1},
  1112. true, "negative Round",
  1113. },
  1114. {
  1115. "invalid block ID",
  1116. &Commit{
  1117. Height: 1,
  1118. Round: 1,
  1119. BlockID: BlockID{},
  1120. },
  1121. true, "commit cannot be for nil block",
  1122. },
  1123. {
  1124. "no signatures",
  1125. &Commit{
  1126. Height: 1,
  1127. Round: 1,
  1128. BlockID: BlockID{
  1129. Hash: make([]byte, tmhash.Size),
  1130. PartSetHeader: PartSetHeader{
  1131. Hash: make([]byte, tmhash.Size),
  1132. },
  1133. },
  1134. },
  1135. true, "no signatures in commit",
  1136. },
  1137. {
  1138. "invalid signature",
  1139. &Commit{
  1140. Height: 1,
  1141. Round: 1,
  1142. BlockID: BlockID{
  1143. Hash: make([]byte, tmhash.Size),
  1144. PartSetHeader: PartSetHeader{
  1145. Hash: make([]byte, tmhash.Size),
  1146. },
  1147. },
  1148. Signatures: []CommitSig{
  1149. {
  1150. BlockIDFlag: BlockIDFlagCommit,
  1151. ValidatorAddress: make([]byte, crypto.AddressSize),
  1152. Signature: make([]byte, MaxSignatureSize+1),
  1153. },
  1154. },
  1155. },
  1156. true, "wrong CommitSig",
  1157. },
  1158. {
  1159. "valid commit",
  1160. &Commit{
  1161. Height: 1,
  1162. Round: 1,
  1163. BlockID: BlockID{
  1164. Hash: make([]byte, tmhash.Size),
  1165. PartSetHeader: PartSetHeader{
  1166. Hash: make([]byte, tmhash.Size),
  1167. },
  1168. },
  1169. Signatures: []CommitSig{
  1170. {
  1171. BlockIDFlag: BlockIDFlagCommit,
  1172. ValidatorAddress: make([]byte, crypto.AddressSize),
  1173. Signature: make([]byte, MaxSignatureSize),
  1174. },
  1175. },
  1176. },
  1177. false, "",
  1178. },
  1179. }
  1180. for _, tc := range testCases {
  1181. tc := tc
  1182. t.Run(tc.name, func(t *testing.T) {
  1183. err := tc.commit.ValidateBasic()
  1184. if tc.expectErr {
  1185. require.Error(t, err)
  1186. require.Contains(t, err.Error(), tc.errString)
  1187. } else {
  1188. require.NoError(t, err)
  1189. }
  1190. })
  1191. }
  1192. }