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.

1258 lines
33 KiB

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