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.

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