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.

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