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.

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