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.

1249 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. LastResultsHash tmbytes.HexBytes `json:"last_results_hash"`
  298. // consensus info
  299. EvidenceHash tmbytes.HexBytes `json:"evidence_hash"` // evidence included in the block
  300. ProposerAddress Address `json:"proposer_address"` // original proposer of the block
  301. }
  302. // Populate the Header with state-derived data.
  303. // Call this after MakeBlock to complete the Header.
  304. func (h *Header) Populate(
  305. version tmversion.Consensus, chainID string,
  306. timestamp time.Time, lastBlockID BlockID,
  307. valHash, nextValHash []byte,
  308. consensusHash, appHash, lastResultsHash []byte,
  309. proposerAddress Address,
  310. ) {
  311. h.Version = version
  312. h.ChainID = chainID
  313. h.Time = timestamp
  314. h.LastBlockID = lastBlockID
  315. h.ValidatorsHash = valHash
  316. h.NextValidatorsHash = nextValHash
  317. h.ConsensusHash = consensusHash
  318. h.AppHash = appHash
  319. h.LastResultsHash = lastResultsHash
  320. h.ProposerAddress = proposerAddress
  321. }
  322. // ValidateBasic performs stateless validation on a Header returning an error
  323. // if any validation fails.
  324. //
  325. // NOTE: Timestamp validation is subtle and handled elsewhere.
  326. func (h Header) ValidateBasic() error {
  327. if h.Version.Block != version.BlockProtocol {
  328. return fmt.Errorf("block protocol is incorrect: got: %d, want: %d ", h.Version.Block, version.BlockProtocol)
  329. }
  330. if len(h.ChainID) > MaxChainIDLen {
  331. return fmt.Errorf("chainID is too long; got: %d, max: %d", len(h.ChainID), MaxChainIDLen)
  332. }
  333. if h.Height < 0 {
  334. return errors.New("negative Height")
  335. } else if h.Height == 0 {
  336. return errors.New("zero Height")
  337. }
  338. if err := h.LastBlockID.ValidateBasic(); err != nil {
  339. return fmt.Errorf("wrong LastBlockID: %w", err)
  340. }
  341. if err := ValidateHash(h.LastCommitHash); err != nil {
  342. return fmt.Errorf("wrong LastCommitHash: %v", err)
  343. }
  344. if err := ValidateHash(h.DataHash); err != nil {
  345. return fmt.Errorf("wrong DataHash: %v", err)
  346. }
  347. if err := ValidateHash(h.EvidenceHash); err != nil {
  348. return fmt.Errorf("wrong EvidenceHash: %v", err)
  349. }
  350. if len(h.ProposerAddress) != crypto.AddressSize {
  351. return fmt.Errorf(
  352. "invalid ProposerAddress length; got: %d, expected: %d",
  353. len(h.ProposerAddress), crypto.AddressSize,
  354. )
  355. }
  356. // Basic validation of hashes related to application data.
  357. // Will validate fully against state in state#ValidateBlock.
  358. if err := ValidateHash(h.ValidatorsHash); err != nil {
  359. return fmt.Errorf("wrong ValidatorsHash: %v", err)
  360. }
  361. if err := ValidateHash(h.NextValidatorsHash); err != nil {
  362. return fmt.Errorf("wrong NextValidatorsHash: %v", err)
  363. }
  364. if err := ValidateHash(h.ConsensusHash); err != nil {
  365. return fmt.Errorf("wrong ConsensusHash: %v", err)
  366. }
  367. // NOTE: AppHash is arbitrary length
  368. if err := ValidateHash(h.LastResultsHash); err != nil {
  369. return fmt.Errorf("wrong LastResultsHash: %v", err)
  370. }
  371. return nil
  372. }
  373. // Hash returns the hash of the header.
  374. // It computes a Merkle tree from the header fields
  375. // ordered as they appear in the Header.
  376. // Returns nil if ValidatorHash is missing,
  377. // since a Header is not valid unless there is
  378. // a ValidatorsHash (corresponding to the validator set).
  379. func (h *Header) Hash() tmbytes.HexBytes {
  380. if h == nil || len(h.ValidatorsHash) == 0 {
  381. return nil
  382. }
  383. hbz, err := h.Version.Marshal()
  384. if err != nil {
  385. return nil
  386. }
  387. pbt, err := gogotypes.StdTimeMarshal(h.Time)
  388. if err != nil {
  389. return nil
  390. }
  391. pbbi := h.LastBlockID.ToProto()
  392. bzbi, err := pbbi.Marshal()
  393. if err != nil {
  394. return nil
  395. }
  396. return merkle.HashFromByteSlices([][]byte{
  397. hbz,
  398. cdcEncode(h.ChainID),
  399. cdcEncode(h.Height),
  400. pbt,
  401. bzbi,
  402. cdcEncode(h.LastCommitHash),
  403. cdcEncode(h.DataHash),
  404. cdcEncode(h.ValidatorsHash),
  405. cdcEncode(h.NextValidatorsHash),
  406. cdcEncode(h.ConsensusHash),
  407. cdcEncode(h.AppHash),
  408. cdcEncode(h.LastResultsHash),
  409. cdcEncode(h.EvidenceHash),
  410. cdcEncode(h.ProposerAddress),
  411. })
  412. }
  413. // StringIndented returns an indented string representation of the header.
  414. func (h *Header) StringIndented(indent string) string {
  415. if h == nil {
  416. return "nil-Header"
  417. }
  418. return fmt.Sprintf(`Header{
  419. %s Version: %v
  420. %s ChainID: %v
  421. %s Height: %v
  422. %s Time: %v
  423. %s LastBlockID: %v
  424. %s LastCommit: %v
  425. %s Data: %v
  426. %s Validators: %v
  427. %s NextValidators: %v
  428. %s App: %v
  429. %s Consensus: %v
  430. %s Results: %v
  431. %s Evidence: %v
  432. %s Proposer: %v
  433. %s}#%v`,
  434. indent, h.Version,
  435. indent, h.ChainID,
  436. indent, h.Height,
  437. indent, h.Time,
  438. indent, h.LastBlockID,
  439. indent, h.LastCommitHash,
  440. indent, h.DataHash,
  441. indent, h.ValidatorsHash,
  442. indent, h.NextValidatorsHash,
  443. indent, h.AppHash,
  444. indent, h.ConsensusHash,
  445. indent, h.LastResultsHash,
  446. indent, h.EvidenceHash,
  447. indent, h.ProposerAddress,
  448. indent, h.Hash())
  449. }
  450. // ToProto converts Header to protobuf
  451. func (h *Header) ToProto() *tmproto.Header {
  452. if h == nil {
  453. return nil
  454. }
  455. return &tmproto.Header{
  456. Version: h.Version,
  457. ChainID: h.ChainID,
  458. Height: h.Height,
  459. Time: h.Time,
  460. LastBlockId: h.LastBlockID.ToProto(),
  461. ValidatorsHash: h.ValidatorsHash,
  462. NextValidatorsHash: h.NextValidatorsHash,
  463. ConsensusHash: h.ConsensusHash,
  464. AppHash: h.AppHash,
  465. DataHash: h.DataHash,
  466. EvidenceHash: h.EvidenceHash,
  467. LastResultsHash: h.LastResultsHash,
  468. LastCommitHash: h.LastCommitHash,
  469. ProposerAddress: h.ProposerAddress,
  470. }
  471. }
  472. // FromProto sets a protobuf Header to the given pointer.
  473. // It returns an error if the header is invalid.
  474. func HeaderFromProto(ph *tmproto.Header) (Header, error) {
  475. if ph == nil {
  476. return Header{}, errors.New("nil Header")
  477. }
  478. h := new(Header)
  479. bi, err := BlockIDFromProto(&ph.LastBlockId)
  480. if err != nil {
  481. return Header{}, err
  482. }
  483. h.Version = ph.Version
  484. h.ChainID = ph.ChainID
  485. h.Height = ph.Height
  486. h.Time = ph.Time
  487. h.Height = ph.Height
  488. h.LastBlockID = *bi
  489. h.ValidatorsHash = ph.ValidatorsHash
  490. h.NextValidatorsHash = ph.NextValidatorsHash
  491. h.ConsensusHash = ph.ConsensusHash
  492. h.AppHash = ph.AppHash
  493. h.DataHash = ph.DataHash
  494. h.EvidenceHash = ph.EvidenceHash
  495. h.LastResultsHash = ph.LastResultsHash
  496. h.LastCommitHash = ph.LastCommitHash
  497. h.ProposerAddress = ph.ProposerAddress
  498. return *h, h.ValidateBasic()
  499. }
  500. //-------------------------------------
  501. // BlockIDFlag indicates which BlockID the signature is for.
  502. type BlockIDFlag byte
  503. const (
  504. // BlockIDFlagAbsent - no vote was received from a validator.
  505. BlockIDFlagAbsent BlockIDFlag = iota + 1
  506. // BlockIDFlagCommit - voted for the Commit.BlockID.
  507. BlockIDFlagCommit
  508. // BlockIDFlagNil - voted for nil.
  509. BlockIDFlagNil
  510. )
  511. const (
  512. // Max size of commit without any commitSigs -> 82 for BlockID, 8 for Height, 4 for Round.
  513. MaxCommitOverheadBytes int64 = 94
  514. // Commit sig size is made up of 64 bytes for the signature, 20 bytes for the address,
  515. // 1 byte for the flag and 14 bytes for the timestamp
  516. MaxCommitSigBytes int64 = 109
  517. )
  518. // CommitSig is a part of the Vote included in a Commit.
  519. type CommitSig struct {
  520. BlockIDFlag BlockIDFlag `json:"block_id_flag"`
  521. ValidatorAddress Address `json:"validator_address"`
  522. Timestamp time.Time `json:"timestamp"`
  523. Signature []byte `json:"signature"`
  524. }
  525. // NewCommitSigForBlock returns new CommitSig with BlockIDFlagCommit.
  526. func NewCommitSigForBlock(signature []byte, valAddr Address, ts time.Time) CommitSig {
  527. return CommitSig{
  528. BlockIDFlag: BlockIDFlagCommit,
  529. ValidatorAddress: valAddr,
  530. Timestamp: ts,
  531. Signature: signature,
  532. }
  533. }
  534. func MaxCommitBytes(valCount int) int64 {
  535. // From the repeated commit sig field
  536. var protoEncodingOverhead int64 = 2
  537. return MaxCommitOverheadBytes + ((MaxCommitSigBytes + protoEncodingOverhead) * int64(valCount))
  538. }
  539. // NewCommitSigAbsent returns new CommitSig with BlockIDFlagAbsent. Other
  540. // fields are all empty.
  541. func NewCommitSigAbsent() CommitSig {
  542. return CommitSig{
  543. BlockIDFlag: BlockIDFlagAbsent,
  544. }
  545. }
  546. // ForBlock returns true if CommitSig is for the block.
  547. func (cs CommitSig) ForBlock() bool {
  548. return cs.BlockIDFlag == BlockIDFlagCommit
  549. }
  550. // Absent returns true if CommitSig is absent.
  551. func (cs CommitSig) Absent() bool {
  552. return cs.BlockIDFlag == BlockIDFlagAbsent
  553. }
  554. // CommitSig returns a string representation of CommitSig.
  555. //
  556. // 1. first 6 bytes of signature
  557. // 2. first 6 bytes of validator address
  558. // 3. block ID flag
  559. // 4. timestamp
  560. func (cs CommitSig) String() string {
  561. return fmt.Sprintf("CommitSig{%X by %X on %v @ %s}",
  562. tmbytes.Fingerprint(cs.Signature),
  563. tmbytes.Fingerprint(cs.ValidatorAddress),
  564. cs.BlockIDFlag,
  565. CanonicalTime(cs.Timestamp))
  566. }
  567. // BlockID returns the Commit's BlockID if CommitSig indicates signing,
  568. // otherwise - empty BlockID.
  569. func (cs CommitSig) BlockID(commitBlockID BlockID) BlockID {
  570. var blockID BlockID
  571. switch cs.BlockIDFlag {
  572. case BlockIDFlagAbsent:
  573. blockID = BlockID{}
  574. case BlockIDFlagCommit:
  575. blockID = commitBlockID
  576. case BlockIDFlagNil:
  577. blockID = BlockID{}
  578. default:
  579. panic(fmt.Sprintf("Unknown BlockIDFlag: %v", cs.BlockIDFlag))
  580. }
  581. return blockID
  582. }
  583. // ValidateBasic performs basic validation.
  584. func (cs CommitSig) ValidateBasic() error {
  585. switch cs.BlockIDFlag {
  586. case BlockIDFlagAbsent:
  587. case BlockIDFlagCommit:
  588. case BlockIDFlagNil:
  589. default:
  590. return fmt.Errorf("unknown BlockIDFlag: %v", cs.BlockIDFlag)
  591. }
  592. switch cs.BlockIDFlag {
  593. case BlockIDFlagAbsent:
  594. if len(cs.ValidatorAddress) != 0 {
  595. return errors.New("validator address is present")
  596. }
  597. if !cs.Timestamp.IsZero() {
  598. return errors.New("time is present")
  599. }
  600. if len(cs.Signature) != 0 {
  601. return errors.New("signature is present")
  602. }
  603. default:
  604. if len(cs.ValidatorAddress) != crypto.AddressSize {
  605. return fmt.Errorf("expected ValidatorAddress size to be %d bytes, got %d bytes",
  606. crypto.AddressSize,
  607. len(cs.ValidatorAddress),
  608. )
  609. }
  610. // NOTE: Timestamp validation is subtle and handled elsewhere.
  611. if len(cs.Signature) == 0 {
  612. return errors.New("signature is missing")
  613. }
  614. if len(cs.Signature) > MaxSignatureSize {
  615. return fmt.Errorf("signature is too big (max: %d)", MaxSignatureSize)
  616. }
  617. }
  618. return nil
  619. }
  620. // ToProto converts CommitSig to protobuf
  621. func (cs *CommitSig) ToProto() *tmproto.CommitSig {
  622. if cs == nil {
  623. return nil
  624. }
  625. return &tmproto.CommitSig{
  626. BlockIdFlag: tmproto.BlockIDFlag(cs.BlockIDFlag),
  627. ValidatorAddress: cs.ValidatorAddress,
  628. Timestamp: cs.Timestamp,
  629. Signature: cs.Signature,
  630. }
  631. }
  632. // FromProto sets a protobuf CommitSig to the given pointer.
  633. // It returns an error if the CommitSig is invalid.
  634. func (cs *CommitSig) FromProto(csp tmproto.CommitSig) error {
  635. cs.BlockIDFlag = BlockIDFlag(csp.BlockIdFlag)
  636. cs.ValidatorAddress = csp.ValidatorAddress
  637. cs.Timestamp = csp.Timestamp
  638. cs.Signature = csp.Signature
  639. return cs.ValidateBasic()
  640. }
  641. //-------------------------------------
  642. // Commit contains the evidence that a block was committed by a set of validators.
  643. // NOTE: Commit is empty for height 1, but never nil.
  644. type Commit struct {
  645. // NOTE: The signatures are in order of address to preserve the bonded
  646. // ValidatorSet order.
  647. // Any peer with a block can gossip signatures by index with a peer without
  648. // recalculating the active ValidatorSet.
  649. Height int64 `json:"height"`
  650. Round int32 `json:"round"`
  651. BlockID BlockID `json:"block_id"`
  652. Signatures []CommitSig `json:"signatures"`
  653. // Memoized in first call to corresponding method.
  654. // NOTE: can't memoize in constructor because constructor isn't used for
  655. // unmarshaling.
  656. hash tmbytes.HexBytes
  657. bitArray *bits.BitArray
  658. }
  659. // NewCommit returns a new Commit.
  660. func NewCommit(height int64, round int32, blockID BlockID, commitSigs []CommitSig) *Commit {
  661. return &Commit{
  662. Height: height,
  663. Round: round,
  664. BlockID: blockID,
  665. Signatures: commitSigs,
  666. }
  667. }
  668. // CommitToVoteSet constructs a VoteSet from the Commit and validator set.
  669. // Panics if signatures from the commit can't be added to the voteset.
  670. // Inverse of VoteSet.MakeCommit().
  671. func CommitToVoteSet(chainID string, commit *Commit, vals *ValidatorSet) *VoteSet {
  672. voteSet := NewVoteSet(chainID, commit.Height, commit.Round, tmproto.PrecommitType, vals)
  673. for idx, commitSig := range commit.Signatures {
  674. if commitSig.Absent() {
  675. continue // OK, some precommits can be missing.
  676. }
  677. added, err := voteSet.AddVote(commit.GetVote(int32(idx)))
  678. if !added || err != nil {
  679. panic(fmt.Sprintf("Failed to reconstruct LastCommit: %v", err))
  680. }
  681. }
  682. return voteSet
  683. }
  684. // GetVote converts the CommitSig for the given valIdx to a Vote.
  685. // Returns nil if the precommit at valIdx is nil.
  686. // Panics if valIdx >= commit.Size().
  687. func (commit *Commit) GetVote(valIdx int32) *Vote {
  688. commitSig := commit.Signatures[valIdx]
  689. return &Vote{
  690. Type: tmproto.PrecommitType,
  691. Height: commit.Height,
  692. Round: commit.Round,
  693. BlockID: commitSig.BlockID(commit.BlockID),
  694. Timestamp: commitSig.Timestamp,
  695. ValidatorAddress: commitSig.ValidatorAddress,
  696. ValidatorIndex: valIdx,
  697. Signature: commitSig.Signature,
  698. }
  699. }
  700. // VoteSignBytes returns the bytes of the Vote corresponding to valIdx for
  701. // signing.
  702. //
  703. // The only unique part is the Timestamp - all other fields signed over are
  704. // otherwise the same for all validators.
  705. //
  706. // Panics if valIdx >= commit.Size().
  707. //
  708. // See VoteSignBytes
  709. func (commit *Commit) VoteSignBytes(chainID string, valIdx int32) []byte {
  710. v := commit.GetVote(valIdx).ToProto()
  711. return VoteSignBytes(chainID, v)
  712. }
  713. // Type returns the vote type of the commit, which is always VoteTypePrecommit
  714. // Implements VoteSetReader.
  715. func (commit *Commit) Type() byte {
  716. return byte(tmproto.PrecommitType)
  717. }
  718. // GetHeight returns height of the commit.
  719. // Implements VoteSetReader.
  720. func (commit *Commit) GetHeight() int64 {
  721. return commit.Height
  722. }
  723. // GetRound returns height of the commit.
  724. // Implements VoteSetReader.
  725. func (commit *Commit) GetRound() int32 {
  726. return commit.Round
  727. }
  728. // Size returns the number of signatures in the commit.
  729. // Implements VoteSetReader.
  730. func (commit *Commit) Size() int {
  731. if commit == nil {
  732. return 0
  733. }
  734. return len(commit.Signatures)
  735. }
  736. // BitArray returns a BitArray of which validators voted for BlockID or nil in this commit.
  737. // Implements VoteSetReader.
  738. func (commit *Commit) BitArray() *bits.BitArray {
  739. if commit.bitArray == nil {
  740. commit.bitArray = bits.NewBitArray(len(commit.Signatures))
  741. for i, commitSig := range commit.Signatures {
  742. // TODO: need to check the BlockID otherwise we could be counting conflicts,
  743. // not just the one with +2/3 !
  744. commit.bitArray.SetIndex(i, !commitSig.Absent())
  745. }
  746. }
  747. return commit.bitArray
  748. }
  749. // GetByIndex returns the vote corresponding to a given validator index.
  750. // Panics if `index >= commit.Size()`.
  751. // Implements VoteSetReader.
  752. func (commit *Commit) GetByIndex(valIdx int32) *Vote {
  753. return commit.GetVote(valIdx)
  754. }
  755. // IsCommit returns true if there is at least one signature.
  756. // Implements VoteSetReader.
  757. func (commit *Commit) IsCommit() bool {
  758. return len(commit.Signatures) != 0
  759. }
  760. // ValidateBasic performs basic validation that doesn't involve state data.
  761. // Does not actually check the cryptographic signatures.
  762. func (commit *Commit) ValidateBasic() error {
  763. if commit.Height < 0 {
  764. return errors.New("negative Height")
  765. }
  766. if commit.Round < 0 {
  767. return errors.New("negative Round")
  768. }
  769. if commit.Height >= 1 {
  770. if commit.BlockID.IsZero() {
  771. return errors.New("commit cannot be for nil block")
  772. }
  773. if len(commit.Signatures) == 0 {
  774. return errors.New("no signatures in commit")
  775. }
  776. for i, commitSig := range commit.Signatures {
  777. if err := commitSig.ValidateBasic(); err != nil {
  778. return fmt.Errorf("wrong CommitSig #%d: %v", i, err)
  779. }
  780. }
  781. }
  782. return nil
  783. }
  784. // Hash returns the hash of the commit
  785. func (commit *Commit) Hash() tmbytes.HexBytes {
  786. if commit == nil {
  787. return nil
  788. }
  789. if commit.hash == nil {
  790. bs := make([][]byte, len(commit.Signatures))
  791. for i, commitSig := range commit.Signatures {
  792. pbcs := commitSig.ToProto()
  793. bz, err := pbcs.Marshal()
  794. if err != nil {
  795. panic(err)
  796. }
  797. bs[i] = bz
  798. }
  799. commit.hash = merkle.HashFromByteSlices(bs)
  800. }
  801. return commit.hash
  802. }
  803. // StringIndented returns a string representation of the commit.
  804. func (commit *Commit) StringIndented(indent string) string {
  805. if commit == nil {
  806. return "nil-Commit"
  807. }
  808. commitSigStrings := make([]string, len(commit.Signatures))
  809. for i, commitSig := range commit.Signatures {
  810. commitSigStrings[i] = commitSig.String()
  811. }
  812. return fmt.Sprintf(`Commit{
  813. %s Height: %d
  814. %s Round: %d
  815. %s BlockID: %v
  816. %s Signatures:
  817. %s %v
  818. %s}#%v`,
  819. indent, commit.Height,
  820. indent, commit.Round,
  821. indent, commit.BlockID,
  822. indent,
  823. indent, strings.Join(commitSigStrings, "\n"+indent+" "),
  824. indent, commit.hash)
  825. }
  826. // ToProto converts Commit to protobuf
  827. func (commit *Commit) ToProto() *tmproto.Commit {
  828. if commit == nil {
  829. return nil
  830. }
  831. c := new(tmproto.Commit)
  832. sigs := make([]tmproto.CommitSig, len(commit.Signatures))
  833. for i := range commit.Signatures {
  834. sigs[i] = *commit.Signatures[i].ToProto()
  835. }
  836. c.Signatures = sigs
  837. c.Height = commit.Height
  838. c.Round = commit.Round
  839. c.BlockID = commit.BlockID.ToProto()
  840. return c
  841. }
  842. // FromProto sets a protobuf Commit to the given pointer.
  843. // It returns an error if the commit is invalid.
  844. func CommitFromProto(cp *tmproto.Commit) (*Commit, error) {
  845. if cp == nil {
  846. return nil, errors.New("nil Commit")
  847. }
  848. var (
  849. commit = new(Commit)
  850. )
  851. bi, err := BlockIDFromProto(&cp.BlockID)
  852. if err != nil {
  853. return nil, err
  854. }
  855. sigs := make([]CommitSig, len(cp.Signatures))
  856. for i := range cp.Signatures {
  857. if err := sigs[i].FromProto(cp.Signatures[i]); err != nil {
  858. return nil, err
  859. }
  860. }
  861. commit.Signatures = sigs
  862. commit.Height = cp.Height
  863. commit.Round = cp.Round
  864. commit.BlockID = *bi
  865. return commit, commit.ValidateBasic()
  866. }
  867. //-----------------------------------------------------------------------------
  868. // Data contains the set of transactions included in the block
  869. type Data struct {
  870. // Txs that will be applied by state @ block.Height+1.
  871. // NOTE: not all txs here are valid. We're just agreeing on the order first.
  872. // This means that block.AppHash does not include these txs.
  873. Txs Txs `json:"txs"`
  874. // Volatile
  875. hash tmbytes.HexBytes
  876. }
  877. // Hash returns the hash of the data
  878. func (data *Data) Hash() tmbytes.HexBytes {
  879. if data == nil {
  880. return (Txs{}).Hash()
  881. }
  882. if data.hash == nil {
  883. data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs
  884. }
  885. return data.hash
  886. }
  887. // StringIndented returns an indented string representation of the transactions.
  888. func (data *Data) StringIndented(indent string) string {
  889. if data == nil {
  890. return "nil-Data"
  891. }
  892. txStrings := make([]string, tmmath.MinInt(len(data.Txs), 21))
  893. for i, tx := range data.Txs {
  894. if i == 20 {
  895. txStrings[i] = fmt.Sprintf("... (%v total)", len(data.Txs))
  896. break
  897. }
  898. txStrings[i] = fmt.Sprintf("%X (%d bytes)", tx.Hash(), len(tx))
  899. }
  900. return fmt.Sprintf(`Data{
  901. %s %v
  902. %s}#%v`,
  903. indent, strings.Join(txStrings, "\n"+indent+" "),
  904. indent, data.hash)
  905. }
  906. // ToProto converts Data to protobuf
  907. func (data *Data) ToProto() tmproto.Data {
  908. tp := new(tmproto.Data)
  909. if len(data.Txs) > 0 {
  910. txBzs := make([][]byte, len(data.Txs))
  911. for i := range data.Txs {
  912. txBzs[i] = data.Txs[i]
  913. }
  914. tp.Txs = txBzs
  915. }
  916. return *tp
  917. }
  918. // DataFromProto takes a protobuf representation of Data &
  919. // returns the native type.
  920. func DataFromProto(dp *tmproto.Data) (Data, error) {
  921. if dp == nil {
  922. return Data{}, errors.New("nil data")
  923. }
  924. data := new(Data)
  925. if len(dp.Txs) > 0 {
  926. txBzs := make(Txs, len(dp.Txs))
  927. for i := range dp.Txs {
  928. txBzs[i] = Tx(dp.Txs[i])
  929. }
  930. data.Txs = txBzs
  931. } else {
  932. data.Txs = Txs{}
  933. }
  934. return *data, nil
  935. }
  936. //-----------------------------------------------------------------------------
  937. // EvidenceData contains any evidence of malicious wrong-doing by validators
  938. type EvidenceData struct {
  939. Evidence EvidenceList `json:"evidence"`
  940. // Volatile. Used as cache
  941. hash tmbytes.HexBytes
  942. byteSize int64
  943. }
  944. // Hash returns the hash of the data.
  945. func (data *EvidenceData) Hash() tmbytes.HexBytes {
  946. if data.hash == nil {
  947. data.hash = data.Evidence.Hash()
  948. }
  949. return data.hash
  950. }
  951. // ByteSize returns the total byte size of all the evidence
  952. func (data *EvidenceData) ByteSize() int64 {
  953. if data.byteSize == 0 && len(data.Evidence) != 0 {
  954. pb, err := data.ToProto()
  955. if err != nil {
  956. panic(err)
  957. }
  958. data.byteSize = int64(pb.Size())
  959. }
  960. return data.byteSize
  961. }
  962. // StringIndented returns a string representation of the evidence.
  963. func (data *EvidenceData) StringIndented(indent string) string {
  964. if data == nil {
  965. return "nil-Evidence"
  966. }
  967. evStrings := make([]string, tmmath.MinInt(len(data.Evidence), 21))
  968. for i, ev := range data.Evidence {
  969. if i == 20 {
  970. evStrings[i] = fmt.Sprintf("... (%v total)", len(data.Evidence))
  971. break
  972. }
  973. evStrings[i] = fmt.Sprintf("Evidence:%v", ev)
  974. }
  975. return fmt.Sprintf(`EvidenceData{
  976. %s %v
  977. %s}#%v`,
  978. indent, strings.Join(evStrings, "\n"+indent+" "),
  979. indent, data.hash)
  980. }
  981. // ToProto converts EvidenceData to protobuf
  982. func (data *EvidenceData) ToProto() (*tmproto.EvidenceList, error) {
  983. if data == nil {
  984. return nil, errors.New("nil evidence data")
  985. }
  986. evi := new(tmproto.EvidenceList)
  987. eviBzs := make([]tmproto.Evidence, len(data.Evidence))
  988. for i := range data.Evidence {
  989. protoEvi, err := EvidenceToProto(data.Evidence[i])
  990. if err != nil {
  991. return nil, err
  992. }
  993. eviBzs[i] = *protoEvi
  994. }
  995. evi.Evidence = eviBzs
  996. return evi, nil
  997. }
  998. // FromProto sets a protobuf EvidenceData to the given pointer.
  999. func (data *EvidenceData) FromProto(eviData *tmproto.EvidenceList) error {
  1000. if eviData == nil {
  1001. return errors.New("nil evidenceData")
  1002. }
  1003. eviBzs := make(EvidenceList, len(eviData.Evidence))
  1004. for i := range eviData.Evidence {
  1005. evi, err := EvidenceFromProto(&eviData.Evidence[i])
  1006. if err != nil {
  1007. return err
  1008. }
  1009. eviBzs[i] = evi
  1010. }
  1011. data.Evidence = eviBzs
  1012. data.byteSize = int64(eviData.Size())
  1013. return nil
  1014. }
  1015. //--------------------------------------------------------------------------------
  1016. // BlockID
  1017. type BlockID struct {
  1018. Hash tmbytes.HexBytes `json:"hash"`
  1019. PartSetHeader PartSetHeader `json:"parts"`
  1020. }
  1021. // Equals returns true if the BlockID matches the given BlockID
  1022. func (blockID BlockID) Equals(other BlockID) bool {
  1023. return bytes.Equal(blockID.Hash, other.Hash) &&
  1024. blockID.PartSetHeader.Equals(other.PartSetHeader)
  1025. }
  1026. // Key returns a machine-readable string representation of the BlockID
  1027. func (blockID BlockID) Key() string {
  1028. pbph := blockID.PartSetHeader.ToProto()
  1029. bz, err := pbph.Marshal()
  1030. if err != nil {
  1031. panic(err)
  1032. }
  1033. return string(blockID.Hash) + string(bz)
  1034. }
  1035. // ValidateBasic performs basic validation.
  1036. func (blockID BlockID) ValidateBasic() error {
  1037. // Hash can be empty in case of POLBlockID in Proposal.
  1038. if err := ValidateHash(blockID.Hash); err != nil {
  1039. return fmt.Errorf("wrong Hash")
  1040. }
  1041. if err := blockID.PartSetHeader.ValidateBasic(); err != nil {
  1042. return fmt.Errorf("wrong PartSetHeader: %v", err)
  1043. }
  1044. return nil
  1045. }
  1046. // IsZero returns true if this is the BlockID of a nil block.
  1047. func (blockID BlockID) IsZero() bool {
  1048. return len(blockID.Hash) == 0 &&
  1049. blockID.PartSetHeader.IsZero()
  1050. }
  1051. // IsComplete returns true if this is a valid BlockID of a non-nil block.
  1052. func (blockID BlockID) IsComplete() bool {
  1053. return len(blockID.Hash) == tmhash.Size &&
  1054. blockID.PartSetHeader.Total > 0 &&
  1055. len(blockID.PartSetHeader.Hash) == tmhash.Size
  1056. }
  1057. // String returns a human readable string representation of the BlockID.
  1058. //
  1059. // 1. hash
  1060. // 2. part set header
  1061. //
  1062. // See PartSetHeader#String
  1063. func (blockID BlockID) String() string {
  1064. return fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartSetHeader)
  1065. }
  1066. // ToProto converts BlockID to protobuf
  1067. func (blockID *BlockID) ToProto() tmproto.BlockID {
  1068. if blockID == nil {
  1069. return tmproto.BlockID{}
  1070. }
  1071. return tmproto.BlockID{
  1072. Hash: blockID.Hash,
  1073. PartSetHeader: blockID.PartSetHeader.ToProto(),
  1074. }
  1075. }
  1076. // FromProto sets a protobuf BlockID to the given pointer.
  1077. // It returns an error if the block id is invalid.
  1078. func BlockIDFromProto(bID *tmproto.BlockID) (*BlockID, error) {
  1079. if bID == nil {
  1080. return nil, errors.New("nil BlockID")
  1081. }
  1082. blockID := new(BlockID)
  1083. ph, err := PartSetHeaderFromProto(&bID.PartSetHeader)
  1084. if err != nil {
  1085. return nil, err
  1086. }
  1087. blockID.PartSetHeader = *ph
  1088. blockID.Hash = bID.Hash
  1089. return blockID, blockID.ValidateBasic()
  1090. }