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.

1349 lines
38 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. tmtime "github.com/tendermint/tendermint/libs/time"
  24. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  25. tmversion "github.com/tendermint/tendermint/proto/tendermint/version"
  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. // exposed for testing
  661. func MakeRandHeader() Header {
  662. chainID := "test"
  663. t := time.Now()
  664. height := mrand.Int63()
  665. randBytes := tmrand.Bytes(tmhash.Size)
  666. randAddress := tmrand.Bytes(crypto.AddressSize)
  667. h := Header{
  668. Version: version.Consensus{Block: version.BlockProtocol, App: 1},
  669. ChainID: chainID,
  670. Height: height,
  671. Time: t,
  672. LastBlockID: BlockID{},
  673. LastCommitHash: randBytes,
  674. DataHash: randBytes,
  675. ValidatorsHash: randBytes,
  676. NextValidatorsHash: randBytes,
  677. ConsensusHash: randBytes,
  678. AppHash: randBytes,
  679. LastResultsHash: randBytes,
  680. EvidenceHash: randBytes,
  681. ProposerAddress: randAddress,
  682. }
  683. return h
  684. }
  685. func TestHeaderProto(t *testing.T) {
  686. h1 := MakeRandHeader()
  687. tc := []struct {
  688. msg string
  689. h1 *Header
  690. expPass bool
  691. }{
  692. {"success", &h1, true},
  693. {"failure empty Header", &Header{}, false},
  694. }
  695. for _, tt := range tc {
  696. tt := tt
  697. t.Run(tt.msg, func(t *testing.T) {
  698. pb := tt.h1.ToProto()
  699. h, err := HeaderFromProto(pb)
  700. if tt.expPass {
  701. require.NoError(t, err, tt.msg)
  702. require.Equal(t, tt.h1, &h, tt.msg)
  703. } else {
  704. require.Error(t, err, tt.msg)
  705. }
  706. })
  707. }
  708. }
  709. func TestBlockIDProtoBuf(t *testing.T) {
  710. blockID := makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))
  711. testCases := []struct {
  712. msg string
  713. bid1 *BlockID
  714. expPass bool
  715. }{
  716. {"success", &blockID, true},
  717. {"success empty", &BlockID{}, true},
  718. {"failure BlockID nil", nil, false},
  719. }
  720. for _, tc := range testCases {
  721. protoBlockID := tc.bid1.ToProto()
  722. bi, err := BlockIDFromProto(&protoBlockID)
  723. if tc.expPass {
  724. require.NoError(t, err)
  725. require.Equal(t, tc.bid1, bi, tc.msg)
  726. } else {
  727. require.NotEqual(t, tc.bid1, bi, tc.msg)
  728. }
  729. }
  730. }
  731. func TestSignedHeaderProtoBuf(t *testing.T) {
  732. commit := randCommit(time.Now())
  733. h := MakeRandHeader()
  734. sh := SignedHeader{Header: &h, Commit: commit}
  735. testCases := []struct {
  736. msg string
  737. sh1 *SignedHeader
  738. expPass bool
  739. }{
  740. {"empty SignedHeader 2", &SignedHeader{}, true},
  741. {"success", &sh, true},
  742. {"failure nil", nil, false},
  743. }
  744. for _, tc := range testCases {
  745. protoSignedHeader := tc.sh1.ToProto()
  746. sh, err := SignedHeaderFromProto(protoSignedHeader)
  747. if tc.expPass {
  748. require.NoError(t, err, tc.msg)
  749. require.Equal(t, tc.sh1, sh, tc.msg)
  750. } else {
  751. require.Error(t, err, tc.msg)
  752. }
  753. }
  754. }
  755. func TestBlockIDEquals(t *testing.T) {
  756. var (
  757. blockID = makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))
  758. blockIDDuplicate = makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))
  759. blockIDDifferent = makeBlockID([]byte("different_hash"), 2, []byte("part_set_hash"))
  760. blockIDEmpty = BlockID{}
  761. )
  762. assert.True(t, blockID.Equals(blockIDDuplicate))
  763. assert.False(t, blockID.Equals(blockIDDifferent))
  764. assert.False(t, blockID.Equals(blockIDEmpty))
  765. assert.True(t, blockIDEmpty.Equals(blockIDEmpty))
  766. assert.False(t, blockIDEmpty.Equals(blockIDDifferent))
  767. }
  768. func TestCommitSig_ValidateBasic(t *testing.T) {
  769. testCases := []struct {
  770. name string
  771. cs CommitSig
  772. expectErr bool
  773. errString string
  774. }{
  775. {
  776. "invalid ID flag",
  777. CommitSig{BlockIDFlag: BlockIDFlag(0xFF)},
  778. true, "unknown BlockIDFlag",
  779. },
  780. {
  781. "BlockIDFlagAbsent validator address present",
  782. CommitSig{BlockIDFlag: BlockIDFlagAbsent, ValidatorAddress: crypto.Address("testaddr")},
  783. true, "validator address is present",
  784. },
  785. {
  786. "BlockIDFlagAbsent timestamp present",
  787. CommitSig{BlockIDFlag: BlockIDFlagAbsent, Timestamp: time.Now().UTC()},
  788. true, "time is present",
  789. },
  790. {
  791. "BlockIDFlagAbsent signatures present",
  792. CommitSig{BlockIDFlag: BlockIDFlagAbsent, Signature: []byte{0xAA}},
  793. true, "signature is present",
  794. },
  795. {
  796. "BlockIDFlagAbsent valid BlockIDFlagAbsent",
  797. CommitSig{BlockIDFlag: BlockIDFlagAbsent},
  798. false, "",
  799. },
  800. {
  801. "non-BlockIDFlagAbsent invalid validator address",
  802. CommitSig{BlockIDFlag: BlockIDFlagCommit, ValidatorAddress: make([]byte, 1)},
  803. true, "expected ValidatorAddress size",
  804. },
  805. {
  806. "non-BlockIDFlagAbsent invalid signature (zero)",
  807. CommitSig{
  808. BlockIDFlag: BlockIDFlagCommit,
  809. ValidatorAddress: make([]byte, crypto.AddressSize),
  810. Signature: make([]byte, 0),
  811. },
  812. true, "signature is missing",
  813. },
  814. {
  815. "non-BlockIDFlagAbsent invalid signature (too large)",
  816. CommitSig{
  817. BlockIDFlag: BlockIDFlagCommit,
  818. ValidatorAddress: make([]byte, crypto.AddressSize),
  819. Signature: make([]byte, MaxSignatureSize+1),
  820. },
  821. true, "signature is too big",
  822. },
  823. {
  824. "non-BlockIDFlagAbsent valid",
  825. CommitSig{
  826. BlockIDFlag: BlockIDFlagCommit,
  827. ValidatorAddress: make([]byte, crypto.AddressSize),
  828. Signature: make([]byte, MaxSignatureSize),
  829. },
  830. false, "",
  831. },
  832. }
  833. for _, tc := range testCases {
  834. tc := tc
  835. t.Run(tc.name, func(t *testing.T) {
  836. err := tc.cs.ValidateBasic()
  837. if tc.expectErr {
  838. require.Error(t, err)
  839. require.Contains(t, err.Error(), tc.errString)
  840. } else {
  841. require.NoError(t, err)
  842. }
  843. })
  844. }
  845. }
  846. func TestHeader_ValidateBasic(t *testing.T) {
  847. testCases := []struct {
  848. name string
  849. header Header
  850. expectErr bool
  851. errString string
  852. }{
  853. {
  854. "invalid version block",
  855. Header{Version: version.Consensus{Block: version.BlockProtocol + 1}},
  856. true, "block protocol is incorrect",
  857. },
  858. {
  859. "invalid chain ID length",
  860. Header{
  861. Version: version.Consensus{Block: version.BlockProtocol},
  862. ChainID: string(make([]byte, MaxChainIDLen+1)),
  863. },
  864. true, "chainID is too long",
  865. },
  866. {
  867. "invalid height (negative)",
  868. Header{
  869. Version: version.Consensus{Block: version.BlockProtocol},
  870. ChainID: string(make([]byte, MaxChainIDLen)),
  871. Height: -1,
  872. },
  873. true, "negative Height",
  874. },
  875. {
  876. "invalid height (zero)",
  877. Header{
  878. Version: version.Consensus{Block: version.BlockProtocol},
  879. ChainID: string(make([]byte, MaxChainIDLen)),
  880. Height: 0,
  881. },
  882. true, "zero Height",
  883. },
  884. {
  885. "invalid block ID hash",
  886. Header{
  887. Version: version.Consensus{Block: version.BlockProtocol},
  888. ChainID: string(make([]byte, MaxChainIDLen)),
  889. Height: 1,
  890. LastBlockID: BlockID{
  891. Hash: make([]byte, tmhash.Size+1),
  892. },
  893. },
  894. true, "wrong Hash",
  895. },
  896. {
  897. "invalid block ID parts header hash",
  898. Header{
  899. Version: version.Consensus{Block: version.BlockProtocol},
  900. ChainID: string(make([]byte, MaxChainIDLen)),
  901. Height: 1,
  902. LastBlockID: BlockID{
  903. Hash: make([]byte, tmhash.Size),
  904. PartSetHeader: PartSetHeader{
  905. Hash: make([]byte, tmhash.Size+1),
  906. },
  907. },
  908. },
  909. true, "wrong PartSetHeader",
  910. },
  911. {
  912. "invalid last commit hash",
  913. Header{
  914. Version: version.Consensus{Block: version.BlockProtocol},
  915. ChainID: string(make([]byte, MaxChainIDLen)),
  916. Height: 1,
  917. LastBlockID: BlockID{
  918. Hash: make([]byte, tmhash.Size),
  919. PartSetHeader: PartSetHeader{
  920. Hash: make([]byte, tmhash.Size),
  921. },
  922. },
  923. LastCommitHash: make([]byte, tmhash.Size+1),
  924. },
  925. true, "wrong LastCommitHash",
  926. },
  927. {
  928. "invalid data hash",
  929. Header{
  930. Version: version.Consensus{Block: version.BlockProtocol},
  931. ChainID: string(make([]byte, MaxChainIDLen)),
  932. Height: 1,
  933. LastBlockID: BlockID{
  934. Hash: make([]byte, tmhash.Size),
  935. PartSetHeader: PartSetHeader{
  936. Hash: make([]byte, tmhash.Size),
  937. },
  938. },
  939. LastCommitHash: make([]byte, tmhash.Size),
  940. DataHash: make([]byte, tmhash.Size+1),
  941. },
  942. true, "wrong DataHash",
  943. },
  944. {
  945. "invalid evidence hash",
  946. Header{
  947. Version: version.Consensus{Block: version.BlockProtocol},
  948. ChainID: string(make([]byte, MaxChainIDLen)),
  949. Height: 1,
  950. LastBlockID: BlockID{
  951. Hash: make([]byte, tmhash.Size),
  952. PartSetHeader: PartSetHeader{
  953. Hash: make([]byte, tmhash.Size),
  954. },
  955. },
  956. LastCommitHash: make([]byte, tmhash.Size),
  957. DataHash: make([]byte, tmhash.Size),
  958. EvidenceHash: make([]byte, tmhash.Size+1),
  959. },
  960. true, "wrong EvidenceHash",
  961. },
  962. {
  963. "invalid proposer address",
  964. Header{
  965. Version: version.Consensus{Block: version.BlockProtocol},
  966. ChainID: string(make([]byte, MaxChainIDLen)),
  967. Height: 1,
  968. LastBlockID: BlockID{
  969. Hash: make([]byte, tmhash.Size),
  970. PartSetHeader: PartSetHeader{
  971. Hash: make([]byte, tmhash.Size),
  972. },
  973. },
  974. LastCommitHash: make([]byte, tmhash.Size),
  975. DataHash: make([]byte, tmhash.Size),
  976. EvidenceHash: make([]byte, tmhash.Size),
  977. ProposerAddress: make([]byte, crypto.AddressSize+1),
  978. },
  979. true, "invalid ProposerAddress length",
  980. },
  981. {
  982. "invalid validator hash",
  983. Header{
  984. Version: version.Consensus{Block: version.BlockProtocol},
  985. ChainID: string(make([]byte, MaxChainIDLen)),
  986. Height: 1,
  987. LastBlockID: BlockID{
  988. Hash: make([]byte, tmhash.Size),
  989. PartSetHeader: PartSetHeader{
  990. Hash: make([]byte, tmhash.Size),
  991. },
  992. },
  993. LastCommitHash: make([]byte, tmhash.Size),
  994. DataHash: make([]byte, tmhash.Size),
  995. EvidenceHash: make([]byte, tmhash.Size),
  996. ProposerAddress: make([]byte, crypto.AddressSize),
  997. ValidatorsHash: make([]byte, tmhash.Size+1),
  998. },
  999. true, "wrong ValidatorsHash",
  1000. },
  1001. {
  1002. "invalid next validator hash",
  1003. Header{
  1004. Version: version.Consensus{Block: version.BlockProtocol},
  1005. ChainID: string(make([]byte, MaxChainIDLen)),
  1006. Height: 1,
  1007. LastBlockID: BlockID{
  1008. Hash: make([]byte, tmhash.Size),
  1009. PartSetHeader: PartSetHeader{
  1010. Hash: make([]byte, tmhash.Size),
  1011. },
  1012. },
  1013. LastCommitHash: make([]byte, tmhash.Size),
  1014. DataHash: make([]byte, tmhash.Size),
  1015. EvidenceHash: make([]byte, tmhash.Size),
  1016. ProposerAddress: make([]byte, crypto.AddressSize),
  1017. ValidatorsHash: make([]byte, tmhash.Size),
  1018. NextValidatorsHash: make([]byte, tmhash.Size+1),
  1019. },
  1020. true, "wrong NextValidatorsHash",
  1021. },
  1022. {
  1023. "invalid consensus hash",
  1024. Header{
  1025. Version: version.Consensus{Block: version.BlockProtocol},
  1026. ChainID: string(make([]byte, MaxChainIDLen)),
  1027. Height: 1,
  1028. LastBlockID: BlockID{
  1029. Hash: make([]byte, tmhash.Size),
  1030. PartSetHeader: PartSetHeader{
  1031. Hash: make([]byte, tmhash.Size),
  1032. },
  1033. },
  1034. LastCommitHash: make([]byte, tmhash.Size),
  1035. DataHash: make([]byte, tmhash.Size),
  1036. EvidenceHash: make([]byte, tmhash.Size),
  1037. ProposerAddress: make([]byte, crypto.AddressSize),
  1038. ValidatorsHash: make([]byte, tmhash.Size),
  1039. NextValidatorsHash: make([]byte, tmhash.Size),
  1040. ConsensusHash: make([]byte, tmhash.Size+1),
  1041. },
  1042. true, "wrong ConsensusHash",
  1043. },
  1044. {
  1045. "invalid last results hash",
  1046. Header{
  1047. Version: version.Consensus{Block: version.BlockProtocol},
  1048. ChainID: string(make([]byte, MaxChainIDLen)),
  1049. Height: 1,
  1050. LastBlockID: BlockID{
  1051. Hash: make([]byte, tmhash.Size),
  1052. PartSetHeader: PartSetHeader{
  1053. Hash: make([]byte, tmhash.Size),
  1054. },
  1055. },
  1056. LastCommitHash: make([]byte, tmhash.Size),
  1057. DataHash: make([]byte, tmhash.Size),
  1058. EvidenceHash: make([]byte, tmhash.Size),
  1059. ProposerAddress: make([]byte, crypto.AddressSize),
  1060. ValidatorsHash: make([]byte, tmhash.Size),
  1061. NextValidatorsHash: make([]byte, tmhash.Size),
  1062. ConsensusHash: make([]byte, tmhash.Size),
  1063. LastResultsHash: make([]byte, tmhash.Size+1),
  1064. },
  1065. true, "wrong LastResultsHash",
  1066. },
  1067. {
  1068. "valid header",
  1069. Header{
  1070. Version: version.Consensus{Block: version.BlockProtocol},
  1071. ChainID: string(make([]byte, MaxChainIDLen)),
  1072. Height: 1,
  1073. LastBlockID: BlockID{
  1074. Hash: make([]byte, tmhash.Size),
  1075. PartSetHeader: PartSetHeader{
  1076. Hash: make([]byte, tmhash.Size),
  1077. },
  1078. },
  1079. LastCommitHash: make([]byte, tmhash.Size),
  1080. DataHash: make([]byte, tmhash.Size),
  1081. EvidenceHash: make([]byte, tmhash.Size),
  1082. ProposerAddress: make([]byte, crypto.AddressSize),
  1083. ValidatorsHash: make([]byte, tmhash.Size),
  1084. NextValidatorsHash: make([]byte, tmhash.Size),
  1085. ConsensusHash: make([]byte, tmhash.Size),
  1086. LastResultsHash: make([]byte, tmhash.Size),
  1087. },
  1088. false, "",
  1089. },
  1090. }
  1091. for _, tc := range testCases {
  1092. tc := tc
  1093. t.Run(tc.name, func(t *testing.T) {
  1094. err := tc.header.ValidateBasic()
  1095. if tc.expectErr {
  1096. require.Error(t, err)
  1097. require.Contains(t, err.Error(), tc.errString)
  1098. } else {
  1099. require.NoError(t, err)
  1100. }
  1101. })
  1102. }
  1103. }
  1104. func TestCommit_ValidateBasic(t *testing.T) {
  1105. testCases := []struct {
  1106. name string
  1107. commit *Commit
  1108. expectErr bool
  1109. errString string
  1110. }{
  1111. {
  1112. "invalid height",
  1113. &Commit{Height: -1},
  1114. true, "negative Height",
  1115. },
  1116. {
  1117. "invalid round",
  1118. &Commit{Height: 1, Round: -1},
  1119. true, "negative Round",
  1120. },
  1121. {
  1122. "invalid block ID",
  1123. &Commit{
  1124. Height: 1,
  1125. Round: 1,
  1126. BlockID: BlockID{},
  1127. },
  1128. true, "commit cannot be for nil block",
  1129. },
  1130. {
  1131. "no signatures",
  1132. &Commit{
  1133. Height: 1,
  1134. Round: 1,
  1135. BlockID: BlockID{
  1136. Hash: make([]byte, tmhash.Size),
  1137. PartSetHeader: PartSetHeader{
  1138. Hash: make([]byte, tmhash.Size),
  1139. },
  1140. },
  1141. },
  1142. true, "no signatures in commit",
  1143. },
  1144. {
  1145. "invalid signature",
  1146. &Commit{
  1147. Height: 1,
  1148. Round: 1,
  1149. BlockID: BlockID{
  1150. Hash: make([]byte, tmhash.Size),
  1151. PartSetHeader: PartSetHeader{
  1152. Hash: make([]byte, tmhash.Size),
  1153. },
  1154. },
  1155. Signatures: []CommitSig{
  1156. {
  1157. BlockIDFlag: BlockIDFlagCommit,
  1158. ValidatorAddress: make([]byte, crypto.AddressSize),
  1159. Signature: make([]byte, MaxSignatureSize+1),
  1160. },
  1161. },
  1162. },
  1163. true, "wrong CommitSig",
  1164. },
  1165. {
  1166. "valid commit",
  1167. &Commit{
  1168. Height: 1,
  1169. Round: 1,
  1170. BlockID: BlockID{
  1171. Hash: make([]byte, tmhash.Size),
  1172. PartSetHeader: PartSetHeader{
  1173. Hash: make([]byte, tmhash.Size),
  1174. },
  1175. },
  1176. Signatures: []CommitSig{
  1177. {
  1178. BlockIDFlag: BlockIDFlagCommit,
  1179. ValidatorAddress: make([]byte, crypto.AddressSize),
  1180. Signature: make([]byte, MaxSignatureSize),
  1181. },
  1182. },
  1183. },
  1184. false, "",
  1185. },
  1186. }
  1187. for _, tc := range testCases {
  1188. tc := tc
  1189. t.Run(tc.name, func(t *testing.T) {
  1190. err := tc.commit.ValidateBasic()
  1191. if tc.expectErr {
  1192. require.Error(t, err)
  1193. require.Contains(t, err.Error(), tc.errString)
  1194. } else {
  1195. require.NoError(t, err)
  1196. }
  1197. })
  1198. }
  1199. }
  1200. func TestHeaderHashVector(t *testing.T) {
  1201. chainID := "test"
  1202. h := Header{
  1203. Version: version.Consensus{Block: 1, App: 1},
  1204. ChainID: chainID,
  1205. Height: 50,
  1206. Time: time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC),
  1207. LastBlockID: BlockID{},
  1208. LastCommitHash: []byte("f2564c78071e26643ae9b3e2a19fa0dc10d4d9e873aa0be808660123f11a1e78"),
  1209. DataHash: []byte("f2564c78071e26643ae9b3e2a19fa0dc10d4d9e873aa0be808660123f11a1e78"),
  1210. ValidatorsHash: []byte("f2564c78071e26643ae9b3e2a19fa0dc10d4d9e873aa0be808660123f11a1e78"),
  1211. NextValidatorsHash: []byte("f2564c78071e26643ae9b3e2a19fa0dc10d4d9e873aa0be808660123f11a1e78"),
  1212. ConsensusHash: []byte("f2564c78071e26643ae9b3e2a19fa0dc10d4d9e873aa0be808660123f11a1e78"),
  1213. AppHash: []byte("f2564c78071e26643ae9b3e2a19fa0dc10d4d9e873aa0be808660123f11a1e78"),
  1214. LastResultsHash: []byte("f2564c78071e26643ae9b3e2a19fa0dc10d4d9e873aa0be808660123f11a1e78"),
  1215. EvidenceHash: []byte("f2564c78071e26643ae9b3e2a19fa0dc10d4d9e873aa0be808660123f11a1e78"),
  1216. ProposerAddress: []byte("2915b7b15f979e48ebc61774bb1d86ba3136b7eb"),
  1217. }
  1218. testCases := []struct {
  1219. header Header
  1220. expBytes string
  1221. }{
  1222. {header: h, expBytes: "87b6117ac7f827d656f178a3d6d30b24b205db2b6a3a053bae8baf4618570bfc"},
  1223. }
  1224. for _, tc := range testCases {
  1225. hash := tc.header.Hash()
  1226. require.Equal(t, tc.expBytes, hex.EncodeToString(hash))
  1227. }
  1228. }