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.

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