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.

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