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.

1259 lines
33 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. "time"
  8. "github.com/gogo/protobuf/proto"
  9. gogotypes "github.com/gogo/protobuf/types"
  10. "github.com/tendermint/tendermint/crypto"
  11. "github.com/tendermint/tendermint/crypto/merkle"
  12. "github.com/tendermint/tendermint/crypto/tmhash"
  13. "github.com/tendermint/tendermint/libs/bits"
  14. tmbytes "github.com/tendermint/tendermint/libs/bytes"
  15. tmmath "github.com/tendermint/tendermint/libs/math"
  16. tmsync "github.com/tendermint/tendermint/libs/sync"
  17. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  18. "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 tmsync.Mutex
  38. Header `json:"header"`
  39. Data `json:"data"`
  40. Evidence EvidenceData `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: %v", 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.Evidence may be nil, but we're just looping.
  70. for i, ev := range b.Evidence.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 {
  110. if b == nil {
  111. return nil
  112. }
  113. b.mtx.Lock()
  114. defer b.mtx.Unlock()
  115. pbb, err := b.ToProto()
  116. if err != nil {
  117. panic(err)
  118. }
  119. bz, err := proto.Marshal(pbb)
  120. if err != nil {
  121. panic(err)
  122. }
  123. return NewPartSetFromData(bz, partSize)
  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: EvidenceData{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"`
  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: %v", err)
  351. }
  352. if err := ValidateHash(h.DataHash); err != nil {
  353. return fmt.Errorf("wrong DataHash: %v", err)
  354. }
  355. if err := ValidateHash(h.EvidenceHash); err != nil {
  356. return fmt.Errorf("wrong EvidenceHash: %v", 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: %v", err)
  368. }
  369. if err := ValidateHash(h.NextValidatorsHash); err != nil {
  370. return fmt.Errorf("wrong NextValidatorsHash: %v", err)
  371. }
  372. if err := ValidateHash(h.ConsensusHash); err != nil {
  373. return fmt.Errorf("wrong ConsensusHash: %v", err)
  374. }
  375. // NOTE: AppHash is arbitrary length
  376. if err := ValidateHash(h.LastResultsHash); err != nil {
  377. return fmt.Errorf("wrong LastResultsHash: %v", 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. }
  534. // NewCommitSigForBlock returns new CommitSig with BlockIDFlagCommit.
  535. func NewCommitSigForBlock(signature []byte, valAddr Address, ts time.Time) CommitSig {
  536. return CommitSig{
  537. BlockIDFlag: BlockIDFlagCommit,
  538. ValidatorAddress: valAddr,
  539. Timestamp: ts,
  540. Signature: signature,
  541. }
  542. }
  543. func MaxCommitBytes(valCount int) int64 {
  544. // From the repeated commit sig field
  545. var protoEncodingOverhead int64 = 2
  546. return MaxCommitOverheadBytes + ((MaxCommitSigBytes + protoEncodingOverhead) * int64(valCount))
  547. }
  548. // NewCommitSigAbsent returns new CommitSig with BlockIDFlagAbsent. Other
  549. // fields are all empty.
  550. func NewCommitSigAbsent() CommitSig {
  551. return CommitSig{
  552. BlockIDFlag: BlockIDFlagAbsent,
  553. }
  554. }
  555. // ForBlock returns true if CommitSig is for the block.
  556. func (cs CommitSig) ForBlock() bool {
  557. return cs.BlockIDFlag == BlockIDFlagCommit
  558. }
  559. // Absent returns true if CommitSig is absent.
  560. func (cs CommitSig) Absent() bool {
  561. return cs.BlockIDFlag == BlockIDFlagAbsent
  562. }
  563. // CommitSig returns a string representation of CommitSig.
  564. //
  565. // 1. first 6 bytes of signature
  566. // 2. first 6 bytes of validator address
  567. // 3. block ID flag
  568. // 4. timestamp
  569. func (cs CommitSig) String() string {
  570. return fmt.Sprintf("CommitSig{%X by %X on %v @ %s}",
  571. tmbytes.Fingerprint(cs.Signature),
  572. tmbytes.Fingerprint(cs.ValidatorAddress),
  573. cs.BlockIDFlag,
  574. CanonicalTime(cs.Timestamp))
  575. }
  576. // BlockID returns the Commit's BlockID if CommitSig indicates signing,
  577. // otherwise - empty BlockID.
  578. func (cs CommitSig) BlockID(commitBlockID BlockID) BlockID {
  579. var blockID BlockID
  580. switch cs.BlockIDFlag {
  581. case BlockIDFlagAbsent:
  582. blockID = BlockID{}
  583. case BlockIDFlagCommit:
  584. blockID = commitBlockID
  585. case BlockIDFlagNil:
  586. blockID = BlockID{}
  587. default:
  588. panic(fmt.Sprintf("Unknown BlockIDFlag: %v", cs.BlockIDFlag))
  589. }
  590. return blockID
  591. }
  592. // ValidateBasic performs basic validation.
  593. func (cs CommitSig) ValidateBasic() error {
  594. switch cs.BlockIDFlag {
  595. case BlockIDFlagAbsent:
  596. case BlockIDFlagCommit:
  597. case BlockIDFlagNil:
  598. default:
  599. return fmt.Errorf("unknown BlockIDFlag: %v", cs.BlockIDFlag)
  600. }
  601. switch cs.BlockIDFlag {
  602. case BlockIDFlagAbsent:
  603. if len(cs.ValidatorAddress) != 0 {
  604. return errors.New("validator address is present")
  605. }
  606. if !cs.Timestamp.IsZero() {
  607. return errors.New("time is present")
  608. }
  609. if len(cs.Signature) != 0 {
  610. return errors.New("signature is present")
  611. }
  612. default:
  613. if len(cs.ValidatorAddress) != crypto.AddressSize {
  614. return fmt.Errorf("expected ValidatorAddress size to be %d bytes, got %d bytes",
  615. crypto.AddressSize,
  616. len(cs.ValidatorAddress),
  617. )
  618. }
  619. // NOTE: Timestamp validation is subtle and handled elsewhere.
  620. if len(cs.Signature) == 0 {
  621. return errors.New("signature is missing")
  622. }
  623. if len(cs.Signature) > MaxSignatureSize {
  624. return fmt.Errorf("signature is too big (max: %d)", MaxSignatureSize)
  625. }
  626. }
  627. return nil
  628. }
  629. // ToProto converts CommitSig to protobuf
  630. func (cs *CommitSig) ToProto() *tmproto.CommitSig {
  631. if cs == nil {
  632. return nil
  633. }
  634. return &tmproto.CommitSig{
  635. BlockIdFlag: tmproto.BlockIDFlag(cs.BlockIDFlag),
  636. ValidatorAddress: cs.ValidatorAddress,
  637. Timestamp: cs.Timestamp,
  638. Signature: cs.Signature,
  639. }
  640. }
  641. // FromProto sets a protobuf CommitSig to the given pointer.
  642. // It returns an error if the CommitSig is invalid.
  643. func (cs *CommitSig) FromProto(csp tmproto.CommitSig) error {
  644. cs.BlockIDFlag = BlockIDFlag(csp.BlockIdFlag)
  645. cs.ValidatorAddress = csp.ValidatorAddress
  646. cs.Timestamp = csp.Timestamp
  647. cs.Signature = csp.Signature
  648. return cs.ValidateBasic()
  649. }
  650. //-------------------------------------
  651. // Commit contains the evidence that a block was committed by a set of validators.
  652. // NOTE: Commit is empty for height 1, but never nil.
  653. type Commit struct {
  654. // NOTE: The signatures are in order of address to preserve the bonded
  655. // ValidatorSet order.
  656. // Any peer with a block can gossip signatures by index with a peer without
  657. // recalculating the active ValidatorSet.
  658. Height int64 `json:"height"`
  659. Round int32 `json:"round"`
  660. BlockID BlockID `json:"block_id"`
  661. Signatures []CommitSig `json:"signatures"`
  662. // Memoized in first call to corresponding method.
  663. // NOTE: can't memoize in constructor because constructor isn't used for
  664. // unmarshaling.
  665. hash tmbytes.HexBytes
  666. bitArray *bits.BitArray
  667. }
  668. // NewCommit returns a new Commit.
  669. func NewCommit(height int64, round int32, blockID BlockID, commitSigs []CommitSig) *Commit {
  670. return &Commit{
  671. Height: height,
  672. Round: round,
  673. BlockID: blockID,
  674. Signatures: commitSigs,
  675. }
  676. }
  677. // CommitToVoteSet constructs a VoteSet from the Commit and validator set.
  678. // Panics if signatures from the commit can't be added to the voteset.
  679. // Inverse of VoteSet.MakeCommit().
  680. func CommitToVoteSet(chainID string, commit *Commit, vals *ValidatorSet) *VoteSet {
  681. voteSet := NewVoteSet(chainID, commit.Height, commit.Round, tmproto.PrecommitType, vals)
  682. for idx, commitSig := range commit.Signatures {
  683. if commitSig.Absent() {
  684. continue // OK, some precommits can be missing.
  685. }
  686. added, err := voteSet.AddVote(commit.GetVote(int32(idx)))
  687. if !added || err != nil {
  688. panic(fmt.Sprintf("Failed to reconstruct LastCommit: %v", err))
  689. }
  690. }
  691. return voteSet
  692. }
  693. // GetVote converts the CommitSig for the given valIdx to a Vote.
  694. // Returns nil if the precommit at valIdx is nil.
  695. // Panics if valIdx >= commit.Size().
  696. func (commit *Commit) GetVote(valIdx int32) *Vote {
  697. commitSig := commit.Signatures[valIdx]
  698. return &Vote{
  699. Type: tmproto.PrecommitType,
  700. Height: commit.Height,
  701. Round: commit.Round,
  702. BlockID: commitSig.BlockID(commit.BlockID),
  703. Timestamp: commitSig.Timestamp,
  704. ValidatorAddress: commitSig.ValidatorAddress,
  705. ValidatorIndex: valIdx,
  706. Signature: commitSig.Signature,
  707. }
  708. }
  709. // VoteSignBytes returns the bytes of the Vote corresponding to valIdx for
  710. // signing.
  711. //
  712. // The only unique part is the Timestamp - all other fields signed over are
  713. // otherwise the same for all validators.
  714. //
  715. // Panics if valIdx >= commit.Size().
  716. //
  717. // See VoteSignBytes
  718. func (commit *Commit) VoteSignBytes(chainID string, valIdx int32) []byte {
  719. v := commit.GetVote(valIdx).ToProto()
  720. return VoteSignBytes(chainID, v)
  721. }
  722. // Type returns the vote type of the commit, which is always VoteTypePrecommit
  723. // Implements VoteSetReader.
  724. func (commit *Commit) Type() byte {
  725. return byte(tmproto.PrecommitType)
  726. }
  727. // GetHeight returns height of the commit.
  728. // Implements VoteSetReader.
  729. func (commit *Commit) GetHeight() int64 {
  730. return commit.Height
  731. }
  732. // GetRound returns height of the commit.
  733. // Implements VoteSetReader.
  734. func (commit *Commit) GetRound() int32 {
  735. return commit.Round
  736. }
  737. // Size returns the number of signatures in the commit.
  738. // Implements VoteSetReader.
  739. func (commit *Commit) Size() int {
  740. if commit == nil {
  741. return 0
  742. }
  743. return len(commit.Signatures)
  744. }
  745. // BitArray returns a BitArray of which validators voted for BlockID or nil in this commit.
  746. // Implements VoteSetReader.
  747. func (commit *Commit) BitArray() *bits.BitArray {
  748. if commit.bitArray == nil {
  749. commit.bitArray = bits.NewBitArray(len(commit.Signatures))
  750. for i, commitSig := range commit.Signatures {
  751. // TODO: need to check the BlockID otherwise we could be counting conflicts,
  752. // not just the one with +2/3 !
  753. commit.bitArray.SetIndex(i, !commitSig.Absent())
  754. }
  755. }
  756. return commit.bitArray
  757. }
  758. // GetByIndex returns the vote corresponding to a given validator index.
  759. // Panics if `index >= commit.Size()`.
  760. // Implements VoteSetReader.
  761. func (commit *Commit) GetByIndex(valIdx int32) *Vote {
  762. return commit.GetVote(valIdx)
  763. }
  764. // IsCommit returns true if there is at least one signature.
  765. // Implements VoteSetReader.
  766. func (commit *Commit) IsCommit() bool {
  767. return len(commit.Signatures) != 0
  768. }
  769. // ValidateBasic performs basic validation that doesn't involve state data.
  770. // Does not actually check the cryptographic signatures.
  771. func (commit *Commit) ValidateBasic() error {
  772. if commit.Height < 0 {
  773. return errors.New("negative Height")
  774. }
  775. if commit.Round < 0 {
  776. return errors.New("negative Round")
  777. }
  778. if commit.Height >= 1 {
  779. if commit.BlockID.IsZero() {
  780. return errors.New("commit cannot be for nil block")
  781. }
  782. if len(commit.Signatures) == 0 {
  783. return errors.New("no signatures in commit")
  784. }
  785. for i, commitSig := range commit.Signatures {
  786. if err := commitSig.ValidateBasic(); err != nil {
  787. return fmt.Errorf("wrong CommitSig #%d: %v", i, err)
  788. }
  789. }
  790. }
  791. return nil
  792. }
  793. // Hash returns the hash of the commit
  794. func (commit *Commit) Hash() tmbytes.HexBytes {
  795. if commit == nil {
  796. return nil
  797. }
  798. if commit.hash == nil {
  799. bs := make([][]byte, len(commit.Signatures))
  800. for i, commitSig := range commit.Signatures {
  801. pbcs := commitSig.ToProto()
  802. bz, err := pbcs.Marshal()
  803. if err != nil {
  804. panic(err)
  805. }
  806. bs[i] = bz
  807. }
  808. commit.hash = merkle.HashFromByteSlices(bs)
  809. }
  810. return commit.hash
  811. }
  812. // StringIndented returns a string representation of the commit.
  813. func (commit *Commit) StringIndented(indent string) string {
  814. if commit == nil {
  815. return "nil-Commit"
  816. }
  817. commitSigStrings := make([]string, len(commit.Signatures))
  818. for i, commitSig := range commit.Signatures {
  819. commitSigStrings[i] = commitSig.String()
  820. }
  821. return fmt.Sprintf(`Commit{
  822. %s Height: %d
  823. %s Round: %d
  824. %s BlockID: %v
  825. %s Signatures:
  826. %s %v
  827. %s}#%v`,
  828. indent, commit.Height,
  829. indent, commit.Round,
  830. indent, commit.BlockID,
  831. indent,
  832. indent, strings.Join(commitSigStrings, "\n"+indent+" "),
  833. indent, commit.hash)
  834. }
  835. // ToProto converts Commit to protobuf
  836. func (commit *Commit) ToProto() *tmproto.Commit {
  837. if commit == nil {
  838. return nil
  839. }
  840. c := new(tmproto.Commit)
  841. sigs := make([]tmproto.CommitSig, len(commit.Signatures))
  842. for i := range commit.Signatures {
  843. sigs[i] = *commit.Signatures[i].ToProto()
  844. }
  845. c.Signatures = sigs
  846. c.Height = commit.Height
  847. c.Round = commit.Round
  848. c.BlockID = commit.BlockID.ToProto()
  849. return c
  850. }
  851. // FromProto sets a protobuf Commit to the given pointer.
  852. // It returns an error if the commit is invalid.
  853. func CommitFromProto(cp *tmproto.Commit) (*Commit, error) {
  854. if cp == nil {
  855. return nil, errors.New("nil Commit")
  856. }
  857. var (
  858. commit = new(Commit)
  859. )
  860. bi, err := BlockIDFromProto(&cp.BlockID)
  861. if err != nil {
  862. return nil, err
  863. }
  864. sigs := make([]CommitSig, len(cp.Signatures))
  865. for i := range cp.Signatures {
  866. if err := sigs[i].FromProto(cp.Signatures[i]); err != nil {
  867. return nil, err
  868. }
  869. }
  870. commit.Signatures = sigs
  871. commit.Height = cp.Height
  872. commit.Round = cp.Round
  873. commit.BlockID = *bi
  874. return commit, commit.ValidateBasic()
  875. }
  876. //-----------------------------------------------------------------------------
  877. // Data contains the set of transactions included in the block
  878. type Data struct {
  879. // Txs that will be applied by state @ block.Height+1.
  880. // NOTE: not all txs here are valid. We're just agreeing on the order first.
  881. // This means that block.AppHash does not include these txs.
  882. Txs Txs `json:"txs"`
  883. // Volatile
  884. hash tmbytes.HexBytes
  885. }
  886. // Hash returns the hash of the data
  887. func (data *Data) Hash() tmbytes.HexBytes {
  888. if data == nil {
  889. return (Txs{}).Hash()
  890. }
  891. if data.hash == nil {
  892. data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs
  893. }
  894. return data.hash
  895. }
  896. // StringIndented returns an indented string representation of the transactions.
  897. func (data *Data) StringIndented(indent string) string {
  898. if data == nil {
  899. return "nil-Data"
  900. }
  901. txStrings := make([]string, tmmath.MinInt(len(data.Txs), 21))
  902. for i, tx := range data.Txs {
  903. if i == 20 {
  904. txStrings[i] = fmt.Sprintf("... (%v total)", len(data.Txs))
  905. break
  906. }
  907. txStrings[i] = fmt.Sprintf("%X (%d bytes)", tx.Hash(), len(tx))
  908. }
  909. return fmt.Sprintf(`Data{
  910. %s %v
  911. %s}#%v`,
  912. indent, strings.Join(txStrings, "\n"+indent+" "),
  913. indent, data.hash)
  914. }
  915. // ToProto converts Data to protobuf
  916. func (data *Data) ToProto() tmproto.Data {
  917. tp := new(tmproto.Data)
  918. if len(data.Txs) > 0 {
  919. txBzs := make([][]byte, len(data.Txs))
  920. for i := range data.Txs {
  921. txBzs[i] = data.Txs[i]
  922. }
  923. tp.Txs = txBzs
  924. }
  925. return *tp
  926. }
  927. // DataFromProto takes a protobuf representation of Data &
  928. // returns the native type.
  929. func DataFromProto(dp *tmproto.Data) (Data, error) {
  930. if dp == nil {
  931. return Data{}, errors.New("nil data")
  932. }
  933. data := new(Data)
  934. if len(dp.Txs) > 0 {
  935. txBzs := make(Txs, len(dp.Txs))
  936. for i := range dp.Txs {
  937. txBzs[i] = Tx(dp.Txs[i])
  938. }
  939. data.Txs = txBzs
  940. } else {
  941. data.Txs = Txs{}
  942. }
  943. return *data, nil
  944. }
  945. //-----------------------------------------------------------------------------
  946. // EvidenceData contains any evidence of malicious wrong-doing by validators
  947. type EvidenceData struct {
  948. Evidence EvidenceList `json:"evidence"`
  949. // Volatile. Used as cache
  950. hash tmbytes.HexBytes
  951. byteSize int64
  952. }
  953. // Hash returns the hash of the data.
  954. func (data *EvidenceData) Hash() tmbytes.HexBytes {
  955. if data.hash == nil {
  956. data.hash = data.Evidence.Hash()
  957. }
  958. return data.hash
  959. }
  960. // ByteSize returns the total byte size of all the evidence
  961. func (data *EvidenceData) ByteSize() int64 {
  962. if data.byteSize == 0 && len(data.Evidence) != 0 {
  963. pb, err := data.ToProto()
  964. if err != nil {
  965. panic(err)
  966. }
  967. data.byteSize = int64(pb.Size())
  968. }
  969. return data.byteSize
  970. }
  971. // StringIndented returns a string representation of the evidence.
  972. func (data *EvidenceData) StringIndented(indent string) string {
  973. if data == nil {
  974. return "nil-Evidence"
  975. }
  976. evStrings := make([]string, tmmath.MinInt(len(data.Evidence), 21))
  977. for i, ev := range data.Evidence {
  978. if i == 20 {
  979. evStrings[i] = fmt.Sprintf("... (%v total)", len(data.Evidence))
  980. break
  981. }
  982. evStrings[i] = fmt.Sprintf("Evidence:%v", ev)
  983. }
  984. return fmt.Sprintf(`EvidenceData{
  985. %s %v
  986. %s}#%v`,
  987. indent, strings.Join(evStrings, "\n"+indent+" "),
  988. indent, data.hash)
  989. }
  990. // ToProto converts EvidenceData to protobuf
  991. func (data *EvidenceData) ToProto() (*tmproto.EvidenceList, error) {
  992. if data == nil {
  993. return nil, errors.New("nil evidence data")
  994. }
  995. evi := new(tmproto.EvidenceList)
  996. eviBzs := make([]tmproto.Evidence, len(data.Evidence))
  997. for i := range data.Evidence {
  998. protoEvi, err := EvidenceToProto(data.Evidence[i])
  999. if err != nil {
  1000. return nil, err
  1001. }
  1002. eviBzs[i] = *protoEvi
  1003. }
  1004. evi.Evidence = eviBzs
  1005. return evi, nil
  1006. }
  1007. // FromProto sets a protobuf EvidenceData to the given pointer.
  1008. func (data *EvidenceData) FromProto(eviData *tmproto.EvidenceList) error {
  1009. if eviData == nil {
  1010. return errors.New("nil evidenceData")
  1011. }
  1012. eviBzs := make(EvidenceList, len(eviData.Evidence))
  1013. for i := range eviData.Evidence {
  1014. evi, err := EvidenceFromProto(&eviData.Evidence[i])
  1015. if err != nil {
  1016. return err
  1017. }
  1018. eviBzs[i] = evi
  1019. }
  1020. data.Evidence = eviBzs
  1021. data.byteSize = int64(eviData.Size())
  1022. return nil
  1023. }
  1024. //--------------------------------------------------------------------------------
  1025. // BlockID
  1026. type BlockID struct {
  1027. Hash tmbytes.HexBytes `json:"hash"`
  1028. PartSetHeader PartSetHeader `json:"part_set_header"`
  1029. }
  1030. // Equals returns true if the BlockID matches the given BlockID
  1031. func (blockID BlockID) Equals(other BlockID) bool {
  1032. return bytes.Equal(blockID.Hash, other.Hash) &&
  1033. blockID.PartSetHeader.Equals(other.PartSetHeader)
  1034. }
  1035. // Key returns a machine-readable string representation of the BlockID
  1036. func (blockID BlockID) Key() string {
  1037. pbph := blockID.PartSetHeader.ToProto()
  1038. bz, err := pbph.Marshal()
  1039. if err != nil {
  1040. panic(err)
  1041. }
  1042. return fmt.Sprint(string(blockID.Hash), string(bz))
  1043. }
  1044. // ValidateBasic performs basic validation.
  1045. func (blockID BlockID) ValidateBasic() error {
  1046. // Hash can be empty in case of POLBlockID in Proposal.
  1047. if err := ValidateHash(blockID.Hash); err != nil {
  1048. return fmt.Errorf("wrong Hash: %w", err)
  1049. }
  1050. if err := blockID.PartSetHeader.ValidateBasic(); err != nil {
  1051. return fmt.Errorf("wrong PartSetHeader: %w", err)
  1052. }
  1053. return nil
  1054. }
  1055. // IsZero returns true if this is the BlockID of a nil block.
  1056. func (blockID BlockID) IsZero() bool {
  1057. return len(blockID.Hash) == 0 &&
  1058. blockID.PartSetHeader.IsZero()
  1059. }
  1060. // IsComplete returns true if this is a valid BlockID of a non-nil block.
  1061. func (blockID BlockID) IsComplete() bool {
  1062. return len(blockID.Hash) == tmhash.Size &&
  1063. blockID.PartSetHeader.Total > 0 &&
  1064. len(blockID.PartSetHeader.Hash) == tmhash.Size
  1065. }
  1066. // String returns a human readable string representation of the BlockID.
  1067. //
  1068. // 1. hash
  1069. // 2. part set header
  1070. //
  1071. // See PartSetHeader#String
  1072. func (blockID BlockID) String() string {
  1073. return fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartSetHeader)
  1074. }
  1075. // ToProto converts BlockID to protobuf
  1076. func (blockID *BlockID) ToProto() tmproto.BlockID {
  1077. if blockID == nil {
  1078. return tmproto.BlockID{}
  1079. }
  1080. return tmproto.BlockID{
  1081. Hash: blockID.Hash,
  1082. PartSetHeader: blockID.PartSetHeader.ToProto(),
  1083. }
  1084. }
  1085. // FromProto sets a protobuf BlockID to the given pointer.
  1086. // It returns an error if the block id is invalid.
  1087. func BlockIDFromProto(bID *tmproto.BlockID) (*BlockID, error) {
  1088. if bID == nil {
  1089. return nil, errors.New("nil BlockID")
  1090. }
  1091. blockID := new(BlockID)
  1092. ph, err := PartSetHeaderFromProto(&bID.PartSetHeader)
  1093. if err != nil {
  1094. return nil, err
  1095. }
  1096. blockID.PartSetHeader = *ph
  1097. blockID.Hash = bID.Hash
  1098. return blockID, blockID.ValidateBasic()
  1099. }