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.

1352 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. ctx, cancel := context.WithCancel(context.Background())
  486. defer cancel()
  487. type commitVoteTest struct {
  488. blockIDs []BlockID
  489. numVotes []int // must sum to numValidators
  490. numValidators int
  491. valid bool
  492. }
  493. testCases := []commitVoteTest{
  494. {[]BlockID{blockID, {}}, []int{67, 33}, 100, true},
  495. }
  496. for _, tc := range testCases {
  497. voteSet, valSet, vals := randVoteSet(height-1, round, tmproto.PrecommitType, tc.numValidators, 1)
  498. vi := int32(0)
  499. for n := range tc.blockIDs {
  500. for i := 0; i < tc.numVotes[n]; i++ {
  501. pubKey, err := vals[vi].GetPubKey(ctx)
  502. require.NoError(t, err)
  503. vote := &Vote{
  504. ValidatorAddress: pubKey.Address(),
  505. ValidatorIndex: vi,
  506. Height: height - 1,
  507. Round: round,
  508. Type: tmproto.PrecommitType,
  509. BlockID: tc.blockIDs[n],
  510. Timestamp: tmtime.Now(),
  511. }
  512. added, err := signAddVote(vals[vi], vote, voteSet)
  513. assert.NoError(t, err)
  514. assert.True(t, added)
  515. vi++
  516. }
  517. }
  518. if tc.valid {
  519. commit := voteSet.MakeCommit() // panics without > 2/3 valid votes
  520. assert.NotNil(t, commit)
  521. err := valSet.VerifyCommit(voteSet.ChainID(), blockID, height-1, commit)
  522. assert.Nil(t, err)
  523. } else {
  524. assert.Panics(t, func() { voteSet.MakeCommit() })
  525. }
  526. }
  527. }
  528. func TestBlockIDValidateBasic(t *testing.T) {
  529. validBlockID := BlockID{
  530. Hash: bytes.HexBytes{},
  531. PartSetHeader: PartSetHeader{
  532. Total: 1,
  533. Hash: bytes.HexBytes{},
  534. },
  535. }
  536. invalidBlockID := BlockID{
  537. Hash: []byte{0},
  538. PartSetHeader: PartSetHeader{
  539. Total: 1,
  540. Hash: []byte{0},
  541. },
  542. }
  543. testCases := []struct {
  544. testName string
  545. blockIDHash bytes.HexBytes
  546. blockIDPartSetHeader PartSetHeader
  547. expectErr bool
  548. }{
  549. {"Valid BlockID", validBlockID.Hash, validBlockID.PartSetHeader, false},
  550. {"Invalid BlockID", invalidBlockID.Hash, validBlockID.PartSetHeader, true},
  551. {"Invalid BlockID", validBlockID.Hash, invalidBlockID.PartSetHeader, true},
  552. }
  553. for _, tc := range testCases {
  554. tc := tc
  555. t.Run(tc.testName, func(t *testing.T) {
  556. blockID := BlockID{
  557. Hash: tc.blockIDHash,
  558. PartSetHeader: tc.blockIDPartSetHeader,
  559. }
  560. assert.Equal(t, tc.expectErr, blockID.ValidateBasic() != nil, "Validate Basic had an unexpected result")
  561. })
  562. }
  563. }
  564. func TestBlockProtoBuf(t *testing.T) {
  565. h := mrand.Int63()
  566. c1 := randCommit(time.Now())
  567. b1 := MakeBlock(h, []Tx{Tx([]byte{1})}, &Commit{Signatures: []CommitSig{}}, []Evidence{})
  568. b1.ProposerAddress = tmrand.Bytes(crypto.AddressSize)
  569. b2 := MakeBlock(h, []Tx{Tx([]byte{1})}, c1, []Evidence{})
  570. b2.ProposerAddress = tmrand.Bytes(crypto.AddressSize)
  571. evidenceTime := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
  572. evi := NewMockDuplicateVoteEvidence(h, evidenceTime, "block-test-chain")
  573. b2.Evidence = EvidenceData{Evidence: EvidenceList{evi}}
  574. b2.EvidenceHash = b2.Evidence.Hash()
  575. b3 := MakeBlock(h, []Tx{}, c1, []Evidence{})
  576. b3.ProposerAddress = tmrand.Bytes(crypto.AddressSize)
  577. testCases := []struct {
  578. msg string
  579. b1 *Block
  580. expPass bool
  581. expPass2 bool
  582. }{
  583. {"nil block", nil, false, false},
  584. {"b1", b1, true, true},
  585. {"b2", b2, true, true},
  586. {"b3", b3, true, true},
  587. }
  588. for _, tc := range testCases {
  589. pb, err := tc.b1.ToProto()
  590. if tc.expPass {
  591. require.NoError(t, err, tc.msg)
  592. } else {
  593. require.Error(t, err, tc.msg)
  594. }
  595. block, err := BlockFromProto(pb)
  596. if tc.expPass2 {
  597. require.NoError(t, err, tc.msg)
  598. require.EqualValues(t, tc.b1.Header, block.Header, tc.msg)
  599. require.EqualValues(t, tc.b1.Data, block.Data, tc.msg)
  600. require.EqualValues(t, tc.b1.Evidence.Evidence, block.Evidence.Evidence, tc.msg)
  601. require.EqualValues(t, *tc.b1.LastCommit, *block.LastCommit, tc.msg)
  602. } else {
  603. require.Error(t, err, tc.msg)
  604. }
  605. }
  606. }
  607. func TestDataProtoBuf(t *testing.T) {
  608. data := &Data{Txs: Txs{Tx([]byte{1}), Tx([]byte{2}), Tx([]byte{3})}}
  609. data2 := &Data{Txs: Txs{}}
  610. testCases := []struct {
  611. msg string
  612. data1 *Data
  613. expPass bool
  614. }{
  615. {"success", data, true},
  616. {"success data2", data2, true},
  617. }
  618. for _, tc := range testCases {
  619. protoData := tc.data1.ToProto()
  620. d, err := DataFromProto(&protoData)
  621. if tc.expPass {
  622. require.NoError(t, err, tc.msg)
  623. require.EqualValues(t, tc.data1, &d, tc.msg)
  624. } else {
  625. require.Error(t, err, tc.msg)
  626. }
  627. }
  628. }
  629. // TestEvidenceDataProtoBuf ensures parity in converting to and from proto.
  630. func TestEvidenceDataProtoBuf(t *testing.T) {
  631. const chainID = "mychain"
  632. ev := NewMockDuplicateVoteEvidence(math.MaxInt64, time.Now(), chainID)
  633. data := &EvidenceData{Evidence: EvidenceList{ev}}
  634. _ = data.ByteSize()
  635. testCases := []struct {
  636. msg string
  637. data1 *EvidenceData
  638. expPass1 bool
  639. expPass2 bool
  640. }{
  641. {"success", data, true, true},
  642. {"empty evidenceData", &EvidenceData{Evidence: EvidenceList{}}, true, true},
  643. {"fail nil Data", nil, false, false},
  644. }
  645. for _, tc := range testCases {
  646. protoData, err := tc.data1.ToProto()
  647. if tc.expPass1 {
  648. require.NoError(t, err, tc.msg)
  649. } else {
  650. require.Error(t, err, tc.msg)
  651. }
  652. eviD := new(EvidenceData)
  653. err = eviD.FromProto(protoData)
  654. if tc.expPass2 {
  655. require.NoError(t, err, tc.msg)
  656. require.Equal(t, tc.data1, eviD, tc.msg)
  657. } else {
  658. require.Error(t, err, tc.msg)
  659. }
  660. }
  661. }
  662. // exposed for testing
  663. func MakeRandHeader() Header {
  664. chainID := "test"
  665. t := time.Now()
  666. height := mrand.Int63()
  667. randBytes := tmrand.Bytes(tmhash.Size)
  668. randAddress := tmrand.Bytes(crypto.AddressSize)
  669. h := Header{
  670. Version: version.Consensus{Block: version.BlockProtocol, App: 1},
  671. ChainID: chainID,
  672. Height: height,
  673. Time: t,
  674. LastBlockID: BlockID{},
  675. LastCommitHash: randBytes,
  676. DataHash: randBytes,
  677. ValidatorsHash: randBytes,
  678. NextValidatorsHash: randBytes,
  679. ConsensusHash: randBytes,
  680. AppHash: randBytes,
  681. LastResultsHash: randBytes,
  682. EvidenceHash: randBytes,
  683. ProposerAddress: randAddress,
  684. }
  685. return h
  686. }
  687. func TestHeaderProto(t *testing.T) {
  688. h1 := MakeRandHeader()
  689. tc := []struct {
  690. msg string
  691. h1 *Header
  692. expPass bool
  693. }{
  694. {"success", &h1, true},
  695. {"failure empty Header", &Header{}, false},
  696. }
  697. for _, tt := range tc {
  698. tt := tt
  699. t.Run(tt.msg, func(t *testing.T) {
  700. pb := tt.h1.ToProto()
  701. h, err := HeaderFromProto(pb)
  702. if tt.expPass {
  703. require.NoError(t, err, tt.msg)
  704. require.Equal(t, tt.h1, &h, tt.msg)
  705. } else {
  706. require.Error(t, err, tt.msg)
  707. }
  708. })
  709. }
  710. }
  711. func TestBlockIDProtoBuf(t *testing.T) {
  712. blockID := makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))
  713. testCases := []struct {
  714. msg string
  715. bid1 *BlockID
  716. expPass bool
  717. }{
  718. {"success", &blockID, true},
  719. {"success empty", &BlockID{}, true},
  720. {"failure BlockID nil", nil, false},
  721. }
  722. for _, tc := range testCases {
  723. protoBlockID := tc.bid1.ToProto()
  724. bi, err := BlockIDFromProto(&protoBlockID)
  725. if tc.expPass {
  726. require.NoError(t, err)
  727. require.Equal(t, tc.bid1, bi, tc.msg)
  728. } else {
  729. require.NotEqual(t, tc.bid1, bi, tc.msg)
  730. }
  731. }
  732. }
  733. func TestSignedHeaderProtoBuf(t *testing.T) {
  734. commit := randCommit(time.Now())
  735. h := MakeRandHeader()
  736. sh := SignedHeader{Header: &h, Commit: commit}
  737. testCases := []struct {
  738. msg string
  739. sh1 *SignedHeader
  740. expPass bool
  741. }{
  742. {"empty SignedHeader 2", &SignedHeader{}, true},
  743. {"success", &sh, true},
  744. {"failure nil", nil, false},
  745. }
  746. for _, tc := range testCases {
  747. protoSignedHeader := tc.sh1.ToProto()
  748. sh, err := SignedHeaderFromProto(protoSignedHeader)
  749. if tc.expPass {
  750. require.NoError(t, err, tc.msg)
  751. require.Equal(t, tc.sh1, sh, tc.msg)
  752. } else {
  753. require.Error(t, err, tc.msg)
  754. }
  755. }
  756. }
  757. func TestBlockIDEquals(t *testing.T) {
  758. var (
  759. blockID = makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))
  760. blockIDDuplicate = makeBlockID([]byte("hash"), 2, []byte("part_set_hash"))
  761. blockIDDifferent = makeBlockID([]byte("different_hash"), 2, []byte("part_set_hash"))
  762. blockIDEmpty = BlockID{}
  763. )
  764. assert.True(t, blockID.Equals(blockIDDuplicate))
  765. assert.False(t, blockID.Equals(blockIDDifferent))
  766. assert.False(t, blockID.Equals(blockIDEmpty))
  767. assert.True(t, blockIDEmpty.Equals(blockIDEmpty))
  768. assert.False(t, blockIDEmpty.Equals(blockIDDifferent))
  769. }
  770. func TestCommitSig_ValidateBasic(t *testing.T) {
  771. testCases := []struct {
  772. name string
  773. cs CommitSig
  774. expectErr bool
  775. errString string
  776. }{
  777. {
  778. "invalid ID flag",
  779. CommitSig{BlockIDFlag: BlockIDFlag(0xFF)},
  780. true, "unknown BlockIDFlag",
  781. },
  782. {
  783. "BlockIDFlagAbsent validator address present",
  784. CommitSig{BlockIDFlag: BlockIDFlagAbsent, ValidatorAddress: crypto.Address("testaddr")},
  785. true, "validator address is present",
  786. },
  787. {
  788. "BlockIDFlagAbsent timestamp present",
  789. CommitSig{BlockIDFlag: BlockIDFlagAbsent, Timestamp: time.Now().UTC()},
  790. true, "time is present",
  791. },
  792. {
  793. "BlockIDFlagAbsent signatures present",
  794. CommitSig{BlockIDFlag: BlockIDFlagAbsent, Signature: []byte{0xAA}},
  795. true, "signature is present",
  796. },
  797. {
  798. "BlockIDFlagAbsent valid BlockIDFlagAbsent",
  799. CommitSig{BlockIDFlag: BlockIDFlagAbsent},
  800. false, "",
  801. },
  802. {
  803. "non-BlockIDFlagAbsent invalid validator address",
  804. CommitSig{BlockIDFlag: BlockIDFlagCommit, ValidatorAddress: make([]byte, 1)},
  805. true, "expected ValidatorAddress size",
  806. },
  807. {
  808. "non-BlockIDFlagAbsent invalid signature (zero)",
  809. CommitSig{
  810. BlockIDFlag: BlockIDFlagCommit,
  811. ValidatorAddress: make([]byte, crypto.AddressSize),
  812. Signature: make([]byte, 0),
  813. },
  814. true, "signature is missing",
  815. },
  816. {
  817. "non-BlockIDFlagAbsent invalid signature (too large)",
  818. CommitSig{
  819. BlockIDFlag: BlockIDFlagCommit,
  820. ValidatorAddress: make([]byte, crypto.AddressSize),
  821. Signature: make([]byte, MaxSignatureSize+1),
  822. },
  823. true, "signature is too big",
  824. },
  825. {
  826. "non-BlockIDFlagAbsent valid",
  827. CommitSig{
  828. BlockIDFlag: BlockIDFlagCommit,
  829. ValidatorAddress: make([]byte, crypto.AddressSize),
  830. Signature: make([]byte, MaxSignatureSize),
  831. },
  832. false, "",
  833. },
  834. }
  835. for _, tc := range testCases {
  836. tc := tc
  837. t.Run(tc.name, func(t *testing.T) {
  838. err := tc.cs.ValidateBasic()
  839. if tc.expectErr {
  840. require.Error(t, err)
  841. require.Contains(t, err.Error(), tc.errString)
  842. } else {
  843. require.NoError(t, err)
  844. }
  845. })
  846. }
  847. }
  848. func TestHeader_ValidateBasic(t *testing.T) {
  849. testCases := []struct {
  850. name string
  851. header Header
  852. expectErr bool
  853. errString string
  854. }{
  855. {
  856. "invalid version block",
  857. Header{Version: version.Consensus{Block: version.BlockProtocol + 1}},
  858. true, "block protocol is incorrect",
  859. },
  860. {
  861. "invalid chain ID length",
  862. Header{
  863. Version: version.Consensus{Block: version.BlockProtocol},
  864. ChainID: string(make([]byte, MaxChainIDLen+1)),
  865. },
  866. true, "chainID is too long",
  867. },
  868. {
  869. "invalid height (negative)",
  870. Header{
  871. Version: version.Consensus{Block: version.BlockProtocol},
  872. ChainID: string(make([]byte, MaxChainIDLen)),
  873. Height: -1,
  874. },
  875. true, "negative Height",
  876. },
  877. {
  878. "invalid height (zero)",
  879. Header{
  880. Version: version.Consensus{Block: version.BlockProtocol},
  881. ChainID: string(make([]byte, MaxChainIDLen)),
  882. Height: 0,
  883. },
  884. true, "zero Height",
  885. },
  886. {
  887. "invalid block ID hash",
  888. Header{
  889. Version: version.Consensus{Block: version.BlockProtocol},
  890. ChainID: string(make([]byte, MaxChainIDLen)),
  891. Height: 1,
  892. LastBlockID: BlockID{
  893. Hash: make([]byte, tmhash.Size+1),
  894. },
  895. },
  896. true, "wrong Hash",
  897. },
  898. {
  899. "invalid block ID parts header hash",
  900. Header{
  901. Version: version.Consensus{Block: version.BlockProtocol},
  902. ChainID: string(make([]byte, MaxChainIDLen)),
  903. Height: 1,
  904. LastBlockID: BlockID{
  905. Hash: make([]byte, tmhash.Size),
  906. PartSetHeader: PartSetHeader{
  907. Hash: make([]byte, tmhash.Size+1),
  908. },
  909. },
  910. },
  911. true, "wrong PartSetHeader",
  912. },
  913. {
  914. "invalid last commit hash",
  915. Header{
  916. Version: version.Consensus{Block: version.BlockProtocol},
  917. ChainID: string(make([]byte, MaxChainIDLen)),
  918. Height: 1,
  919. LastBlockID: BlockID{
  920. Hash: make([]byte, tmhash.Size),
  921. PartSetHeader: PartSetHeader{
  922. Hash: make([]byte, tmhash.Size),
  923. },
  924. },
  925. LastCommitHash: make([]byte, tmhash.Size+1),
  926. },
  927. true, "wrong LastCommitHash",
  928. },
  929. {
  930. "invalid data hash",
  931. Header{
  932. Version: version.Consensus{Block: version.BlockProtocol},
  933. ChainID: string(make([]byte, MaxChainIDLen)),
  934. Height: 1,
  935. LastBlockID: BlockID{
  936. Hash: make([]byte, tmhash.Size),
  937. PartSetHeader: PartSetHeader{
  938. Hash: make([]byte, tmhash.Size),
  939. },
  940. },
  941. LastCommitHash: make([]byte, tmhash.Size),
  942. DataHash: make([]byte, tmhash.Size+1),
  943. },
  944. true, "wrong DataHash",
  945. },
  946. {
  947. "invalid evidence hash",
  948. Header{
  949. Version: version.Consensus{Block: version.BlockProtocol},
  950. ChainID: string(make([]byte, MaxChainIDLen)),
  951. Height: 1,
  952. LastBlockID: BlockID{
  953. Hash: make([]byte, tmhash.Size),
  954. PartSetHeader: PartSetHeader{
  955. Hash: make([]byte, tmhash.Size),
  956. },
  957. },
  958. LastCommitHash: make([]byte, tmhash.Size),
  959. DataHash: make([]byte, tmhash.Size),
  960. EvidenceHash: make([]byte, tmhash.Size+1),
  961. },
  962. true, "wrong EvidenceHash",
  963. },
  964. {
  965. "invalid proposer address",
  966. Header{
  967. Version: version.Consensus{Block: version.BlockProtocol},
  968. ChainID: string(make([]byte, MaxChainIDLen)),
  969. Height: 1,
  970. LastBlockID: BlockID{
  971. Hash: make([]byte, tmhash.Size),
  972. PartSetHeader: PartSetHeader{
  973. Hash: make([]byte, tmhash.Size),
  974. },
  975. },
  976. LastCommitHash: make([]byte, tmhash.Size),
  977. DataHash: make([]byte, tmhash.Size),
  978. EvidenceHash: make([]byte, tmhash.Size),
  979. ProposerAddress: make([]byte, crypto.AddressSize+1),
  980. },
  981. true, "invalid ProposerAddress length",
  982. },
  983. {
  984. "invalid validator hash",
  985. Header{
  986. Version: version.Consensus{Block: version.BlockProtocol},
  987. ChainID: string(make([]byte, MaxChainIDLen)),
  988. Height: 1,
  989. LastBlockID: BlockID{
  990. Hash: make([]byte, tmhash.Size),
  991. PartSetHeader: PartSetHeader{
  992. Hash: make([]byte, tmhash.Size),
  993. },
  994. },
  995. LastCommitHash: make([]byte, tmhash.Size),
  996. DataHash: make([]byte, tmhash.Size),
  997. EvidenceHash: make([]byte, tmhash.Size),
  998. ProposerAddress: make([]byte, crypto.AddressSize),
  999. ValidatorsHash: make([]byte, tmhash.Size+1),
  1000. },
  1001. true, "wrong ValidatorsHash",
  1002. },
  1003. {
  1004. "invalid next validator hash",
  1005. Header{
  1006. Version: version.Consensus{Block: version.BlockProtocol},
  1007. ChainID: string(make([]byte, MaxChainIDLen)),
  1008. Height: 1,
  1009. LastBlockID: BlockID{
  1010. Hash: make([]byte, tmhash.Size),
  1011. PartSetHeader: PartSetHeader{
  1012. Hash: make([]byte, tmhash.Size),
  1013. },
  1014. },
  1015. LastCommitHash: make([]byte, tmhash.Size),
  1016. DataHash: make([]byte, tmhash.Size),
  1017. EvidenceHash: make([]byte, tmhash.Size),
  1018. ProposerAddress: make([]byte, crypto.AddressSize),
  1019. ValidatorsHash: make([]byte, tmhash.Size),
  1020. NextValidatorsHash: make([]byte, tmhash.Size+1),
  1021. },
  1022. true, "wrong NextValidatorsHash",
  1023. },
  1024. {
  1025. "invalid consensus hash",
  1026. Header{
  1027. Version: version.Consensus{Block: version.BlockProtocol},
  1028. ChainID: string(make([]byte, MaxChainIDLen)),
  1029. Height: 1,
  1030. LastBlockID: BlockID{
  1031. Hash: make([]byte, tmhash.Size),
  1032. PartSetHeader: PartSetHeader{
  1033. Hash: make([]byte, tmhash.Size),
  1034. },
  1035. },
  1036. LastCommitHash: make([]byte, tmhash.Size),
  1037. DataHash: make([]byte, tmhash.Size),
  1038. EvidenceHash: make([]byte, tmhash.Size),
  1039. ProposerAddress: make([]byte, crypto.AddressSize),
  1040. ValidatorsHash: make([]byte, tmhash.Size),
  1041. NextValidatorsHash: make([]byte, tmhash.Size),
  1042. ConsensusHash: make([]byte, tmhash.Size+1),
  1043. },
  1044. true, "wrong ConsensusHash",
  1045. },
  1046. {
  1047. "invalid last results hash",
  1048. Header{
  1049. Version: version.Consensus{Block: version.BlockProtocol},
  1050. ChainID: string(make([]byte, MaxChainIDLen)),
  1051. Height: 1,
  1052. LastBlockID: BlockID{
  1053. Hash: make([]byte, tmhash.Size),
  1054. PartSetHeader: PartSetHeader{
  1055. Hash: make([]byte, tmhash.Size),
  1056. },
  1057. },
  1058. LastCommitHash: make([]byte, tmhash.Size),
  1059. DataHash: make([]byte, tmhash.Size),
  1060. EvidenceHash: make([]byte, tmhash.Size),
  1061. ProposerAddress: make([]byte, crypto.AddressSize),
  1062. ValidatorsHash: make([]byte, tmhash.Size),
  1063. NextValidatorsHash: make([]byte, tmhash.Size),
  1064. ConsensusHash: make([]byte, tmhash.Size),
  1065. LastResultsHash: make([]byte, tmhash.Size+1),
  1066. },
  1067. true, "wrong LastResultsHash",
  1068. },
  1069. {
  1070. "valid header",
  1071. Header{
  1072. Version: version.Consensus{Block: version.BlockProtocol},
  1073. ChainID: string(make([]byte, MaxChainIDLen)),
  1074. Height: 1,
  1075. LastBlockID: BlockID{
  1076. Hash: make([]byte, tmhash.Size),
  1077. PartSetHeader: PartSetHeader{
  1078. Hash: make([]byte, tmhash.Size),
  1079. },
  1080. },
  1081. LastCommitHash: make([]byte, tmhash.Size),
  1082. DataHash: make([]byte, tmhash.Size),
  1083. EvidenceHash: make([]byte, tmhash.Size),
  1084. ProposerAddress: make([]byte, crypto.AddressSize),
  1085. ValidatorsHash: make([]byte, tmhash.Size),
  1086. NextValidatorsHash: make([]byte, tmhash.Size),
  1087. ConsensusHash: make([]byte, tmhash.Size),
  1088. LastResultsHash: make([]byte, tmhash.Size),
  1089. },
  1090. false, "",
  1091. },
  1092. }
  1093. for _, tc := range testCases {
  1094. tc := tc
  1095. t.Run(tc.name, func(t *testing.T) {
  1096. err := tc.header.ValidateBasic()
  1097. if tc.expectErr {
  1098. require.Error(t, err)
  1099. require.Contains(t, err.Error(), tc.errString)
  1100. } else {
  1101. require.NoError(t, err)
  1102. }
  1103. })
  1104. }
  1105. }
  1106. func TestCommit_ValidateBasic(t *testing.T) {
  1107. testCases := []struct {
  1108. name string
  1109. commit *Commit
  1110. expectErr bool
  1111. errString string
  1112. }{
  1113. {
  1114. "invalid height",
  1115. &Commit{Height: -1},
  1116. true, "negative Height",
  1117. },
  1118. {
  1119. "invalid round",
  1120. &Commit{Height: 1, Round: -1},
  1121. true, "negative Round",
  1122. },
  1123. {
  1124. "invalid block ID",
  1125. &Commit{
  1126. Height: 1,
  1127. Round: 1,
  1128. BlockID: BlockID{},
  1129. },
  1130. true, "commit cannot be for nil block",
  1131. },
  1132. {
  1133. "no signatures",
  1134. &Commit{
  1135. Height: 1,
  1136. Round: 1,
  1137. BlockID: BlockID{
  1138. Hash: make([]byte, tmhash.Size),
  1139. PartSetHeader: PartSetHeader{
  1140. Hash: make([]byte, tmhash.Size),
  1141. },
  1142. },
  1143. },
  1144. true, "no signatures in commit",
  1145. },
  1146. {
  1147. "invalid signature",
  1148. &Commit{
  1149. Height: 1,
  1150. Round: 1,
  1151. BlockID: BlockID{
  1152. Hash: make([]byte, tmhash.Size),
  1153. PartSetHeader: PartSetHeader{
  1154. Hash: make([]byte, tmhash.Size),
  1155. },
  1156. },
  1157. Signatures: []CommitSig{
  1158. {
  1159. BlockIDFlag: BlockIDFlagCommit,
  1160. ValidatorAddress: make([]byte, crypto.AddressSize),
  1161. Signature: make([]byte, MaxSignatureSize+1),
  1162. },
  1163. },
  1164. },
  1165. true, "wrong CommitSig",
  1166. },
  1167. {
  1168. "valid commit",
  1169. &Commit{
  1170. Height: 1,
  1171. Round: 1,
  1172. BlockID: BlockID{
  1173. Hash: make([]byte, tmhash.Size),
  1174. PartSetHeader: PartSetHeader{
  1175. Hash: make([]byte, tmhash.Size),
  1176. },
  1177. },
  1178. Signatures: []CommitSig{
  1179. {
  1180. BlockIDFlag: BlockIDFlagCommit,
  1181. ValidatorAddress: make([]byte, crypto.AddressSize),
  1182. Signature: make([]byte, MaxSignatureSize),
  1183. },
  1184. },
  1185. },
  1186. false, "",
  1187. },
  1188. }
  1189. for _, tc := range testCases {
  1190. tc := tc
  1191. t.Run(tc.name, func(t *testing.T) {
  1192. err := tc.commit.ValidateBasic()
  1193. if tc.expectErr {
  1194. require.Error(t, err)
  1195. require.Contains(t, err.Error(), tc.errString)
  1196. } else {
  1197. require.NoError(t, err)
  1198. }
  1199. })
  1200. }
  1201. }
  1202. func TestHeaderHashVector(t *testing.T) {
  1203. chainID := "test"
  1204. h := Header{
  1205. Version: version.Consensus{Block: 1, App: 1},
  1206. ChainID: chainID,
  1207. Height: 50,
  1208. Time: time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC),
  1209. LastBlockID: BlockID{},
  1210. LastCommitHash: []byte("f2564c78071e26643ae9b3e2a19fa0dc10d4d9e873aa0be808660123f11a1e78"),
  1211. DataHash: []byte("f2564c78071e26643ae9b3e2a19fa0dc10d4d9e873aa0be808660123f11a1e78"),
  1212. ValidatorsHash: []byte("f2564c78071e26643ae9b3e2a19fa0dc10d4d9e873aa0be808660123f11a1e78"),
  1213. NextValidatorsHash: []byte("f2564c78071e26643ae9b3e2a19fa0dc10d4d9e873aa0be808660123f11a1e78"),
  1214. ConsensusHash: []byte("f2564c78071e26643ae9b3e2a19fa0dc10d4d9e873aa0be808660123f11a1e78"),
  1215. AppHash: []byte("f2564c78071e26643ae9b3e2a19fa0dc10d4d9e873aa0be808660123f11a1e78"),
  1216. LastResultsHash: []byte("f2564c78071e26643ae9b3e2a19fa0dc10d4d9e873aa0be808660123f11a1e78"),
  1217. EvidenceHash: []byte("f2564c78071e26643ae9b3e2a19fa0dc10d4d9e873aa0be808660123f11a1e78"),
  1218. ProposerAddress: []byte("2915b7b15f979e48ebc61774bb1d86ba3136b7eb"),
  1219. }
  1220. testCases := []struct {
  1221. header Header
  1222. expBytes string
  1223. }{
  1224. {header: h, expBytes: "87b6117ac7f827d656f178a3d6d30b24b205db2b6a3a053bae8baf4618570bfc"},
  1225. }
  1226. for _, tc := range testCases {
  1227. hash := tc.header.Hash()
  1228. require.Equal(t, tc.expBytes, hex.EncodeToString(hash))
  1229. }
  1230. }