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.

1175 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/spec/blob/master/spec/blockchain/blockchain.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. // ToProto converts Header to protobuf
  460. func (h *Header) ToProto() *tmproto.Header {
  461. if h == nil {
  462. return nil
  463. }
  464. return &tmproto.Header{
  465. Version: h.Version.ToProto(),
  466. ChainID: h.ChainID,
  467. Height: h.Height,
  468. Time: h.Time,
  469. LastBlockId: h.LastBlockID.ToProto(),
  470. ValidatorsHash: h.ValidatorsHash,
  471. NextValidatorsHash: h.NextValidatorsHash,
  472. ConsensusHash: h.ConsensusHash,
  473. AppHash: h.AppHash,
  474. DataHash: h.DataHash,
  475. EvidenceHash: h.EvidenceHash,
  476. LastResultsHash: h.LastResultsHash,
  477. LastCommitHash: h.LastCommitHash,
  478. ProposerAddress: h.ProposerAddress,
  479. }
  480. }
  481. // FromProto sets a protobuf Header to the given pointer.
  482. // It returns an error if the header is invalid.
  483. func HeaderFromProto(ph *tmproto.Header) (Header, error) {
  484. if ph == nil {
  485. return Header{}, errors.New("nil Header")
  486. }
  487. h := new(Header)
  488. bi, err := BlockIDFromProto(&ph.LastBlockId)
  489. if err != nil {
  490. return Header{}, err
  491. }
  492. h.Version = version.Consensus{Block: ph.Version.Block, App: ph.Version.App}
  493. h.ChainID = ph.ChainID
  494. h.Height = ph.Height
  495. h.Time = ph.Time
  496. h.Height = ph.Height
  497. h.LastBlockID = *bi
  498. h.ValidatorsHash = ph.ValidatorsHash
  499. h.NextValidatorsHash = ph.NextValidatorsHash
  500. h.ConsensusHash = ph.ConsensusHash
  501. h.AppHash = ph.AppHash
  502. h.DataHash = ph.DataHash
  503. h.EvidenceHash = ph.EvidenceHash
  504. h.LastResultsHash = ph.LastResultsHash
  505. h.LastCommitHash = ph.LastCommitHash
  506. h.ProposerAddress = ph.ProposerAddress
  507. return *h, h.ValidateBasic()
  508. }
  509. //-------------------------------------
  510. // BlockIDFlag indicates which BlockID the signature is for.
  511. type BlockIDFlag byte
  512. const (
  513. // BlockIDFlagAbsent - no vote was received from a validator.
  514. BlockIDFlagAbsent BlockIDFlag = iota + 1
  515. // BlockIDFlagCommit - voted for the Commit.BlockID.
  516. BlockIDFlagCommit
  517. // BlockIDFlagNil - voted for nil.
  518. BlockIDFlagNil
  519. )
  520. const (
  521. // Max size of commit without any commitSigs -> 82 for BlockID, 8 for Height, 4 for Round.
  522. MaxCommitOverheadBytes int64 = 94
  523. // Commit sig size is made up of 64 bytes for the signature, 20 bytes for the address,
  524. // 1 byte for the flag and 14 bytes for the timestamp
  525. MaxCommitSigBytes int64 = 109
  526. )
  527. // CommitSig is a part of the Vote included in a Commit.
  528. type CommitSig struct {
  529. BlockIDFlag BlockIDFlag `json:"block_id_flag"`
  530. ValidatorAddress Address `json:"validator_address"`
  531. Timestamp time.Time `json:"timestamp"`
  532. Signature []byte `json:"signature"`
  533. VoteExtension VoteExtensionToSign `json:"vote_extension"`
  534. }
  535. // NewCommitSigForBlock returns new CommitSig with BlockIDFlagCommit.
  536. func NewCommitSigForBlock(signature []byte, valAddr Address, ts time.Time, ext VoteExtensionToSign) CommitSig {
  537. return CommitSig{
  538. BlockIDFlag: BlockIDFlagCommit,
  539. ValidatorAddress: valAddr,
  540. Timestamp: ts,
  541. Signature: signature,
  542. VoteExtension: ext,
  543. }
  544. }
  545. func MaxCommitBytes(valCount int) int64 {
  546. // From the repeated commit sig field
  547. var protoEncodingOverhead int64 = 2
  548. return MaxCommitOverheadBytes + ((MaxCommitSigBytes + protoEncodingOverhead) * int64(valCount))
  549. }
  550. // NewCommitSigAbsent returns new CommitSig with BlockIDFlagAbsent. Other
  551. // fields are all empty.
  552. func NewCommitSigAbsent() CommitSig {
  553. return CommitSig{
  554. BlockIDFlag: BlockIDFlagAbsent,
  555. }
  556. }
  557. // ForBlock returns true if CommitSig is for the block.
  558. func (cs CommitSig) ForBlock() bool {
  559. return cs.BlockIDFlag == BlockIDFlagCommit
  560. }
  561. // Absent returns true if CommitSig is absent.
  562. func (cs CommitSig) Absent() bool {
  563. return cs.BlockIDFlag == BlockIDFlagAbsent
  564. }
  565. // CommitSig returns a string representation of CommitSig.
  566. //
  567. // 1. first 6 bytes of signature
  568. // 2. first 6 bytes of validator address
  569. // 3. block ID flag
  570. // 4. first 6 bytes of the vote extension
  571. // 5. timestamp
  572. func (cs CommitSig) String() string {
  573. return fmt.Sprintf("CommitSig{%X by %X on %v with %X @ %s}",
  574. tmbytes.Fingerprint(cs.Signature),
  575. tmbytes.Fingerprint(cs.ValidatorAddress),
  576. cs.BlockIDFlag,
  577. tmbytes.Fingerprint(cs.VoteExtension.BytesPacked()),
  578. CanonicalTime(cs.Timestamp))
  579. }
  580. // BlockID returns the Commit's BlockID if CommitSig indicates signing,
  581. // otherwise - empty BlockID.
  582. func (cs CommitSig) BlockID(commitBlockID BlockID) BlockID {
  583. var blockID BlockID
  584. switch cs.BlockIDFlag {
  585. case BlockIDFlagAbsent:
  586. blockID = BlockID{}
  587. case BlockIDFlagCommit:
  588. blockID = commitBlockID
  589. case BlockIDFlagNil:
  590. blockID = BlockID{}
  591. default:
  592. panic(fmt.Sprintf("Unknown BlockIDFlag: %v", cs.BlockIDFlag))
  593. }
  594. return blockID
  595. }
  596. // ValidateBasic performs basic validation.
  597. func (cs CommitSig) ValidateBasic() error {
  598. switch cs.BlockIDFlag {
  599. case BlockIDFlagAbsent:
  600. case BlockIDFlagCommit:
  601. case BlockIDFlagNil:
  602. default:
  603. return fmt.Errorf("unknown BlockIDFlag: %v", cs.BlockIDFlag)
  604. }
  605. switch cs.BlockIDFlag {
  606. case BlockIDFlagAbsent:
  607. if len(cs.ValidatorAddress) != 0 {
  608. return errors.New("validator address is present")
  609. }
  610. if !cs.Timestamp.IsZero() {
  611. return errors.New("time is present")
  612. }
  613. if len(cs.Signature) != 0 {
  614. return errors.New("signature is present")
  615. }
  616. default:
  617. if len(cs.ValidatorAddress) != crypto.AddressSize {
  618. return fmt.Errorf("expected ValidatorAddress size to be %d bytes, got %d bytes",
  619. crypto.AddressSize,
  620. len(cs.ValidatorAddress),
  621. )
  622. }
  623. // NOTE: Timestamp validation is subtle and handled elsewhere.
  624. if len(cs.Signature) == 0 {
  625. return errors.New("signature is missing")
  626. }
  627. if len(cs.Signature) > MaxSignatureSize {
  628. return fmt.Errorf("signature is too big (max: %d)", MaxSignatureSize)
  629. }
  630. }
  631. return nil
  632. }
  633. // ToProto converts CommitSig to protobuf
  634. func (cs *CommitSig) ToProto() *tmproto.CommitSig {
  635. if cs == nil {
  636. return nil
  637. }
  638. return &tmproto.CommitSig{
  639. BlockIdFlag: tmproto.BlockIDFlag(cs.BlockIDFlag),
  640. ValidatorAddress: cs.ValidatorAddress,
  641. Timestamp: cs.Timestamp,
  642. Signature: cs.Signature,
  643. VoteExtension: cs.VoteExtension.ToProto(),
  644. }
  645. }
  646. // FromProto sets a protobuf CommitSig to the given pointer.
  647. // It returns an error if the CommitSig is invalid.
  648. func (cs *CommitSig) FromProto(csp tmproto.CommitSig) error {
  649. cs.BlockIDFlag = BlockIDFlag(csp.BlockIdFlag)
  650. cs.ValidatorAddress = csp.ValidatorAddress
  651. cs.Timestamp = csp.Timestamp
  652. cs.Signature = csp.Signature
  653. cs.VoteExtension = VoteExtensionToSignFromProto(csp.VoteExtension)
  654. return cs.ValidateBasic()
  655. }
  656. //-------------------------------------
  657. // Commit contains the evidence that a block was committed by a set of validators.
  658. // NOTE: Commit is empty for height 1, but never nil.
  659. type Commit struct {
  660. // NOTE: The signatures are in order of address to preserve the bonded
  661. // ValidatorSet order.
  662. // Any peer with a block can gossip signatures by index with a peer without
  663. // recalculating the active ValidatorSet.
  664. Height int64 `json:"height,string"`
  665. Round int32 `json:"round"`
  666. BlockID BlockID `json:"block_id"`
  667. Signatures []CommitSig `json:"signatures"`
  668. // Memoized in first call to corresponding method.
  669. // NOTE: can't memoize in constructor because constructor isn't used for
  670. // unmarshaling.
  671. hash tmbytes.HexBytes
  672. bitArray *bits.BitArray
  673. }
  674. // NewCommit returns a new Commit.
  675. func NewCommit(height int64, round int32, blockID BlockID, commitSigs []CommitSig) *Commit {
  676. return &Commit{
  677. Height: height,
  678. Round: round,
  679. BlockID: blockID,
  680. Signatures: commitSigs,
  681. }
  682. }
  683. // CommitToVoteSet constructs a VoteSet from the Commit and validator set.
  684. // Panics if signatures from the commit can't be added to the voteset.
  685. // Inverse of VoteSet.MakeCommit().
  686. func CommitToVoteSet(chainID string, commit *Commit, vals *ValidatorSet) *VoteSet {
  687. voteSet := NewVoteSet(chainID, commit.Height, commit.Round, tmproto.PrecommitType, vals)
  688. for idx, commitSig := range commit.Signatures {
  689. if commitSig.Absent() {
  690. continue // OK, some precommits can be missing.
  691. }
  692. added, err := voteSet.AddVote(commit.GetVote(int32(idx)))
  693. if !added || err != nil {
  694. panic(fmt.Errorf("failed to reconstruct LastCommit: %w", err))
  695. }
  696. }
  697. return voteSet
  698. }
  699. // GetVote converts the CommitSig for the given valIdx to a Vote.
  700. // Returns nil if the precommit at valIdx is nil.
  701. // Panics if valIdx >= commit.Size().
  702. func (commit *Commit) GetVote(valIdx int32) *Vote {
  703. commitSig := commit.Signatures[valIdx]
  704. return &Vote{
  705. Type: tmproto.PrecommitType,
  706. Height: commit.Height,
  707. Round: commit.Round,
  708. BlockID: commitSig.BlockID(commit.BlockID),
  709. Timestamp: commitSig.Timestamp,
  710. ValidatorAddress: commitSig.ValidatorAddress,
  711. ValidatorIndex: valIdx,
  712. Signature: commitSig.Signature,
  713. VoteExtension: commitSig.VoteExtension.ToVoteExtension(),
  714. }
  715. }
  716. // VoteSignBytes returns the bytes of the Vote corresponding to valIdx for
  717. // signing.
  718. //
  719. // The only unique part is the Timestamp - all other fields signed over are
  720. // otherwise the same for all validators.
  721. //
  722. // Panics if valIdx >= commit.Size().
  723. //
  724. // See VoteSignBytes
  725. func (commit *Commit) VoteSignBytes(chainID string, valIdx int32) []byte {
  726. v := commit.GetVote(valIdx).ToProto()
  727. return VoteSignBytes(chainID, v)
  728. }
  729. // Type returns the vote type of the commit, which is always VoteTypePrecommit
  730. // Implements VoteSetReader.
  731. func (commit *Commit) Type() byte {
  732. return byte(tmproto.PrecommitType)
  733. }
  734. // GetHeight returns height of the commit.
  735. // Implements VoteSetReader.
  736. func (commit *Commit) GetHeight() int64 {
  737. return commit.Height
  738. }
  739. // GetRound returns height of the commit.
  740. // Implements VoteSetReader.
  741. func (commit *Commit) GetRound() int32 {
  742. return commit.Round
  743. }
  744. // Size returns the number of signatures in the commit.
  745. // Implements VoteSetReader.
  746. func (commit *Commit) Size() int {
  747. if commit == nil {
  748. return 0
  749. }
  750. return len(commit.Signatures)
  751. }
  752. // BitArray returns a BitArray of which validators voted for BlockID or nil in this commit.
  753. // Implements VoteSetReader.
  754. func (commit *Commit) BitArray() *bits.BitArray {
  755. if commit.bitArray == nil {
  756. commit.bitArray = bits.NewBitArray(len(commit.Signatures))
  757. for i, commitSig := range commit.Signatures {
  758. // TODO: need to check the BlockID otherwise we could be counting conflicts,
  759. // not just the one with +2/3 !
  760. commit.bitArray.SetIndex(i, !commitSig.Absent())
  761. }
  762. }
  763. return commit.bitArray
  764. }
  765. // GetByIndex returns the vote corresponding to a given validator index.
  766. // Panics if `index >= commit.Size()`.
  767. // Implements VoteSetReader.
  768. func (commit *Commit) GetByIndex(valIdx int32) *Vote {
  769. return commit.GetVote(valIdx)
  770. }
  771. // IsCommit returns true if there is at least one signature.
  772. // Implements VoteSetReader.
  773. func (commit *Commit) IsCommit() bool {
  774. return len(commit.Signatures) != 0
  775. }
  776. // ValidateBasic performs basic validation that doesn't involve state data.
  777. // Does not actually check the cryptographic signatures.
  778. func (commit *Commit) ValidateBasic() error {
  779. if commit.Height < 0 {
  780. return errors.New("negative Height")
  781. }
  782. if commit.Round < 0 {
  783. return errors.New("negative Round")
  784. }
  785. if commit.Height >= 1 {
  786. if commit.BlockID.IsNil() {
  787. return errors.New("commit cannot be for nil block")
  788. }
  789. if len(commit.Signatures) == 0 {
  790. return errors.New("no signatures in commit")
  791. }
  792. for i, commitSig := range commit.Signatures {
  793. if err := commitSig.ValidateBasic(); err != nil {
  794. return fmt.Errorf("wrong CommitSig #%d: %v", i, err)
  795. }
  796. }
  797. }
  798. return nil
  799. }
  800. // Hash returns the hash of the commit
  801. func (commit *Commit) Hash() tmbytes.HexBytes {
  802. if commit == nil {
  803. return nil
  804. }
  805. if commit.hash == nil {
  806. bs := make([][]byte, len(commit.Signatures))
  807. for i, commitSig := range commit.Signatures {
  808. pbcs := commitSig.ToProto()
  809. bz, err := pbcs.Marshal()
  810. if err != nil {
  811. panic(err)
  812. }
  813. bs[i] = bz
  814. }
  815. commit.hash = merkle.HashFromByteSlices(bs)
  816. }
  817. return commit.hash
  818. }
  819. // StringIndented returns a string representation of the commit.
  820. func (commit *Commit) StringIndented(indent string) string {
  821. if commit == nil {
  822. return "nil-Commit"
  823. }
  824. commitSigStrings := make([]string, len(commit.Signatures))
  825. for i, commitSig := range commit.Signatures {
  826. commitSigStrings[i] = commitSig.String()
  827. }
  828. return fmt.Sprintf(`Commit{
  829. %s Height: %d
  830. %s Round: %d
  831. %s BlockID: %v
  832. %s Signatures:
  833. %s %v
  834. %s}#%v`,
  835. indent, commit.Height,
  836. indent, commit.Round,
  837. indent, commit.BlockID,
  838. indent,
  839. indent, strings.Join(commitSigStrings, "\n"+indent+" "),
  840. indent, commit.hash)
  841. }
  842. // ToProto converts Commit to protobuf
  843. func (commit *Commit) ToProto() *tmproto.Commit {
  844. if commit == nil {
  845. return nil
  846. }
  847. c := new(tmproto.Commit)
  848. sigs := make([]tmproto.CommitSig, len(commit.Signatures))
  849. for i := range commit.Signatures {
  850. sigs[i] = *commit.Signatures[i].ToProto()
  851. }
  852. c.Signatures = sigs
  853. c.Height = commit.Height
  854. c.Round = commit.Round
  855. c.BlockID = commit.BlockID.ToProto()
  856. return c
  857. }
  858. // FromProto sets a protobuf Commit to the given pointer.
  859. // It returns an error if the commit is invalid.
  860. func CommitFromProto(cp *tmproto.Commit) (*Commit, error) {
  861. if cp == nil {
  862. return nil, errors.New("nil Commit")
  863. }
  864. var (
  865. commit = new(Commit)
  866. )
  867. bi, err := BlockIDFromProto(&cp.BlockID)
  868. if err != nil {
  869. return nil, err
  870. }
  871. sigs := make([]CommitSig, len(cp.Signatures))
  872. for i := range cp.Signatures {
  873. if err := sigs[i].FromProto(cp.Signatures[i]); err != nil {
  874. return nil, err
  875. }
  876. }
  877. commit.Signatures = sigs
  878. commit.Height = cp.Height
  879. commit.Round = cp.Round
  880. commit.BlockID = *bi
  881. return commit, commit.ValidateBasic()
  882. }
  883. //-----------------------------------------------------------------------------
  884. // Data contains the set of transactions included in the block
  885. type Data struct {
  886. // Txs that will be applied by state @ block.Height+1.
  887. // NOTE: not all txs here are valid. We're just agreeing on the order first.
  888. // This means that block.AppHash does not include these txs.
  889. Txs Txs `json:"txs"`
  890. // Volatile
  891. hash tmbytes.HexBytes
  892. }
  893. // Hash returns the hash of the data
  894. func (data *Data) Hash() tmbytes.HexBytes {
  895. if data == nil {
  896. return (Txs{}).Hash()
  897. }
  898. if data.hash == nil {
  899. data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs
  900. }
  901. return data.hash
  902. }
  903. // StringIndented returns an indented string representation of the transactions.
  904. func (data *Data) StringIndented(indent string) string {
  905. if data == nil {
  906. return "nil-Data"
  907. }
  908. txStrings := make([]string, tmmath.MinInt(len(data.Txs), 21))
  909. for i, tx := range data.Txs {
  910. if i == 20 {
  911. txStrings[i] = fmt.Sprintf("... (%v total)", len(data.Txs))
  912. break
  913. }
  914. txStrings[i] = fmt.Sprintf("%X (%d bytes)", tx.Hash(), len(tx))
  915. }
  916. return fmt.Sprintf(`Data{
  917. %s %v
  918. %s}#%v`,
  919. indent, strings.Join(txStrings, "\n"+indent+" "),
  920. indent, data.hash)
  921. }
  922. // ToProto converts Data to protobuf
  923. func (data *Data) ToProto() tmproto.Data {
  924. tp := new(tmproto.Data)
  925. if len(data.Txs) > 0 {
  926. txBzs := make([][]byte, len(data.Txs))
  927. for i := range data.Txs {
  928. txBzs[i] = data.Txs[i]
  929. }
  930. tp.Txs = txBzs
  931. }
  932. return *tp
  933. }
  934. // DataFromProto takes a protobuf representation of Data &
  935. // returns the native type.
  936. func DataFromProto(dp *tmproto.Data) (Data, error) {
  937. if dp == nil {
  938. return Data{}, errors.New("nil data")
  939. }
  940. data := new(Data)
  941. if len(dp.Txs) > 0 {
  942. txBzs := make(Txs, len(dp.Txs))
  943. for i := range dp.Txs {
  944. txBzs[i] = Tx(dp.Txs[i])
  945. }
  946. data.Txs = txBzs
  947. } else {
  948. data.Txs = Txs{}
  949. }
  950. return *data, nil
  951. }
  952. //--------------------------------------------------------------------------------
  953. // BlockID
  954. type BlockID struct {
  955. Hash tmbytes.HexBytes `json:"hash"`
  956. PartSetHeader PartSetHeader `json:"parts"`
  957. }
  958. // Equals returns true if the BlockID matches the given BlockID
  959. func (blockID BlockID) Equals(other BlockID) bool {
  960. return bytes.Equal(blockID.Hash, other.Hash) &&
  961. blockID.PartSetHeader.Equals(other.PartSetHeader)
  962. }
  963. // Key returns a machine-readable string representation of the BlockID
  964. func (blockID BlockID) Key() string {
  965. pbph := blockID.PartSetHeader.ToProto()
  966. bz, err := pbph.Marshal()
  967. if err != nil {
  968. panic(err)
  969. }
  970. return fmt.Sprint(string(blockID.Hash), string(bz))
  971. }
  972. // ValidateBasic performs basic validation.
  973. func (blockID BlockID) ValidateBasic() error {
  974. // Hash can be empty in case of POLBlockID in Proposal.
  975. if err := ValidateHash(blockID.Hash); err != nil {
  976. return fmt.Errorf("wrong Hash: %w", err)
  977. }
  978. if err := blockID.PartSetHeader.ValidateBasic(); err != nil {
  979. return fmt.Errorf("wrong PartSetHeader: %w", err)
  980. }
  981. return nil
  982. }
  983. // IsNil returns true if this is the BlockID of a nil block.
  984. func (blockID BlockID) IsNil() bool {
  985. return len(blockID.Hash) == 0 &&
  986. blockID.PartSetHeader.IsZero()
  987. }
  988. // IsComplete returns true if this is a valid BlockID of a non-nil block.
  989. func (blockID BlockID) IsComplete() bool {
  990. return len(blockID.Hash) == tmhash.Size &&
  991. blockID.PartSetHeader.Total > 0 &&
  992. len(blockID.PartSetHeader.Hash) == tmhash.Size
  993. }
  994. // String returns a human readable string representation of the BlockID.
  995. //
  996. // 1. hash
  997. // 2. part set header
  998. //
  999. // See PartSetHeader#String
  1000. func (blockID BlockID) String() string {
  1001. return fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartSetHeader)
  1002. }
  1003. // ToProto converts BlockID to protobuf
  1004. func (blockID *BlockID) ToProto() tmproto.BlockID {
  1005. if blockID == nil {
  1006. return tmproto.BlockID{}
  1007. }
  1008. return tmproto.BlockID{
  1009. Hash: blockID.Hash,
  1010. PartSetHeader: blockID.PartSetHeader.ToProto(),
  1011. }
  1012. }
  1013. // FromProto sets a protobuf BlockID to the given pointer.
  1014. // It returns an error if the block id is invalid.
  1015. func BlockIDFromProto(bID *tmproto.BlockID) (*BlockID, error) {
  1016. if bID == nil {
  1017. return nil, errors.New("nil BlockID")
  1018. }
  1019. blockID := new(BlockID)
  1020. ph, err := PartSetHeaderFromProto(&bID.PartSetHeader)
  1021. if err != nil {
  1022. return nil, err
  1023. }
  1024. blockID.PartSetHeader = *ph
  1025. blockID.Hash = bID.Hash
  1026. return blockID, blockID.ValidateBasic()
  1027. }