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.

1359 lines
35 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
10 years ago
10 years ago
6 years ago
6 years ago
6 years ago
7 years ago
10 years ago
10 years ago
  1. package types
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "github.com/gogo/protobuf/proto"
  9. gogotypes "github.com/gogo/protobuf/types"
  10. "github.com/tendermint/tendermint/crypto"
  11. "github.com/tendermint/tendermint/crypto/merkle"
  12. "github.com/tendermint/tendermint/crypto/tmhash"
  13. "github.com/tendermint/tendermint/libs/bits"
  14. tmbytes "github.com/tendermint/tendermint/libs/bytes"
  15. tmmath "github.com/tendermint/tendermint/libs/math"
  16. tmsync "github.com/tendermint/tendermint/libs/sync"
  17. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  18. tmversion "github.com/tendermint/tendermint/proto/tendermint/version"
  19. )
  20. const (
  21. // MaxHeaderBytes is a maximum header size.
  22. MaxHeaderBytes int64 = 626
  23. // MaxOverheadForBlock - maximum overhead to encode a block (up to
  24. // MaxBlockSizeBytes in size) not including it's parts except Data.
  25. // This means it also excludes the overhead for individual transactions.
  26. //
  27. // Uvarint length of MaxBlockSizeBytes: 4 bytes
  28. // 2 fields (2 embedded): 2 bytes
  29. // Uvarint length of Data.Txs: 4 bytes
  30. // Data.Txs field: 1 byte
  31. MaxOverheadForBlock int64 = 11
  32. )
  33. // Block defines the atomic unit of a Tendermint blockchain.
  34. type Block struct {
  35. mtx tmsync.Mutex
  36. Header `json:"header"`
  37. Data `json:"data"`
  38. Evidence EvidenceData `json:"evidence"`
  39. LastCommit *Commit `json:"last_commit"`
  40. }
  41. // ValidateBasic performs basic validation that doesn't involve state data.
  42. // It checks the internal consistency of the block.
  43. // Further validation is done using state#ValidateBlock.
  44. func (b *Block) ValidateBasic() error {
  45. if b == nil {
  46. return errors.New("nil block")
  47. }
  48. b.mtx.Lock()
  49. defer b.mtx.Unlock()
  50. if err := b.Header.ValidateBasic(); err != nil {
  51. return fmt.Errorf("invalid header: %w", err)
  52. }
  53. // Validate the last commit and its hash.
  54. if b.LastCommit == nil {
  55. return errors.New("nil LastCommit")
  56. }
  57. if b.Header.Height > 1 {
  58. if err := b.LastCommit.ValidateBasic(); err != nil {
  59. return fmt.Errorf("wrong LastCommit: %v", err)
  60. }
  61. }
  62. if !bytes.Equal(b.LastCommitHash, b.LastCommit.Hash()) {
  63. return fmt.Errorf("wrong Header.LastCommitHash. Expected %v, got %v",
  64. b.LastCommit.Hash(),
  65. b.LastCommitHash,
  66. )
  67. }
  68. // NOTE: b.Data.Txs may be nil, but b.Data.Hash() still works fine.
  69. if !bytes.Equal(b.DataHash, b.Data.Hash()) {
  70. return fmt.Errorf(
  71. "wrong Header.DataHash. Expected %v, got %v",
  72. b.Data.Hash(),
  73. b.DataHash,
  74. )
  75. }
  76. // NOTE: b.Evidence.Evidence may be nil, but we're just looping.
  77. for i, ev := range b.Evidence.Evidence {
  78. switch ev.(type) {
  79. case *ConflictingHeadersEvidence:
  80. // ConflictingHeadersEvidence must be broken up in pieces and never
  81. // committed as a single piece.
  82. return fmt.Errorf("found ConflictingHeadersEvidence (#%d)", i)
  83. case *PotentialAmnesiaEvidence:
  84. // PotentialAmnesiaEvidence does not contribute to anything on its own, so
  85. // reject it as well.
  86. return fmt.Errorf("found PotentialAmnesiaEvidence (#%d)", i)
  87. }
  88. if err := ev.ValidateBasic(); err != nil {
  89. return fmt.Errorf("invalid evidence (#%d): %v", i, err)
  90. }
  91. }
  92. if !bytes.Equal(b.EvidenceHash, b.Evidence.Hash()) {
  93. return fmt.Errorf("wrong Header.EvidenceHash. Expected %v, got %v",
  94. b.EvidenceHash,
  95. b.Evidence.Hash(),
  96. )
  97. }
  98. return nil
  99. }
  100. // fillHeader fills in any remaining header fields that are a function of the block data
  101. func (b *Block) fillHeader() {
  102. if b.LastCommitHash == nil {
  103. b.LastCommitHash = b.LastCommit.Hash()
  104. }
  105. if b.DataHash == nil {
  106. b.DataHash = b.Data.Hash()
  107. }
  108. if b.EvidenceHash == nil {
  109. b.EvidenceHash = b.Evidence.Hash()
  110. }
  111. }
  112. // Hash computes and returns the block hash.
  113. // If the block is incomplete, block hash is nil for safety.
  114. func (b *Block) Hash() tmbytes.HexBytes {
  115. if b == nil {
  116. return nil
  117. }
  118. b.mtx.Lock()
  119. defer b.mtx.Unlock()
  120. if b.LastCommit == nil {
  121. return nil
  122. }
  123. b.fillHeader()
  124. return b.Header.Hash()
  125. }
  126. // MakePartSet returns a PartSet containing parts of a serialized block.
  127. // This is the form in which the block is gossipped to peers.
  128. // CONTRACT: partSize is greater than zero.
  129. func (b *Block) MakePartSet(partSize uint32) *PartSet {
  130. if b == nil {
  131. return nil
  132. }
  133. b.mtx.Lock()
  134. defer b.mtx.Unlock()
  135. pbb, err := b.ToProto()
  136. if err != nil {
  137. panic(err)
  138. }
  139. bz, err := proto.Marshal(pbb)
  140. if err != nil {
  141. panic(err)
  142. }
  143. return NewPartSetFromData(bz, partSize)
  144. }
  145. // HashesTo is a convenience function that checks if a block hashes to the given argument.
  146. // Returns false if the block is nil or the hash is empty.
  147. func (b *Block) HashesTo(hash []byte) bool {
  148. if len(hash) == 0 {
  149. return false
  150. }
  151. if b == nil {
  152. return false
  153. }
  154. return bytes.Equal(b.Hash(), hash)
  155. }
  156. // Size returns size of the block in bytes.
  157. func (b *Block) Size() int {
  158. pbb, err := b.ToProto()
  159. if err != nil {
  160. return 0
  161. }
  162. return pbb.Size()
  163. }
  164. // String returns a string representation of the block
  165. //
  166. // See StringIndented.
  167. func (b *Block) String() string {
  168. return b.StringIndented("")
  169. }
  170. // StringIndented returns an indented String.
  171. //
  172. // Header
  173. // Data
  174. // Evidence
  175. // LastCommit
  176. // Hash
  177. func (b *Block) StringIndented(indent string) string {
  178. if b == nil {
  179. return "nil-Block"
  180. }
  181. return fmt.Sprintf(`Block{
  182. %s %v
  183. %s %v
  184. %s %v
  185. %s %v
  186. %s}#%v`,
  187. indent, b.Header.StringIndented(indent+" "),
  188. indent, b.Data.StringIndented(indent+" "),
  189. indent, b.Evidence.StringIndented(indent+" "),
  190. indent, b.LastCommit.StringIndented(indent+" "),
  191. indent, b.Hash())
  192. }
  193. // StringShort returns a shortened string representation of the block.
  194. func (b *Block) StringShort() string {
  195. if b == nil {
  196. return "nil-Block"
  197. }
  198. return fmt.Sprintf("Block#%X", b.Hash())
  199. }
  200. // ToProto converts Block to protobuf
  201. func (b *Block) ToProto() (*tmproto.Block, error) {
  202. if b == nil {
  203. return nil, errors.New("nil Block")
  204. }
  205. pb := new(tmproto.Block)
  206. pb.Header = *b.Header.ToProto()
  207. pb.LastCommit = b.LastCommit.ToProto()
  208. pb.Data = b.Data.ToProto()
  209. protoEvidence, err := b.Evidence.ToProto()
  210. if err != nil {
  211. return nil, err
  212. }
  213. pb.Evidence = *protoEvidence
  214. return pb, nil
  215. }
  216. // FromProto sets a protobuf Block to the given pointer.
  217. // It returns an error if the block is invalid.
  218. func BlockFromProto(bp *tmproto.Block) (*Block, error) {
  219. if bp == nil {
  220. return nil, errors.New("nil block")
  221. }
  222. b := new(Block)
  223. h, err := HeaderFromProto(&bp.Header)
  224. if err != nil {
  225. return nil, err
  226. }
  227. b.Header = h
  228. data, err := DataFromProto(&bp.Data)
  229. if err != nil {
  230. return nil, err
  231. }
  232. b.Data = data
  233. b.Evidence.FromProto(&bp.Evidence)
  234. if bp.LastCommit != nil {
  235. lc, err := CommitFromProto(bp.LastCommit)
  236. if err != nil {
  237. return nil, err
  238. }
  239. b.LastCommit = lc
  240. }
  241. return b, b.ValidateBasic()
  242. }
  243. //-----------------------------------------------------------------------------
  244. // MaxDataBytes returns the maximum size of block's data.
  245. //
  246. // XXX: Panics on negative result.
  247. func MaxDataBytes(maxBytes int64, valsCount, evidenceCount int) int64 {
  248. maxDataBytes := maxBytes -
  249. MaxOverheadForBlock -
  250. MaxHeaderBytes -
  251. int64(valsCount)*MaxVoteBytes -
  252. int64(evidenceCount)*MaxEvidenceBytes
  253. if maxDataBytes < 0 {
  254. panic(fmt.Sprintf(
  255. "Negative MaxDataBytes. Block.MaxBytes=%d is too small to accommodate header&lastCommit&evidence=%d",
  256. maxBytes,
  257. -(maxDataBytes - maxBytes),
  258. ))
  259. }
  260. return maxDataBytes
  261. }
  262. // MaxDataBytesUnknownEvidence returns the maximum size of block's data when
  263. // evidence count is unknown. MaxEvidencePerBlock will be used for the size
  264. // of evidence.
  265. //
  266. // XXX: Panics on negative result.
  267. func MaxDataBytesUnknownEvidence(maxBytes int64, valsCount int, maxNumEvidence uint32) int64 {
  268. maxEvidenceBytes := int64(maxNumEvidence) * MaxEvidenceBytes
  269. maxDataBytes := maxBytes -
  270. MaxOverheadForBlock -
  271. MaxHeaderBytes -
  272. int64(valsCount)*MaxVoteBytes -
  273. maxEvidenceBytes
  274. if maxDataBytes < 0 {
  275. panic(fmt.Sprintf(
  276. "Negative MaxDataBytesUnknownEvidence. Block.MaxBytes=%d is too small to accommodate header&lastCommit&evidence=%d",
  277. maxBytes,
  278. -(maxDataBytes - maxBytes),
  279. ))
  280. }
  281. return maxDataBytes
  282. }
  283. //-----------------------------------------------------------------------------
  284. // Header defines the structure of a Tendermint block header.
  285. // NOTE: changes to the Header should be duplicated in:
  286. // - header.Hash()
  287. // - abci.Header
  288. // - https://github.com/tendermint/spec/blob/master/spec/blockchain/blockchain.md
  289. type Header struct {
  290. // basic block info
  291. Version tmversion.Consensus `json:"version"`
  292. ChainID string `json:"chain_id"`
  293. Height int64 `json:"height"`
  294. Time time.Time `json:"time"`
  295. // prev block info
  296. LastBlockID BlockID `json:"last_block_id"`
  297. // hashes of block data
  298. LastCommitHash tmbytes.HexBytes `json:"last_commit_hash"` // commit from validators from the last block
  299. DataHash tmbytes.HexBytes `json:"data_hash"` // transactions
  300. // hashes from the app output from the prev block
  301. ValidatorsHash tmbytes.HexBytes `json:"validators_hash"` // validators for the current block
  302. NextValidatorsHash tmbytes.HexBytes `json:"next_validators_hash"` // validators for the next block
  303. ConsensusHash tmbytes.HexBytes `json:"consensus_hash"` // consensus params for current block
  304. AppHash tmbytes.HexBytes `json:"app_hash"` // state after txs from the previous block
  305. // root hash of all results from the txs from the previous block
  306. LastResultsHash tmbytes.HexBytes `json:"last_results_hash"`
  307. // consensus info
  308. EvidenceHash tmbytes.HexBytes `json:"evidence_hash"` // evidence included in the block
  309. ProposerAddress Address `json:"proposer_address"` // original proposer of the block
  310. }
  311. // Populate the Header with state-derived data.
  312. // Call this after MakeBlock to complete the Header.
  313. func (h *Header) Populate(
  314. version tmversion.Consensus, chainID string,
  315. timestamp time.Time, lastBlockID BlockID,
  316. valHash, nextValHash []byte,
  317. consensusHash, appHash, lastResultsHash []byte,
  318. proposerAddress Address,
  319. ) {
  320. h.Version = version
  321. h.ChainID = chainID
  322. h.Time = timestamp
  323. h.LastBlockID = lastBlockID
  324. h.ValidatorsHash = valHash
  325. h.NextValidatorsHash = nextValHash
  326. h.ConsensusHash = consensusHash
  327. h.AppHash = appHash
  328. h.LastResultsHash = lastResultsHash
  329. h.ProposerAddress = proposerAddress
  330. }
  331. // ValidateBasic performs stateless validation on a Header returning an error
  332. // if any validation fails.
  333. //
  334. // NOTE: Timestamp validation is subtle and handled elsewhere.
  335. func (h Header) ValidateBasic() error {
  336. if len(h.ChainID) > MaxChainIDLen {
  337. return fmt.Errorf("chainID is too long; got: %d, max: %d", len(h.ChainID), MaxChainIDLen)
  338. }
  339. if h.Height < 0 {
  340. return errors.New("negative Height")
  341. } else if h.Height == 0 {
  342. return errors.New("zero Height")
  343. }
  344. if err := h.LastBlockID.ValidateBasic(); err != nil {
  345. return fmt.Errorf("wrong LastBlockID: %w", err)
  346. }
  347. if err := ValidateHash(h.LastCommitHash); err != nil {
  348. return fmt.Errorf("wrong LastCommitHash: %v", err)
  349. }
  350. if err := ValidateHash(h.DataHash); err != nil {
  351. return fmt.Errorf("wrong DataHash: %v", err)
  352. }
  353. if err := ValidateHash(h.EvidenceHash); err != nil {
  354. return fmt.Errorf("wrong EvidenceHash: %v", err)
  355. }
  356. if len(h.ProposerAddress) != crypto.AddressSize {
  357. return fmt.Errorf(
  358. "invalid ProposerAddress length; got: %d, expected: %d",
  359. len(h.ProposerAddress), crypto.AddressSize,
  360. )
  361. }
  362. // Basic validation of hashes related to application data.
  363. // Will validate fully against state in state#ValidateBlock.
  364. if err := ValidateHash(h.ValidatorsHash); err != nil {
  365. return fmt.Errorf("wrong ValidatorsHash: %v", err)
  366. }
  367. if err := ValidateHash(h.NextValidatorsHash); err != nil {
  368. return fmt.Errorf("wrong NextValidatorsHash: %v", err)
  369. }
  370. if err := ValidateHash(h.ConsensusHash); err != nil {
  371. return fmt.Errorf("wrong ConsensusHash: %v", err)
  372. }
  373. // NOTE: AppHash is arbitrary length
  374. if err := ValidateHash(h.LastResultsHash); err != nil {
  375. return fmt.Errorf("wrong LastResultsHash: %v", err)
  376. }
  377. return nil
  378. }
  379. // Hash returns the hash of the header.
  380. // It computes a Merkle tree from the header fields
  381. // ordered as they appear in the Header.
  382. // Returns nil if ValidatorHash is missing,
  383. // since a Header is not valid unless there is
  384. // a ValidatorsHash (corresponding to the validator set).
  385. func (h *Header) Hash() tmbytes.HexBytes {
  386. if h == nil || len(h.ValidatorsHash) == 0 {
  387. return nil
  388. }
  389. hbz, err := h.Version.Marshal()
  390. if err != nil {
  391. return nil
  392. }
  393. pbt, err := gogotypes.StdTimeMarshal(h.Time)
  394. if err != nil {
  395. return nil
  396. }
  397. pbbi := h.LastBlockID.ToProto()
  398. bzbi, err := pbbi.Marshal()
  399. if err != nil {
  400. return nil
  401. }
  402. return merkle.HashFromByteSlices([][]byte{
  403. hbz,
  404. cdcEncode(h.ChainID),
  405. cdcEncode(h.Height),
  406. pbt,
  407. bzbi,
  408. cdcEncode(h.LastCommitHash),
  409. cdcEncode(h.DataHash),
  410. cdcEncode(h.ValidatorsHash),
  411. cdcEncode(h.NextValidatorsHash),
  412. cdcEncode(h.ConsensusHash),
  413. cdcEncode(h.AppHash),
  414. cdcEncode(h.LastResultsHash),
  415. cdcEncode(h.EvidenceHash),
  416. cdcEncode(h.ProposerAddress),
  417. })
  418. }
  419. // StringIndented returns an indented string representation of the header.
  420. func (h *Header) StringIndented(indent string) string {
  421. if h == nil {
  422. return "nil-Header"
  423. }
  424. return fmt.Sprintf(`Header{
  425. %s Version: %v
  426. %s ChainID: %v
  427. %s Height: %v
  428. %s Time: %v
  429. %s LastBlockID: %v
  430. %s LastCommit: %v
  431. %s Data: %v
  432. %s Validators: %v
  433. %s NextValidators: %v
  434. %s App: %v
  435. %s Consensus: %v
  436. %s Results: %v
  437. %s Evidence: %v
  438. %s Proposer: %v
  439. %s}#%v`,
  440. indent, h.Version,
  441. indent, h.ChainID,
  442. indent, h.Height,
  443. indent, h.Time,
  444. indent, h.LastBlockID,
  445. indent, h.LastCommitHash,
  446. indent, h.DataHash,
  447. indent, h.ValidatorsHash,
  448. indent, h.NextValidatorsHash,
  449. indent, h.AppHash,
  450. indent, h.ConsensusHash,
  451. indent, h.LastResultsHash,
  452. indent, h.EvidenceHash,
  453. indent, h.ProposerAddress,
  454. indent, h.Hash())
  455. }
  456. // ToProto converts Header to protobuf
  457. func (h *Header) ToProto() *tmproto.Header {
  458. if h == nil {
  459. return nil
  460. }
  461. return &tmproto.Header{
  462. Version: h.Version,
  463. ChainID: h.ChainID,
  464. Height: h.Height,
  465. Time: h.Time,
  466. LastBlockId: h.LastBlockID.ToProto(),
  467. ValidatorsHash: h.ValidatorsHash,
  468. NextValidatorsHash: h.NextValidatorsHash,
  469. ConsensusHash: h.ConsensusHash,
  470. AppHash: h.AppHash,
  471. DataHash: h.DataHash,
  472. EvidenceHash: h.EvidenceHash,
  473. LastResultsHash: h.LastResultsHash,
  474. LastCommitHash: h.LastCommitHash,
  475. ProposerAddress: h.ProposerAddress,
  476. }
  477. }
  478. // FromProto sets a protobuf Header to the given pointer.
  479. // It returns an error if the header is invalid.
  480. func HeaderFromProto(ph *tmproto.Header) (Header, error) {
  481. if ph == nil {
  482. return Header{}, errors.New("nil Header")
  483. }
  484. h := new(Header)
  485. bi, err := BlockIDFromProto(&ph.LastBlockId)
  486. if err != nil {
  487. return Header{}, err
  488. }
  489. h.Version = ph.Version
  490. h.ChainID = ph.ChainID
  491. h.Height = ph.Height
  492. h.Time = ph.Time
  493. h.Height = ph.Height
  494. h.LastBlockID = *bi
  495. h.ValidatorsHash = ph.ValidatorsHash
  496. h.NextValidatorsHash = ph.NextValidatorsHash
  497. h.ConsensusHash = ph.ConsensusHash
  498. h.AppHash = ph.AppHash
  499. h.DataHash = ph.DataHash
  500. h.EvidenceHash = ph.EvidenceHash
  501. h.LastResultsHash = ph.LastResultsHash
  502. h.LastCommitHash = ph.LastCommitHash
  503. h.ProposerAddress = ph.ProposerAddress
  504. return *h, h.ValidateBasic()
  505. }
  506. //-------------------------------------
  507. // BlockIDFlag indicates which BlockID the signature is for.
  508. type BlockIDFlag byte
  509. const (
  510. // BlockIDFlagAbsent - no vote was received from a validator.
  511. BlockIDFlagAbsent BlockIDFlag = iota + 1
  512. // BlockIDFlagCommit - voted for the Commit.BlockID.
  513. BlockIDFlagCommit
  514. // BlockIDFlagNil - voted for nil.
  515. BlockIDFlagNil
  516. )
  517. // CommitSig is a part of the Vote included in a Commit.
  518. type CommitSig struct {
  519. BlockIDFlag BlockIDFlag `json:"block_id_flag"`
  520. ValidatorAddress Address `json:"validator_address"`
  521. Timestamp time.Time `json:"timestamp"`
  522. Signature []byte `json:"signature"`
  523. }
  524. // NewCommitSigForBlock returns new CommitSig with BlockIDFlagCommit.
  525. func NewCommitSigForBlock(signature []byte, valAddr Address, ts time.Time) CommitSig {
  526. return CommitSig{
  527. BlockIDFlag: BlockIDFlagCommit,
  528. ValidatorAddress: valAddr,
  529. Timestamp: ts,
  530. Signature: signature,
  531. }
  532. }
  533. // ForBlock returns true if CommitSig is for the block.
  534. func (cs CommitSig) ForBlock() bool {
  535. return cs.BlockIDFlag == BlockIDFlagCommit
  536. }
  537. // NewCommitSigAbsent returns new CommitSig with BlockIDFlagAbsent. Other
  538. // fields are all empty.
  539. func NewCommitSigAbsent() CommitSig {
  540. return CommitSig{
  541. BlockIDFlag: BlockIDFlagAbsent,
  542. }
  543. }
  544. // Absent returns true if CommitSig is absent.
  545. func (cs CommitSig) Absent() bool {
  546. return cs.BlockIDFlag == BlockIDFlagAbsent
  547. }
  548. // CommitSig returns a string representation of CommitSig.
  549. //
  550. // 1. first 6 bytes of signature
  551. // 2. first 6 bytes of validator address
  552. // 3. block ID flag
  553. // 4. timestamp
  554. func (cs CommitSig) String() string {
  555. return fmt.Sprintf("CommitSig{%X by %X on %v @ %s}",
  556. tmbytes.Fingerprint(cs.Signature),
  557. tmbytes.Fingerprint(cs.ValidatorAddress),
  558. cs.BlockIDFlag,
  559. CanonicalTime(cs.Timestamp))
  560. }
  561. // BlockID returns the Commit's BlockID if CommitSig indicates signing,
  562. // otherwise - empty BlockID.
  563. func (cs CommitSig) BlockID(commitBlockID BlockID) BlockID {
  564. var blockID BlockID
  565. switch cs.BlockIDFlag {
  566. case BlockIDFlagAbsent:
  567. blockID = BlockID{}
  568. case BlockIDFlagCommit:
  569. blockID = commitBlockID
  570. case BlockIDFlagNil:
  571. blockID = BlockID{}
  572. default:
  573. panic(fmt.Sprintf("Unknown BlockIDFlag: %v", cs.BlockIDFlag))
  574. }
  575. return blockID
  576. }
  577. // ValidateBasic performs basic validation.
  578. func (cs CommitSig) ValidateBasic() error {
  579. switch cs.BlockIDFlag {
  580. case BlockIDFlagAbsent:
  581. case BlockIDFlagCommit:
  582. case BlockIDFlagNil:
  583. default:
  584. return fmt.Errorf("unknown BlockIDFlag: %v", cs.BlockIDFlag)
  585. }
  586. switch cs.BlockIDFlag {
  587. case BlockIDFlagAbsent:
  588. if len(cs.ValidatorAddress) != 0 {
  589. return errors.New("validator address is present")
  590. }
  591. if !cs.Timestamp.IsZero() {
  592. return errors.New("time is present")
  593. }
  594. if len(cs.Signature) != 0 {
  595. return errors.New("signature is present")
  596. }
  597. default:
  598. if len(cs.ValidatorAddress) != crypto.AddressSize {
  599. return fmt.Errorf("expected ValidatorAddress size to be %d bytes, got %d bytes",
  600. crypto.AddressSize,
  601. len(cs.ValidatorAddress),
  602. )
  603. }
  604. // NOTE: Timestamp validation is subtle and handled elsewhere.
  605. if len(cs.Signature) == 0 {
  606. return errors.New("signature is missing")
  607. }
  608. if len(cs.Signature) > MaxSignatureSize {
  609. return fmt.Errorf("signature is too big (max: %d)", MaxSignatureSize)
  610. }
  611. }
  612. return nil
  613. }
  614. // ToProto converts CommitSig to protobuf
  615. func (cs *CommitSig) ToProto() *tmproto.CommitSig {
  616. if cs == nil {
  617. return nil
  618. }
  619. return &tmproto.CommitSig{
  620. BlockIdFlag: tmproto.BlockIDFlag(cs.BlockIDFlag),
  621. ValidatorAddress: cs.ValidatorAddress,
  622. Timestamp: cs.Timestamp,
  623. Signature: cs.Signature,
  624. }
  625. }
  626. // FromProto sets a protobuf CommitSig to the given pointer.
  627. // It returns an error if the CommitSig is invalid.
  628. func (cs *CommitSig) FromProto(csp tmproto.CommitSig) error {
  629. cs.BlockIDFlag = BlockIDFlag(csp.BlockIdFlag)
  630. cs.ValidatorAddress = csp.ValidatorAddress
  631. cs.Timestamp = csp.Timestamp
  632. cs.Signature = csp.Signature
  633. return cs.ValidateBasic()
  634. }
  635. //-------------------------------------
  636. // Commit contains the evidence that a block was committed by a set of validators.
  637. // NOTE: Commit is empty for height 1, but never nil.
  638. type Commit struct {
  639. // NOTE: The signatures are in order of address to preserve the bonded
  640. // ValidatorSet order.
  641. // Any peer with a block can gossip signatures by index with a peer without
  642. // recalculating the active ValidatorSet.
  643. Height int64 `json:"height"`
  644. Round int32 `json:"round"`
  645. BlockID BlockID `json:"block_id"`
  646. Signatures []CommitSig `json:"signatures"`
  647. // Memoized in first call to corresponding method.
  648. // NOTE: can't memoize in constructor because constructor isn't used for
  649. // unmarshaling.
  650. hash tmbytes.HexBytes
  651. bitArray *bits.BitArray
  652. }
  653. // NewCommit returns a new Commit.
  654. func NewCommit(height int64, round int32, blockID BlockID, commitSigs []CommitSig) *Commit {
  655. return &Commit{
  656. Height: height,
  657. Round: round,
  658. BlockID: blockID,
  659. Signatures: commitSigs,
  660. }
  661. }
  662. // CommitToVoteSet constructs a VoteSet from the Commit and validator set.
  663. // Panics if signatures from the commit can't be added to the voteset.
  664. // Inverse of VoteSet.MakeCommit().
  665. func CommitToVoteSet(chainID string, commit *Commit, vals *ValidatorSet) *VoteSet {
  666. voteSet := NewVoteSet(chainID, commit.Height, commit.Round, tmproto.PrecommitType, vals)
  667. for idx, commitSig := range commit.Signatures {
  668. if commitSig.Absent() {
  669. continue // OK, some precommits can be missing.
  670. }
  671. added, err := voteSet.AddVote(commit.GetVote(int32(idx)))
  672. if !added || err != nil {
  673. panic(fmt.Sprintf("Failed to reconstruct LastCommit: %v", err))
  674. }
  675. }
  676. return voteSet
  677. }
  678. // GetVote converts the CommitSig for the given valIdx to a Vote.
  679. // Returns nil if the precommit at valIdx is nil.
  680. // Panics if valIdx >= commit.Size().
  681. func (commit *Commit) GetVote(valIdx int32) *Vote {
  682. commitSig := commit.Signatures[valIdx]
  683. return &Vote{
  684. Type: tmproto.PrecommitType,
  685. Height: commit.Height,
  686. Round: commit.Round,
  687. BlockID: commitSig.BlockID(commit.BlockID),
  688. Timestamp: commitSig.Timestamp,
  689. ValidatorAddress: commitSig.ValidatorAddress,
  690. ValidatorIndex: valIdx,
  691. Signature: commitSig.Signature,
  692. }
  693. }
  694. // VoteSignBytes returns the bytes of the Vote corresponding to valIdx for
  695. // signing.
  696. //
  697. // The only unique part is the Timestamp - all other fields signed over are
  698. // otherwise the same for all validators.
  699. //
  700. // Panics if valIdx >= commit.Size().
  701. //
  702. // See VoteSignBytes
  703. func (commit *Commit) VoteSignBytes(chainID string, valIdx int32) []byte {
  704. v := commit.GetVote(valIdx).ToProto()
  705. return VoteSignBytes(chainID, v)
  706. }
  707. // Type returns the vote type of the commit, which is always VoteTypePrecommit
  708. // Implements VoteSetReader.
  709. func (commit *Commit) Type() byte {
  710. return byte(tmproto.PrecommitType)
  711. }
  712. // GetHeight returns height of the commit.
  713. // Implements VoteSetReader.
  714. func (commit *Commit) GetHeight() int64 {
  715. return commit.Height
  716. }
  717. // GetRound returns height of the commit.
  718. // Implements VoteSetReader.
  719. func (commit *Commit) GetRound() int32 {
  720. return commit.Round
  721. }
  722. // Size returns the number of signatures in the commit.
  723. // Implements VoteSetReader.
  724. func (commit *Commit) Size() int {
  725. if commit == nil {
  726. return 0
  727. }
  728. return len(commit.Signatures)
  729. }
  730. // BitArray returns a BitArray of which validators voted for BlockID or nil in this commit.
  731. // Implements VoteSetReader.
  732. func (commit *Commit) BitArray() *bits.BitArray {
  733. if commit.bitArray == nil {
  734. commit.bitArray = bits.NewBitArray(len(commit.Signatures))
  735. for i, commitSig := range commit.Signatures {
  736. // TODO: need to check the BlockID otherwise we could be counting conflicts,
  737. // not just the one with +2/3 !
  738. commit.bitArray.SetIndex(i, !commitSig.Absent())
  739. }
  740. }
  741. return commit.bitArray
  742. }
  743. // GetByIndex returns the vote corresponding to a given validator index.
  744. // Panics if `index >= commit.Size()`.
  745. // Implements VoteSetReader.
  746. func (commit *Commit) GetByIndex(valIdx int32) *Vote {
  747. return commit.GetVote(valIdx)
  748. }
  749. // IsCommit returns true if there is at least one signature.
  750. // Implements VoteSetReader.
  751. func (commit *Commit) IsCommit() bool {
  752. return len(commit.Signatures) != 0
  753. }
  754. // ValidateBasic performs basic validation that doesn't involve state data.
  755. // Does not actually check the cryptographic signatures.
  756. func (commit *Commit) ValidateBasic() error {
  757. if commit.Height < 0 {
  758. return errors.New("negative Height")
  759. }
  760. if commit.Round < 0 {
  761. return errors.New("negative Round")
  762. }
  763. if commit.Height >= 1 {
  764. if commit.BlockID.IsZero() {
  765. return errors.New("commit cannot be for nil block")
  766. }
  767. if len(commit.Signatures) == 0 {
  768. return errors.New("no signatures in commit")
  769. }
  770. for i, commitSig := range commit.Signatures {
  771. if err := commitSig.ValidateBasic(); err != nil {
  772. return fmt.Errorf("wrong CommitSig #%d: %v", i, err)
  773. }
  774. }
  775. }
  776. return nil
  777. }
  778. // Hash returns the hash of the commit
  779. func (commit *Commit) Hash() tmbytes.HexBytes {
  780. if commit == nil {
  781. return nil
  782. }
  783. if commit.hash == nil {
  784. bs := make([][]byte, len(commit.Signatures))
  785. for i, commitSig := range commit.Signatures {
  786. pbcs := commitSig.ToProto()
  787. bz, err := pbcs.Marshal()
  788. if err != nil {
  789. panic(err)
  790. }
  791. bs[i] = bz
  792. }
  793. commit.hash = merkle.HashFromByteSlices(bs)
  794. }
  795. return commit.hash
  796. }
  797. // StringIndented returns a string representation of the commit.
  798. func (commit *Commit) StringIndented(indent string) string {
  799. if commit == nil {
  800. return "nil-Commit"
  801. }
  802. commitSigStrings := make([]string, len(commit.Signatures))
  803. for i, commitSig := range commit.Signatures {
  804. commitSigStrings[i] = commitSig.String()
  805. }
  806. return fmt.Sprintf(`Commit{
  807. %s Height: %d
  808. %s Round: %d
  809. %s BlockID: %v
  810. %s Signatures:
  811. %s %v
  812. %s}#%v`,
  813. indent, commit.Height,
  814. indent, commit.Round,
  815. indent, commit.BlockID,
  816. indent,
  817. indent, strings.Join(commitSigStrings, "\n"+indent+" "),
  818. indent, commit.hash)
  819. }
  820. // ToProto converts Commit to protobuf
  821. func (commit *Commit) ToProto() *tmproto.Commit {
  822. if commit == nil {
  823. return nil
  824. }
  825. c := new(tmproto.Commit)
  826. sigs := make([]tmproto.CommitSig, len(commit.Signatures))
  827. for i := range commit.Signatures {
  828. sigs[i] = *commit.Signatures[i].ToProto()
  829. }
  830. c.Signatures = sigs
  831. c.Height = commit.Height
  832. c.Round = commit.Round
  833. c.BlockID = commit.BlockID.ToProto()
  834. if commit.hash != nil {
  835. c.Hash = commit.hash
  836. }
  837. c.BitArray = commit.bitArray.ToProto()
  838. return c
  839. }
  840. // FromProto sets a protobuf Commit to the given pointer.
  841. // It returns an error if the commit is invalid.
  842. func CommitFromProto(cp *tmproto.Commit) (*Commit, error) {
  843. if cp == nil {
  844. return nil, errors.New("nil Commit")
  845. }
  846. var (
  847. commit = new(Commit)
  848. bitArray *bits.BitArray
  849. )
  850. bi, err := BlockIDFromProto(&cp.BlockID)
  851. if err != nil {
  852. return nil, err
  853. }
  854. bitArray.FromProto(cp.BitArray)
  855. sigs := make([]CommitSig, len(cp.Signatures))
  856. for i := range cp.Signatures {
  857. if err := sigs[i].FromProto(cp.Signatures[i]); err != nil {
  858. return nil, err
  859. }
  860. }
  861. commit.Signatures = sigs
  862. commit.Height = cp.Height
  863. commit.Round = cp.Round
  864. commit.BlockID = *bi
  865. commit.hash = cp.Hash
  866. commit.bitArray = bitArray
  867. return commit, commit.ValidateBasic()
  868. }
  869. //-----------------------------------------------------------------------------
  870. // SignedHeader is a header along with the commits that prove it.
  871. // It is the basis of the light client.
  872. type SignedHeader struct {
  873. *Header `json:"header"`
  874. Commit *Commit `json:"commit"`
  875. }
  876. // ValidateBasic does basic consistency checks and makes sure the header
  877. // and commit are consistent.
  878. //
  879. // NOTE: This does not actually check the cryptographic signatures. Make sure
  880. // to use a Verifier to validate the signatures actually provide a
  881. // significantly strong proof for this header's validity.
  882. func (sh SignedHeader) ValidateBasic(chainID string) error {
  883. if sh.Header == nil {
  884. return errors.New("missing header")
  885. }
  886. if sh.Commit == nil {
  887. return errors.New("missing commit")
  888. }
  889. if err := sh.Header.ValidateBasic(); err != nil {
  890. return fmt.Errorf("invalid header: %w", err)
  891. }
  892. if err := sh.Commit.ValidateBasic(); err != nil {
  893. return fmt.Errorf("invalid commit: %w", err)
  894. }
  895. if sh.ChainID != chainID {
  896. return fmt.Errorf("header belongs to another chain %q, not %q", sh.ChainID, chainID)
  897. }
  898. // Make sure the header is consistent with the commit.
  899. if sh.Commit.Height != sh.Height {
  900. return fmt.Errorf("header and commit height mismatch: %d vs %d", sh.Height, sh.Commit.Height)
  901. }
  902. if hhash, chash := sh.Hash(), sh.Commit.BlockID.Hash; !bytes.Equal(hhash, chash) {
  903. return fmt.Errorf("commit signs block %X, header is block %X", chash, hhash)
  904. }
  905. return nil
  906. }
  907. // String returns a string representation of SignedHeader.
  908. func (sh SignedHeader) String() string {
  909. return sh.StringIndented("")
  910. }
  911. // StringIndented returns an indented string representation of SignedHeader.
  912. //
  913. // Header
  914. // Commit
  915. func (sh SignedHeader) StringIndented(indent string) string {
  916. return fmt.Sprintf(`SignedHeader{
  917. %s %v
  918. %s %v
  919. %s}`,
  920. indent, sh.Header.StringIndented(indent+" "),
  921. indent, sh.Commit.StringIndented(indent+" "),
  922. indent)
  923. }
  924. // ToProto converts SignedHeader to protobuf
  925. func (sh *SignedHeader) ToProto() *tmproto.SignedHeader {
  926. if sh == nil {
  927. return nil
  928. }
  929. psh := new(tmproto.SignedHeader)
  930. if sh.Header != nil {
  931. psh.Header = sh.Header.ToProto()
  932. }
  933. if sh.Commit != nil {
  934. psh.Commit = sh.Commit.ToProto()
  935. }
  936. return psh
  937. }
  938. // FromProto sets a protobuf SignedHeader to the given pointer.
  939. // It returns an error if the hader or the commit is invalid.
  940. func SignedHeaderFromProto(shp *tmproto.SignedHeader) (*SignedHeader, error) {
  941. if shp == nil {
  942. return nil, errors.New("nil SignedHeader")
  943. }
  944. sh := new(SignedHeader)
  945. if shp.Header != nil {
  946. h, err := HeaderFromProto(shp.Header)
  947. if err != nil {
  948. return nil, err
  949. }
  950. sh.Header = &h
  951. }
  952. if shp.Commit != nil {
  953. c, err := CommitFromProto(shp.Commit)
  954. if err != nil {
  955. return nil, err
  956. }
  957. sh.Commit = c
  958. }
  959. return sh, nil
  960. }
  961. //-----------------------------------------------------------------------------
  962. // Data contains the set of transactions included in the block
  963. type Data struct {
  964. // Txs that will be applied by state @ block.Height+1.
  965. // NOTE: not all txs here are valid. We're just agreeing on the order first.
  966. // This means that block.AppHash does not include these txs.
  967. Txs Txs `json:"txs"`
  968. // Volatile
  969. hash tmbytes.HexBytes
  970. }
  971. // Hash returns the hash of the data
  972. func (data *Data) Hash() tmbytes.HexBytes {
  973. if data == nil {
  974. return (Txs{}).Hash()
  975. }
  976. if data.hash == nil {
  977. data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs
  978. }
  979. return data.hash
  980. }
  981. // StringIndented returns an indented string representation of the transactions.
  982. func (data *Data) StringIndented(indent string) string {
  983. if data == nil {
  984. return "nil-Data"
  985. }
  986. txStrings := make([]string, tmmath.MinInt(len(data.Txs), 21))
  987. for i, tx := range data.Txs {
  988. if i == 20 {
  989. txStrings[i] = fmt.Sprintf("... (%v total)", len(data.Txs))
  990. break
  991. }
  992. txStrings[i] = fmt.Sprintf("%X (%d bytes)", tx.Hash(), len(tx))
  993. }
  994. return fmt.Sprintf(`Data{
  995. %s %v
  996. %s}#%v`,
  997. indent, strings.Join(txStrings, "\n"+indent+" "),
  998. indent, data.hash)
  999. }
  1000. // ToProto converts Data to protobuf
  1001. func (data *Data) ToProto() tmproto.Data {
  1002. tp := new(tmproto.Data)
  1003. if len(data.Txs) > 0 {
  1004. txBzs := make([][]byte, len(data.Txs))
  1005. for i := range data.Txs {
  1006. txBzs[i] = data.Txs[i]
  1007. }
  1008. tp.Txs = txBzs
  1009. }
  1010. if data.hash != nil {
  1011. tp.Hash = data.hash
  1012. }
  1013. return *tp
  1014. }
  1015. // DataFromProto takes a protobuf representation of Data &
  1016. // returns the native type.
  1017. func DataFromProto(dp *tmproto.Data) (Data, error) {
  1018. if dp == nil {
  1019. return Data{}, errors.New("nil data")
  1020. }
  1021. data := new(Data)
  1022. if len(dp.Txs) > 0 {
  1023. txBzs := make(Txs, len(dp.Txs))
  1024. for i := range dp.Txs {
  1025. txBzs[i] = Tx(dp.Txs[i])
  1026. }
  1027. data.Txs = txBzs
  1028. } else {
  1029. data.Txs = Txs{}
  1030. }
  1031. data.hash = dp.Hash
  1032. return *data, nil
  1033. }
  1034. //-----------------------------------------------------------------------------
  1035. // EvidenceData contains any evidence of malicious wrong-doing by validators
  1036. type EvidenceData struct {
  1037. Evidence EvidenceList `json:"evidence"`
  1038. // Volatile
  1039. hash tmbytes.HexBytes
  1040. }
  1041. // Hash returns the hash of the data.
  1042. func (data *EvidenceData) Hash() tmbytes.HexBytes {
  1043. if data.hash == nil {
  1044. data.hash = data.Evidence.Hash()
  1045. }
  1046. return data.hash
  1047. }
  1048. // StringIndented returns a string representation of the evidence.
  1049. func (data *EvidenceData) StringIndented(indent string) string {
  1050. if data == nil {
  1051. return "nil-Evidence"
  1052. }
  1053. evStrings := make([]string, tmmath.MinInt(len(data.Evidence), 21))
  1054. for i, ev := range data.Evidence {
  1055. if i == 20 {
  1056. evStrings[i] = fmt.Sprintf("... (%v total)", len(data.Evidence))
  1057. break
  1058. }
  1059. evStrings[i] = fmt.Sprintf("Evidence:%v", ev)
  1060. }
  1061. return fmt.Sprintf(`EvidenceData{
  1062. %s %v
  1063. %s}#%v`,
  1064. indent, strings.Join(evStrings, "\n"+indent+" "),
  1065. indent, data.hash)
  1066. }
  1067. // ToProto converts EvidenceData to protobuf
  1068. func (data *EvidenceData) ToProto() (*tmproto.EvidenceData, error) {
  1069. if data == nil {
  1070. return nil, errors.New("nil evidence data")
  1071. }
  1072. evi := new(tmproto.EvidenceData)
  1073. eviBzs := make([]tmproto.Evidence, len(data.Evidence))
  1074. for i := range data.Evidence {
  1075. protoEvi, err := EvidenceToProto(data.Evidence[i])
  1076. if err != nil {
  1077. return nil, err
  1078. }
  1079. eviBzs[i] = *protoEvi
  1080. }
  1081. evi.Evidence = eviBzs
  1082. if data.hash != nil {
  1083. evi.Hash = data.hash
  1084. }
  1085. return evi, nil
  1086. }
  1087. // FromProto sets a protobuf EvidenceData to the given pointer.
  1088. func (data *EvidenceData) FromProto(eviData *tmproto.EvidenceData) error {
  1089. if eviData == nil {
  1090. return errors.New("nil evidenceData")
  1091. }
  1092. eviBzs := make(EvidenceList, len(eviData.Evidence))
  1093. for i := range eviData.Evidence {
  1094. evi, err := EvidenceFromProto(&eviData.Evidence[i])
  1095. if err != nil {
  1096. return err
  1097. }
  1098. eviBzs[i] = evi
  1099. }
  1100. data.Evidence = eviBzs
  1101. data.hash = eviData.GetHash()
  1102. return nil
  1103. }
  1104. //--------------------------------------------------------------------------------
  1105. // BlockID
  1106. type BlockID struct {
  1107. Hash tmbytes.HexBytes `json:"hash"`
  1108. PartSetHeader PartSetHeader `json:"parts"`
  1109. }
  1110. // Equals returns true if the BlockID matches the given BlockID
  1111. func (blockID BlockID) Equals(other BlockID) bool {
  1112. return bytes.Equal(blockID.Hash, other.Hash) &&
  1113. blockID.PartSetHeader.Equals(other.PartSetHeader)
  1114. }
  1115. // Key returns a machine-readable string representation of the BlockID
  1116. func (blockID BlockID) Key() string {
  1117. pbph := blockID.PartSetHeader.ToProto()
  1118. bz, err := pbph.Marshal()
  1119. if err != nil {
  1120. panic(err)
  1121. }
  1122. return string(blockID.Hash) + string(bz)
  1123. }
  1124. // ValidateBasic performs basic validation.
  1125. func (blockID BlockID) ValidateBasic() error {
  1126. // Hash can be empty in case of POLBlockID in Proposal.
  1127. if err := ValidateHash(blockID.Hash); err != nil {
  1128. return fmt.Errorf("wrong Hash")
  1129. }
  1130. if err := blockID.PartSetHeader.ValidateBasic(); err != nil {
  1131. return fmt.Errorf("wrong PartSetHeader: %v", err)
  1132. }
  1133. return nil
  1134. }
  1135. // IsZero returns true if this is the BlockID of a nil block.
  1136. func (blockID BlockID) IsZero() bool {
  1137. return len(blockID.Hash) == 0 &&
  1138. blockID.PartSetHeader.IsZero()
  1139. }
  1140. // IsComplete returns true if this is a valid BlockID of a non-nil block.
  1141. func (blockID BlockID) IsComplete() bool {
  1142. return len(blockID.Hash) == tmhash.Size &&
  1143. blockID.PartSetHeader.Total > 0 &&
  1144. len(blockID.PartSetHeader.Hash) == tmhash.Size
  1145. }
  1146. // String returns a human readable string representation of the BlockID.
  1147. //
  1148. // 1. hash
  1149. // 2. part set header
  1150. //
  1151. // See PartSetHeader#String
  1152. func (blockID BlockID) String() string {
  1153. return fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartSetHeader)
  1154. }
  1155. // ToProto converts BlockID to protobuf
  1156. func (blockID *BlockID) ToProto() tmproto.BlockID {
  1157. if blockID == nil {
  1158. return tmproto.BlockID{}
  1159. }
  1160. return tmproto.BlockID{
  1161. Hash: blockID.Hash,
  1162. PartSetHeader: blockID.PartSetHeader.ToProto(),
  1163. }
  1164. }
  1165. // FromProto sets a protobuf BlockID to the given pointer.
  1166. // It returns an error if the block id is invalid.
  1167. func BlockIDFromProto(bID *tmproto.BlockID) (*BlockID, error) {
  1168. if bID == nil {
  1169. return nil, errors.New("nil BlockID")
  1170. }
  1171. blockID := new(BlockID)
  1172. ph, err := PartSetHeaderFromProto(&bID.PartSetHeader)
  1173. if err != nil {
  1174. return nil, err
  1175. }
  1176. blockID.PartSetHeader = *ph
  1177. blockID.Hash = bID.Hash
  1178. return blockID, blockID.ValidateBasic()
  1179. }