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.

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