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.

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