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.

1312 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: version.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: version.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 version.Consensus:
  327. pbc := tmversion.Consensus{
  328. Block: f.Block,
  329. App: f.App,
  330. }
  331. bz, err := pbc.Marshal()
  332. require.NoError(t, err)
  333. byteSlices = append(byteSlices, bz)
  334. case BlockID:
  335. pbbi := f.ToProto()
  336. bz, err := pbbi.Marshal()
  337. require.NoError(t, err)
  338. byteSlices = append(byteSlices, bz)
  339. default:
  340. t.Errorf("unknown type %T", f)
  341. }
  342. }
  343. assert.Equal(t,
  344. bytes.HexBytes(merkle.HashFromByteSlices(byteSlices)), tc.header.Hash())
  345. }
  346. })
  347. }
  348. }
  349. func TestMaxHeaderBytes(t *testing.T) {
  350. // Construct a UTF-8 string of MaxChainIDLen length using the supplementary
  351. // characters.
  352. // Each supplementary character takes 4 bytes.
  353. // http://www.i18nguy.com/unicode/supplementary-test.html
  354. maxChainID := ""
  355. for i := 0; i < MaxChainIDLen; i++ {
  356. maxChainID += "𠜎"
  357. }
  358. // time is varint encoded so need to pick the max.
  359. // year int, month Month, day, hour, min, sec, nsec int, loc *Location
  360. timestamp := time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC)
  361. h := Header{
  362. Version: version.Consensus{Block: math.MaxInt64, App: math.MaxInt64},
  363. ChainID: maxChainID,
  364. Height: math.MaxInt64,
  365. Time: timestamp,
  366. LastBlockID: makeBlockID(make([]byte, tmhash.Size), math.MaxInt32, make([]byte, tmhash.Size)),
  367. LastCommitHash: tmhash.Sum([]byte("last_commit_hash")),
  368. DataHash: tmhash.Sum([]byte("data_hash")),
  369. ValidatorsHash: tmhash.Sum([]byte("validators_hash")),
  370. NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")),
  371. ConsensusHash: tmhash.Sum([]byte("consensus_hash")),
  372. AppHash: tmhash.Sum([]byte("app_hash")),
  373. LastResultsHash: tmhash.Sum([]byte("last_results_hash")),
  374. EvidenceHash: tmhash.Sum([]byte("evidence_hash")),
  375. ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
  376. }
  377. bz, err := h.ToProto().Marshal()
  378. require.NoError(t, err)
  379. assert.EqualValues(t, MaxHeaderBytes, int64(len(bz)))
  380. }
  381. func randCommit(now time.Time) *Commit {
  382. lastID := makeBlockIDRandom()
  383. h := int64(3)
  384. voteSet, _, vals := randVoteSet(h-1, 1, tmproto.PrecommitType, 10, 1)
  385. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, now)
  386. if err != nil {
  387. panic(err)
  388. }
  389. return commit
  390. }
  391. func hexBytesFromString(s string) bytes.HexBytes {
  392. b, err := hex.DecodeString(s)
  393. if err != nil {
  394. panic(err)
  395. }
  396. return bytes.HexBytes(b)
  397. }
  398. func TestBlockMaxDataBytes(t *testing.T) {
  399. testCases := []struct {
  400. maxBytes int64
  401. valsCount int
  402. evidenceBytes int64
  403. panics bool
  404. result int64
  405. }{
  406. 0: {-10, 1, 0, true, 0},
  407. 1: {10, 1, 0, true, 0},
  408. 2: {841, 1, 0, true, 0},
  409. 3: {842, 1, 0, false, 0},
  410. 4: {843, 1, 0, false, 1},
  411. 5: {954, 2, 0, false, 1},
  412. 6: {1053, 2, 100, false, 0},
  413. }
  414. for i, tc := range testCases {
  415. tc := tc
  416. if tc.panics {
  417. assert.Panics(t, func() {
  418. MaxDataBytes(tc.maxBytes, tc.evidenceBytes, tc.valsCount)
  419. }, "#%v", i)
  420. } else {
  421. assert.Equal(t,
  422. tc.result,
  423. MaxDataBytes(tc.maxBytes, tc.evidenceBytes, tc.valsCount),
  424. "#%v", i)
  425. }
  426. }
  427. }
  428. func TestBlockMaxDataBytesNoEvidence(t *testing.T) {
  429. testCases := []struct {
  430. maxBytes int64
  431. valsCount int
  432. panics bool
  433. result int64
  434. }{
  435. 0: {-10, 1, true, 0},
  436. 1: {10, 1, true, 0},
  437. 2: {841, 1, true, 0},
  438. 3: {842, 1, false, 0},
  439. 4: {843, 1, false, 1},
  440. }
  441. for i, tc := range testCases {
  442. tc := tc
  443. if tc.panics {
  444. assert.Panics(t, func() {
  445. MaxDataBytesNoEvidence(tc.maxBytes, tc.valsCount)
  446. }, "#%v", i)
  447. } else {
  448. assert.Equal(t,
  449. tc.result,
  450. MaxDataBytesNoEvidence(tc.maxBytes, tc.valsCount),
  451. "#%v", i)
  452. }
  453. }
  454. }
  455. func TestCommitToVoteSet(t *testing.T) {
  456. lastID := makeBlockIDRandom()
  457. h := int64(3)
  458. voteSet, valSet, vals := randVoteSet(h-1, 1, tmproto.PrecommitType, 10, 1)
  459. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, time.Now())
  460. assert.NoError(t, err)
  461. chainID := voteSet.ChainID()
  462. voteSet2 := CommitToVoteSet(chainID, commit, valSet)
  463. for i := int32(0); int(i) < len(vals); i++ {
  464. vote1 := voteSet.GetByIndex(i)
  465. vote2 := voteSet2.GetByIndex(i)
  466. vote3 := commit.GetVote(i)
  467. vote1bz, err := vote1.ToProto().Marshal()
  468. require.NoError(t, err)
  469. vote2bz, err := vote2.ToProto().Marshal()
  470. require.NoError(t, err)
  471. vote3bz, err := vote3.ToProto().Marshal()
  472. require.NoError(t, err)
  473. assert.Equal(t, vote1bz, vote2bz)
  474. assert.Equal(t, vote1bz, vote3bz)
  475. }
  476. }
  477. func TestCommitToVoteSetWithVotesForNilBlock(t *testing.T) {
  478. blockID := makeBlockID([]byte("blockhash"), 1000, []byte("partshash"))
  479. const (
  480. height = int64(3)
  481. round = 0
  482. )
  483. type commitVoteTest struct {
  484. blockIDs []BlockID
  485. numVotes []int // must sum to numValidators
  486. numValidators int
  487. valid bool
  488. }
  489. testCases := []commitVoteTest{
  490. {[]BlockID{blockID, {}}, []int{67, 33}, 100, true},
  491. }
  492. for _, tc := range testCases {
  493. voteSet, valSet, vals := randVoteSet(height-1, round, tmproto.PrecommitType, tc.numValidators, 1)
  494. vi := int32(0)
  495. for n := range tc.blockIDs {
  496. for i := 0; i < tc.numVotes[n]; i++ {
  497. pubKey, err := vals[vi].GetPubKey()
  498. require.NoError(t, err)
  499. vote := &Vote{
  500. ValidatorAddress: pubKey.Address(),
  501. ValidatorIndex: vi,
  502. Height: height - 1,
  503. Round: round,
  504. Type: tmproto.PrecommitType,
  505. BlockID: tc.blockIDs[n],
  506. Timestamp: tmtime.Now(),
  507. }
  508. added, err := signAddVote(vals[vi], vote, voteSet)
  509. assert.NoError(t, err)
  510. assert.True(t, added)
  511. vi++
  512. }
  513. }
  514. if tc.valid {
  515. commit := voteSet.MakeCommit() // panics without > 2/3 valid votes
  516. assert.NotNil(t, commit)
  517. err := valSet.VerifyCommit(voteSet.ChainID(), blockID, height-1, commit)
  518. assert.Nil(t, err)
  519. } else {
  520. assert.Panics(t, func() { voteSet.MakeCommit() })
  521. }
  522. }
  523. }
  524. func TestBlockIDValidateBasic(t *testing.T) {
  525. validBlockID := BlockID{
  526. Hash: bytes.HexBytes{},
  527. PartSetHeader: PartSetHeader{
  528. Total: 1,
  529. Hash: bytes.HexBytes{},
  530. },
  531. }
  532. invalidBlockID := BlockID{
  533. Hash: []byte{0},
  534. PartSetHeader: PartSetHeader{
  535. Total: 1,
  536. Hash: []byte{0},
  537. },
  538. }
  539. testCases := []struct {
  540. testName string
  541. blockIDHash bytes.HexBytes
  542. blockIDPartSetHeader PartSetHeader
  543. expectErr bool
  544. }{
  545. {"Valid BlockID", validBlockID.Hash, validBlockID.PartSetHeader, false},
  546. {"Invalid BlockID", invalidBlockID.Hash, validBlockID.PartSetHeader, true},
  547. {"Invalid BlockID", validBlockID.Hash, invalidBlockID.PartSetHeader, true},
  548. }
  549. for _, tc := range testCases {
  550. tc := tc
  551. t.Run(tc.testName, func(t *testing.T) {
  552. blockID := BlockID{
  553. Hash: tc.blockIDHash,
  554. PartSetHeader: tc.blockIDPartSetHeader,
  555. }
  556. assert.Equal(t, tc.expectErr, blockID.ValidateBasic() != nil, "Validate Basic had an unexpected result")
  557. })
  558. }
  559. }
  560. func TestBlockProtoBuf(t *testing.T) {
  561. h := tmrand.Int63()
  562. c1 := randCommit(time.Now())
  563. b1 := MakeBlock(h, []Tx{Tx([]byte{1})}, &Commit{Signatures: []CommitSig{}}, []Evidence{})
  564. b1.ProposerAddress = tmrand.Bytes(crypto.AddressSize)
  565. b2 := MakeBlock(h, []Tx{Tx([]byte{1})}, c1, []Evidence{})
  566. b2.ProposerAddress = tmrand.Bytes(crypto.AddressSize)
  567. evidenceTime := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
  568. evi := NewMockDuplicateVoteEvidence(h, evidenceTime, "block-test-chain")
  569. b2.Evidence = EvidenceData{Evidence: EvidenceList{evi}}
  570. b2.EvidenceHash = b2.Evidence.Hash()
  571. b3 := MakeBlock(h, []Tx{}, c1, []Evidence{})
  572. b3.ProposerAddress = tmrand.Bytes(crypto.AddressSize)
  573. testCases := []struct {
  574. msg string
  575. b1 *Block
  576. expPass bool
  577. expPass2 bool
  578. }{
  579. {"nil block", nil, false, false},
  580. {"b1", b1, true, true},
  581. {"b2", b2, true, true},
  582. {"b3", b3, true, true},
  583. }
  584. for _, tc := range testCases {
  585. pb, err := tc.b1.ToProto()
  586. if tc.expPass {
  587. require.NoError(t, err, tc.msg)
  588. } else {
  589. require.Error(t, err, tc.msg)
  590. }
  591. block, err := BlockFromProto(pb)
  592. if tc.expPass2 {
  593. require.NoError(t, err, tc.msg)
  594. require.EqualValues(t, tc.b1.Header, block.Header, tc.msg)
  595. require.EqualValues(t, tc.b1.Data, block.Data, tc.msg)
  596. require.EqualValues(t, tc.b1.Evidence.Evidence, block.Evidence.Evidence, tc.msg)
  597. require.EqualValues(t, *tc.b1.LastCommit, *block.LastCommit, tc.msg)
  598. } else {
  599. require.Error(t, err, tc.msg)
  600. }
  601. }
  602. }
  603. func TestDataProtoBuf(t *testing.T) {
  604. data := &Data{Txs: Txs{Tx([]byte{1}), Tx([]byte{2}), Tx([]byte{3})}}
  605. data2 := &Data{Txs: Txs{}}
  606. testCases := []struct {
  607. msg string
  608. data1 *Data
  609. expPass bool
  610. }{
  611. {"success", data, true},
  612. {"success data2", data2, true},
  613. }
  614. for _, tc := range testCases {
  615. protoData := tc.data1.ToProto()
  616. d, err := DataFromProto(&protoData)
  617. if tc.expPass {
  618. require.NoError(t, err, tc.msg)
  619. require.EqualValues(t, tc.data1, &d, tc.msg)
  620. } else {
  621. require.Error(t, err, tc.msg)
  622. }
  623. }
  624. }
  625. // TestEvidenceDataProtoBuf ensures parity in converting to and from proto.
  626. func TestEvidenceDataProtoBuf(t *testing.T) {
  627. const chainID = "mychain"
  628. ev := NewMockDuplicateVoteEvidence(math.MaxInt64, time.Now(), chainID)
  629. data := &EvidenceData{Evidence: EvidenceList{ev}}
  630. _ = data.ByteSize()
  631. testCases := []struct {
  632. msg string
  633. data1 *EvidenceData
  634. expPass1 bool
  635. expPass2 bool
  636. }{
  637. {"success", data, true, true},
  638. {"empty evidenceData", &EvidenceData{Evidence: EvidenceList{}}, true, true},
  639. {"fail nil Data", nil, false, false},
  640. }
  641. for _, tc := range testCases {
  642. protoData, err := tc.data1.ToProto()
  643. if tc.expPass1 {
  644. require.NoError(t, err, tc.msg)
  645. } else {
  646. require.Error(t, err, tc.msg)
  647. }
  648. eviD := new(EvidenceData)
  649. err = eviD.FromProto(protoData)
  650. if tc.expPass2 {
  651. require.NoError(t, err, tc.msg)
  652. require.Equal(t, tc.data1, eviD, tc.msg)
  653. } else {
  654. require.Error(t, err, tc.msg)
  655. }
  656. }
  657. }
  658. func makeRandHeader() Header {
  659. chainID := "test"
  660. t := time.Now()
  661. height := tmrand.Int63()
  662. randBytes := tmrand.Bytes(tmhash.Size)
  663. randAddress := tmrand.Bytes(crypto.AddressSize)
  664. h := Header{
  665. Version: version.Consensus{Block: version.BlockProtocol, App: 1},
  666. ChainID: chainID,
  667. Height: height,
  668. Time: t,
  669. LastBlockID: BlockID{},
  670. LastCommitHash: randBytes,
  671. DataHash: randBytes,
  672. ValidatorsHash: randBytes,
  673. NextValidatorsHash: randBytes,
  674. ConsensusHash: randBytes,
  675. AppHash: randBytes,
  676. LastResultsHash: randBytes,
  677. EvidenceHash: randBytes,
  678. ProposerAddress: randAddress,
  679. }
  680. return h
  681. }
  682. func TestHeaderProto(t *testing.T) {
  683. h1 := makeRandHeader()
  684. tc := []struct {
  685. msg string
  686. h1 *Header
  687. expPass bool
  688. }{
  689. {"success", &h1, true},
  690. {"failure empty Header", &Header{}, false},
  691. }
  692. for _, tt := range tc {
  693. tt := tt
  694. t.Run(tt.msg, func(t *testing.T) {
  695. pb := tt.h1.ToProto()
  696. h, err := HeaderFromProto(pb)
  697. if tt.expPass {
  698. require.NoError(t, err, tt.msg)
  699. require.Equal(t, tt.h1, &h, tt.msg)
  700. } else {
  701. require.Error(t, err, tt.msg)
  702. }
  703. })
  704. }
  705. }
  706. func TestBlockIDProtoBuf(t *testing.T) {
  707. blockID := makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))
  708. testCases := []struct {
  709. msg string
  710. bid1 *BlockID
  711. expPass bool
  712. }{
  713. {"success", &blockID, true},
  714. {"success empty", &BlockID{}, true},
  715. {"failure BlockID nil", nil, false},
  716. }
  717. for _, tc := range testCases {
  718. protoBlockID := tc.bid1.ToProto()
  719. bi, err := BlockIDFromProto(&protoBlockID)
  720. if tc.expPass {
  721. require.NoError(t, err)
  722. require.Equal(t, tc.bid1, bi, tc.msg)
  723. } else {
  724. require.NotEqual(t, tc.bid1, bi, tc.msg)
  725. }
  726. }
  727. }
  728. func TestSignedHeaderProtoBuf(t *testing.T) {
  729. commit := randCommit(time.Now())
  730. h := makeRandHeader()
  731. sh := SignedHeader{Header: &h, Commit: commit}
  732. testCases := []struct {
  733. msg string
  734. sh1 *SignedHeader
  735. expPass bool
  736. }{
  737. {"empty SignedHeader 2", &SignedHeader{}, true},
  738. {"success", &sh, true},
  739. {"failure nil", nil, false},
  740. }
  741. for _, tc := range testCases {
  742. protoSignedHeader := tc.sh1.ToProto()
  743. sh, err := SignedHeaderFromProto(protoSignedHeader)
  744. if tc.expPass {
  745. require.NoError(t, err, tc.msg)
  746. require.Equal(t, tc.sh1, sh, tc.msg)
  747. } else {
  748. require.Error(t, err, tc.msg)
  749. }
  750. }
  751. }
  752. func TestBlockIDEquals(t *testing.T) {
  753. var (
  754. blockID = makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))
  755. blockIDDuplicate = makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))
  756. blockIDDifferent = makeBlockID([]byte("different_hash"), 2, []byte("part_set_hash"))
  757. blockIDEmpty = BlockID{}
  758. )
  759. assert.True(t, blockID.Equals(blockIDDuplicate))
  760. assert.False(t, blockID.Equals(blockIDDifferent))
  761. assert.False(t, blockID.Equals(blockIDEmpty))
  762. assert.True(t, blockIDEmpty.Equals(blockIDEmpty))
  763. assert.False(t, blockIDEmpty.Equals(blockIDDifferent))
  764. }
  765. func TestCommitSig_ValidateBasic(t *testing.T) {
  766. testCases := []struct {
  767. name string
  768. cs CommitSig
  769. expectErr bool
  770. errString string
  771. }{
  772. {
  773. "invalid ID flag",
  774. CommitSig{BlockIDFlag: BlockIDFlag(0xFF)},
  775. true, "unknown BlockIDFlag",
  776. },
  777. {
  778. "BlockIDFlagAbsent validator address present",
  779. CommitSig{BlockIDFlag: BlockIDFlagAbsent, ValidatorAddress: crypto.Address("testaddr")},
  780. true, "validator address is present",
  781. },
  782. {
  783. "BlockIDFlagAbsent timestamp present",
  784. CommitSig{BlockIDFlag: BlockIDFlagAbsent, Timestamp: time.Now().UTC()},
  785. true, "time is present",
  786. },
  787. {
  788. "BlockIDFlagAbsent signatures present",
  789. CommitSig{BlockIDFlag: BlockIDFlagAbsent, Signature: []byte{0xAA}},
  790. true, "signature is present",
  791. },
  792. {
  793. "BlockIDFlagAbsent valid BlockIDFlagAbsent",
  794. CommitSig{BlockIDFlag: BlockIDFlagAbsent},
  795. false, "",
  796. },
  797. {
  798. "non-BlockIDFlagAbsent invalid validator address",
  799. CommitSig{BlockIDFlag: BlockIDFlagCommit, ValidatorAddress: make([]byte, 1)},
  800. true, "expected ValidatorAddress size",
  801. },
  802. {
  803. "non-BlockIDFlagAbsent invalid signature (zero)",
  804. CommitSig{
  805. BlockIDFlag: BlockIDFlagCommit,
  806. ValidatorAddress: make([]byte, crypto.AddressSize),
  807. Signature: make([]byte, 0),
  808. },
  809. true, "signature is missing",
  810. },
  811. {
  812. "non-BlockIDFlagAbsent invalid signature (too large)",
  813. CommitSig{
  814. BlockIDFlag: BlockIDFlagCommit,
  815. ValidatorAddress: make([]byte, crypto.AddressSize),
  816. Signature: make([]byte, MaxSignatureSize+1),
  817. },
  818. true, "signature is too big",
  819. },
  820. {
  821. "non-BlockIDFlagAbsent valid",
  822. CommitSig{
  823. BlockIDFlag: BlockIDFlagCommit,
  824. ValidatorAddress: make([]byte, crypto.AddressSize),
  825. Signature: make([]byte, MaxSignatureSize),
  826. },
  827. false, "",
  828. },
  829. }
  830. for _, tc := range testCases {
  831. tc := tc
  832. t.Run(tc.name, func(t *testing.T) {
  833. err := tc.cs.ValidateBasic()
  834. if tc.expectErr {
  835. require.Error(t, err)
  836. require.Contains(t, err.Error(), tc.errString)
  837. } else {
  838. require.NoError(t, err)
  839. }
  840. })
  841. }
  842. }
  843. func TestHeader_ValidateBasic(t *testing.T) {
  844. testCases := []struct {
  845. name string
  846. header Header
  847. expectErr bool
  848. errString string
  849. }{
  850. {
  851. "invalid version block",
  852. Header{Version: version.Consensus{Block: version.BlockProtocol + 1}},
  853. true, "block protocol is incorrect",
  854. },
  855. {
  856. "invalid chain ID length",
  857. Header{
  858. Version: version.Consensus{Block: version.BlockProtocol},
  859. ChainID: string(make([]byte, MaxChainIDLen+1)),
  860. },
  861. true, "chainID is too long",
  862. },
  863. {
  864. "invalid height (negative)",
  865. Header{
  866. Version: version.Consensus{Block: version.BlockProtocol},
  867. ChainID: string(make([]byte, MaxChainIDLen)),
  868. Height: -1,
  869. },
  870. true, "negative Height",
  871. },
  872. {
  873. "invalid height (zero)",
  874. Header{
  875. Version: version.Consensus{Block: version.BlockProtocol},
  876. ChainID: string(make([]byte, MaxChainIDLen)),
  877. Height: 0,
  878. },
  879. true, "zero Height",
  880. },
  881. {
  882. "invalid block ID hash",
  883. Header{
  884. Version: version.Consensus{Block: version.BlockProtocol},
  885. ChainID: string(make([]byte, MaxChainIDLen)),
  886. Height: 1,
  887. LastBlockID: BlockID{
  888. Hash: make([]byte, tmhash.Size+1),
  889. },
  890. },
  891. true, "wrong Hash",
  892. },
  893. {
  894. "invalid block ID parts header hash",
  895. Header{
  896. Version: version.Consensus{Block: version.BlockProtocol},
  897. ChainID: string(make([]byte, MaxChainIDLen)),
  898. Height: 1,
  899. LastBlockID: BlockID{
  900. Hash: make([]byte, tmhash.Size),
  901. PartSetHeader: PartSetHeader{
  902. Hash: make([]byte, tmhash.Size+1),
  903. },
  904. },
  905. },
  906. true, "wrong PartSetHeader",
  907. },
  908. {
  909. "invalid last commit hash",
  910. Header{
  911. Version: version.Consensus{Block: version.BlockProtocol},
  912. ChainID: string(make([]byte, MaxChainIDLen)),
  913. Height: 1,
  914. LastBlockID: BlockID{
  915. Hash: make([]byte, tmhash.Size),
  916. PartSetHeader: PartSetHeader{
  917. Hash: make([]byte, tmhash.Size),
  918. },
  919. },
  920. LastCommitHash: make([]byte, tmhash.Size+1),
  921. },
  922. true, "wrong LastCommitHash",
  923. },
  924. {
  925. "invalid data hash",
  926. Header{
  927. Version: version.Consensus{Block: version.BlockProtocol},
  928. ChainID: string(make([]byte, MaxChainIDLen)),
  929. Height: 1,
  930. LastBlockID: BlockID{
  931. Hash: make([]byte, tmhash.Size),
  932. PartSetHeader: PartSetHeader{
  933. Hash: make([]byte, tmhash.Size),
  934. },
  935. },
  936. LastCommitHash: make([]byte, tmhash.Size),
  937. DataHash: make([]byte, tmhash.Size+1),
  938. },
  939. true, "wrong DataHash",
  940. },
  941. {
  942. "invalid evidence hash",
  943. Header{
  944. Version: version.Consensus{Block: version.BlockProtocol},
  945. ChainID: string(make([]byte, MaxChainIDLen)),
  946. Height: 1,
  947. LastBlockID: BlockID{
  948. Hash: make([]byte, tmhash.Size),
  949. PartSetHeader: PartSetHeader{
  950. Hash: make([]byte, tmhash.Size),
  951. },
  952. },
  953. LastCommitHash: make([]byte, tmhash.Size),
  954. DataHash: make([]byte, tmhash.Size),
  955. EvidenceHash: make([]byte, tmhash.Size+1),
  956. },
  957. true, "wrong EvidenceHash",
  958. },
  959. {
  960. "invalid proposer address",
  961. Header{
  962. Version: version.Consensus{Block: version.BlockProtocol},
  963. ChainID: string(make([]byte, MaxChainIDLen)),
  964. Height: 1,
  965. LastBlockID: BlockID{
  966. Hash: make([]byte, tmhash.Size),
  967. PartSetHeader: PartSetHeader{
  968. Hash: make([]byte, tmhash.Size),
  969. },
  970. },
  971. LastCommitHash: make([]byte, tmhash.Size),
  972. DataHash: make([]byte, tmhash.Size),
  973. EvidenceHash: make([]byte, tmhash.Size),
  974. ProposerAddress: make([]byte, crypto.AddressSize+1),
  975. },
  976. true, "invalid ProposerAddress length",
  977. },
  978. {
  979. "invalid validator hash",
  980. Header{
  981. Version: version.Consensus{Block: version.BlockProtocol},
  982. ChainID: string(make([]byte, MaxChainIDLen)),
  983. Height: 1,
  984. LastBlockID: BlockID{
  985. Hash: make([]byte, tmhash.Size),
  986. PartSetHeader: PartSetHeader{
  987. Hash: make([]byte, tmhash.Size),
  988. },
  989. },
  990. LastCommitHash: make([]byte, tmhash.Size),
  991. DataHash: make([]byte, tmhash.Size),
  992. EvidenceHash: make([]byte, tmhash.Size),
  993. ProposerAddress: make([]byte, crypto.AddressSize),
  994. ValidatorsHash: make([]byte, tmhash.Size+1),
  995. },
  996. true, "wrong ValidatorsHash",
  997. },
  998. {
  999. "invalid next validator hash",
  1000. Header{
  1001. Version: version.Consensus{Block: version.BlockProtocol},
  1002. ChainID: string(make([]byte, MaxChainIDLen)),
  1003. Height: 1,
  1004. LastBlockID: BlockID{
  1005. Hash: make([]byte, tmhash.Size),
  1006. PartSetHeader: PartSetHeader{
  1007. Hash: make([]byte, tmhash.Size),
  1008. },
  1009. },
  1010. LastCommitHash: make([]byte, tmhash.Size),
  1011. DataHash: make([]byte, tmhash.Size),
  1012. EvidenceHash: make([]byte, tmhash.Size),
  1013. ProposerAddress: make([]byte, crypto.AddressSize),
  1014. ValidatorsHash: make([]byte, tmhash.Size),
  1015. NextValidatorsHash: make([]byte, tmhash.Size+1),
  1016. },
  1017. true, "wrong NextValidatorsHash",
  1018. },
  1019. {
  1020. "invalid consensus hash",
  1021. Header{
  1022. Version: version.Consensus{Block: version.BlockProtocol},
  1023. ChainID: string(make([]byte, MaxChainIDLen)),
  1024. Height: 1,
  1025. LastBlockID: BlockID{
  1026. Hash: make([]byte, tmhash.Size),
  1027. PartSetHeader: PartSetHeader{
  1028. Hash: make([]byte, tmhash.Size),
  1029. },
  1030. },
  1031. LastCommitHash: make([]byte, tmhash.Size),
  1032. DataHash: make([]byte, tmhash.Size),
  1033. EvidenceHash: make([]byte, tmhash.Size),
  1034. ProposerAddress: make([]byte, crypto.AddressSize),
  1035. ValidatorsHash: make([]byte, tmhash.Size),
  1036. NextValidatorsHash: make([]byte, tmhash.Size),
  1037. ConsensusHash: make([]byte, tmhash.Size+1),
  1038. },
  1039. true, "wrong ConsensusHash",
  1040. },
  1041. {
  1042. "invalid last results hash",
  1043. Header{
  1044. Version: version.Consensus{Block: version.BlockProtocol},
  1045. ChainID: string(make([]byte, MaxChainIDLen)),
  1046. Height: 1,
  1047. LastBlockID: BlockID{
  1048. Hash: make([]byte, tmhash.Size),
  1049. PartSetHeader: PartSetHeader{
  1050. Hash: make([]byte, tmhash.Size),
  1051. },
  1052. },
  1053. LastCommitHash: make([]byte, tmhash.Size),
  1054. DataHash: make([]byte, tmhash.Size),
  1055. EvidenceHash: make([]byte, tmhash.Size),
  1056. ProposerAddress: make([]byte, crypto.AddressSize),
  1057. ValidatorsHash: make([]byte, tmhash.Size),
  1058. NextValidatorsHash: make([]byte, tmhash.Size),
  1059. ConsensusHash: make([]byte, tmhash.Size),
  1060. LastResultsHash: make([]byte, tmhash.Size+1),
  1061. },
  1062. true, "wrong LastResultsHash",
  1063. },
  1064. {
  1065. "valid header",
  1066. Header{
  1067. Version: version.Consensus{Block: version.BlockProtocol},
  1068. ChainID: string(make([]byte, MaxChainIDLen)),
  1069. Height: 1,
  1070. LastBlockID: BlockID{
  1071. Hash: make([]byte, tmhash.Size),
  1072. PartSetHeader: PartSetHeader{
  1073. Hash: make([]byte, tmhash.Size),
  1074. },
  1075. },
  1076. LastCommitHash: make([]byte, tmhash.Size),
  1077. DataHash: make([]byte, tmhash.Size),
  1078. EvidenceHash: make([]byte, tmhash.Size),
  1079. ProposerAddress: make([]byte, crypto.AddressSize),
  1080. ValidatorsHash: make([]byte, tmhash.Size),
  1081. NextValidatorsHash: make([]byte, tmhash.Size),
  1082. ConsensusHash: make([]byte, tmhash.Size),
  1083. LastResultsHash: make([]byte, tmhash.Size),
  1084. },
  1085. false, "",
  1086. },
  1087. }
  1088. for _, tc := range testCases {
  1089. tc := tc
  1090. t.Run(tc.name, func(t *testing.T) {
  1091. err := tc.header.ValidateBasic()
  1092. if tc.expectErr {
  1093. require.Error(t, err)
  1094. require.Contains(t, err.Error(), tc.errString)
  1095. } else {
  1096. require.NoError(t, err)
  1097. }
  1098. })
  1099. }
  1100. }
  1101. func TestCommit_ValidateBasic(t *testing.T) {
  1102. testCases := []struct {
  1103. name string
  1104. commit *Commit
  1105. expectErr bool
  1106. errString string
  1107. }{
  1108. {
  1109. "invalid height",
  1110. &Commit{Height: -1},
  1111. true, "negative Height",
  1112. },
  1113. {
  1114. "invalid round",
  1115. &Commit{Height: 1, Round: -1},
  1116. true, "negative Round",
  1117. },
  1118. {
  1119. "invalid block ID",
  1120. &Commit{
  1121. Height: 1,
  1122. Round: 1,
  1123. BlockID: BlockID{},
  1124. },
  1125. true, "commit cannot be for nil block",
  1126. },
  1127. {
  1128. "no signatures",
  1129. &Commit{
  1130. Height: 1,
  1131. Round: 1,
  1132. BlockID: BlockID{
  1133. Hash: make([]byte, tmhash.Size),
  1134. PartSetHeader: PartSetHeader{
  1135. Hash: make([]byte, tmhash.Size),
  1136. },
  1137. },
  1138. },
  1139. true, "no signatures in commit",
  1140. },
  1141. {
  1142. "invalid signature",
  1143. &Commit{
  1144. Height: 1,
  1145. Round: 1,
  1146. BlockID: BlockID{
  1147. Hash: make([]byte, tmhash.Size),
  1148. PartSetHeader: PartSetHeader{
  1149. Hash: make([]byte, tmhash.Size),
  1150. },
  1151. },
  1152. Signatures: []CommitSig{
  1153. {
  1154. BlockIDFlag: BlockIDFlagCommit,
  1155. ValidatorAddress: make([]byte, crypto.AddressSize),
  1156. Signature: make([]byte, MaxSignatureSize+1),
  1157. },
  1158. },
  1159. },
  1160. true, "wrong CommitSig",
  1161. },
  1162. {
  1163. "valid commit",
  1164. &Commit{
  1165. Height: 1,
  1166. Round: 1,
  1167. BlockID: BlockID{
  1168. Hash: make([]byte, tmhash.Size),
  1169. PartSetHeader: PartSetHeader{
  1170. Hash: make([]byte, tmhash.Size),
  1171. },
  1172. },
  1173. Signatures: []CommitSig{
  1174. {
  1175. BlockIDFlag: BlockIDFlagCommit,
  1176. ValidatorAddress: make([]byte, crypto.AddressSize),
  1177. Signature: make([]byte, MaxSignatureSize),
  1178. },
  1179. },
  1180. },
  1181. false, "",
  1182. },
  1183. }
  1184. for _, tc := range testCases {
  1185. tc := tc
  1186. t.Run(tc.name, func(t *testing.T) {
  1187. err := tc.commit.ValidateBasic()
  1188. if tc.expectErr {
  1189. require.Error(t, err)
  1190. require.Contains(t, err.Error(), tc.errString)
  1191. } else {
  1192. require.NoError(t, err)
  1193. }
  1194. })
  1195. }
  1196. }