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.

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