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. tmversion "github.com/tendermint/tendermint/proto/tendermint/version"
  19. "github.com/tendermint/tendermint/version"
  20. )
  21. const (
  22. // MaxHeaderBytes is a maximum header size.
  23. // NOTE: Because app hash can be of arbitrary size, the header is therefore not
  24. // capped in size and thus this number should be seen as a soft max
  25. MaxHeaderBytes int64 = 626
  26. // MaxOverheadForBlock - maximum overhead to encode a block (up to
  27. // MaxBlockSizeBytes in size) not including it's parts except Data.
  28. // This means it also excludes the overhead for individual transactions.
  29. //
  30. // Uvarint length of MaxBlockSizeBytes: 4 bytes
  31. // 2 fields (2 embedded): 2 bytes
  32. // Uvarint length of Data.Txs: 4 bytes
  33. // Data.Txs field: 1 byte
  34. MaxOverheadForBlock int64 = 11
  35. )
  36. // Block defines the atomic unit of a Tendermint blockchain.
  37. type Block struct {
  38. mtx tmsync.Mutex
  39. Header `json:"header"`
  40. Data `json:"data"`
  41. Evidence EvidenceData `json:"evidence"`
  42. LastCommit *Commit `json:"last_commit"`
  43. }
  44. // ValidateBasic performs basic validation that doesn't involve state data.
  45. // It checks the internal consistency of the block.
  46. // Further validation is done using state#ValidateBlock.
  47. func (b *Block) ValidateBasic() error {
  48. if b == nil {
  49. return errors.New("nil block")
  50. }
  51. b.mtx.Lock()
  52. defer b.mtx.Unlock()
  53. if err := b.Header.ValidateBasic(); err != nil {
  54. return fmt.Errorf("invalid header: %w", err)
  55. }
  56. // Validate the last commit and its hash.
  57. if b.LastCommit == nil {
  58. return errors.New("nil LastCommit")
  59. }
  60. if err := b.LastCommit.ValidateBasic(); err != nil {
  61. return fmt.Errorf("wrong LastCommit: %v", err)
  62. }
  63. if w, g := b.LastCommit.Hash(), b.LastCommitHash; !bytes.Equal(w, g) {
  64. return fmt.Errorf("wrong Header.LastCommitHash. Expected %X, got %X", w, g)
  65. }
  66. // NOTE: b.Data.Txs may be nil, but b.Data.Hash() still works fine.
  67. if w, g := b.Data.Hash(), b.DataHash; !bytes.Equal(w, g) {
  68. return fmt.Errorf("wrong Header.DataHash. Expected %X, got %X", w, g)
  69. }
  70. // NOTE: b.Evidence.Evidence may be nil, but we're just looping.
  71. for i, ev := range b.Evidence.Evidence {
  72. if err := ev.ValidateBasic(); err != nil {
  73. return fmt.Errorf("invalid evidence (#%d): %v", i, err)
  74. }
  75. }
  76. if w, g := b.Evidence.Hash(), b.EvidenceHash; !bytes.Equal(w, g) {
  77. return fmt.Errorf("wrong Header.EvidenceHash. Expected %X, got %X", w, g)
  78. }
  79. return nil
  80. }
  81. // fillHeader fills in any remaining header fields that are a function of the block data
  82. func (b *Block) fillHeader() {
  83. if b.LastCommitHash == nil {
  84. b.LastCommitHash = b.LastCommit.Hash()
  85. }
  86. if b.DataHash == nil {
  87. b.DataHash = b.Data.Hash()
  88. }
  89. if b.EvidenceHash == nil {
  90. b.EvidenceHash = b.Evidence.Hash()
  91. }
  92. }
  93. // Hash computes and returns the block hash.
  94. // If the block is incomplete, block hash is nil for safety.
  95. func (b *Block) Hash() tmbytes.HexBytes {
  96. if b == nil {
  97. return nil
  98. }
  99. b.mtx.Lock()
  100. defer b.mtx.Unlock()
  101. if b.LastCommit == nil {
  102. return nil
  103. }
  104. b.fillHeader()
  105. return b.Header.Hash()
  106. }
  107. // MakePartSet returns a PartSet containing parts of a serialized block.
  108. // This is the form in which the block is gossipped to peers.
  109. // CONTRACT: partSize is greater than zero.
  110. func (b *Block) MakePartSet(partSize uint32) *PartSet {
  111. if b == nil {
  112. return nil
  113. }
  114. b.mtx.Lock()
  115. defer b.mtx.Unlock()
  116. pbb, err := b.ToProto()
  117. if err != nil {
  118. panic(err)
  119. }
  120. bz, err := proto.Marshal(pbb)
  121. if err != nil {
  122. panic(err)
  123. }
  124. return NewPartSetFromData(bz, partSize)
  125. }
  126. // HashesTo is a convenience function that checks if a block hashes to the given argument.
  127. // Returns false if the block is nil or the hash is empty.
  128. func (b *Block) HashesTo(hash []byte) bool {
  129. if len(hash) == 0 {
  130. return false
  131. }
  132. if b == nil {
  133. return false
  134. }
  135. return bytes.Equal(b.Hash(), hash)
  136. }
  137. // Size returns size of the block in bytes.
  138. func (b *Block) Size() int {
  139. pbb, err := b.ToProto()
  140. if err != nil {
  141. return 0
  142. }
  143. return pbb.Size()
  144. }
  145. // String returns a string representation of the block
  146. //
  147. // See StringIndented.
  148. func (b *Block) String() string {
  149. return b.StringIndented("")
  150. }
  151. // StringIndented returns an indented String.
  152. //
  153. // Header
  154. // Data
  155. // Evidence
  156. // LastCommit
  157. // Hash
  158. func (b *Block) StringIndented(indent string) string {
  159. if b == nil {
  160. return "nil-Block"
  161. }
  162. return fmt.Sprintf(`Block{
  163. %s %v
  164. %s %v
  165. %s %v
  166. %s %v
  167. %s}#%v`,
  168. indent, b.Header.StringIndented(indent+" "),
  169. indent, b.Data.StringIndented(indent+" "),
  170. indent, b.Evidence.StringIndented(indent+" "),
  171. indent, b.LastCommit.StringIndented(indent+" "),
  172. indent, b.Hash())
  173. }
  174. // StringShort returns a shortened string representation of the block.
  175. func (b *Block) StringShort() string {
  176. if b == nil {
  177. return "nil-Block"
  178. }
  179. return fmt.Sprintf("Block#%X", b.Hash())
  180. }
  181. // ToProto converts Block to protobuf
  182. func (b *Block) ToProto() (*tmproto.Block, error) {
  183. if b == nil {
  184. return nil, errors.New("nil Block")
  185. }
  186. pb := new(tmproto.Block)
  187. pb.Header = *b.Header.ToProto()
  188. pb.LastCommit = b.LastCommit.ToProto()
  189. pb.Data = b.Data.ToProto()
  190. protoEvidence, err := b.Evidence.ToProto()
  191. if err != nil {
  192. return nil, err
  193. }
  194. pb.Evidence = *protoEvidence
  195. return pb, nil
  196. }
  197. // FromProto sets a protobuf Block to the given pointer.
  198. // It returns an error if the block is invalid.
  199. func BlockFromProto(bp *tmproto.Block) (*Block, error) {
  200. if bp == nil {
  201. return nil, errors.New("nil block")
  202. }
  203. b := new(Block)
  204. h, err := HeaderFromProto(&bp.Header)
  205. if err != nil {
  206. return nil, err
  207. }
  208. b.Header = h
  209. data, err := DataFromProto(&bp.Data)
  210. if err != nil {
  211. return nil, err
  212. }
  213. b.Data = data
  214. if err := b.Evidence.FromProto(&bp.Evidence); err != nil {
  215. return nil, err
  216. }
  217. if bp.LastCommit != nil {
  218. lc, err := CommitFromProto(bp.LastCommit)
  219. if err != nil {
  220. return nil, err
  221. }
  222. b.LastCommit = lc
  223. }
  224. return b, b.ValidateBasic()
  225. }
  226. //-----------------------------------------------------------------------------
  227. // MaxDataBytes returns the maximum size of block's data.
  228. //
  229. // XXX: Panics on negative result.
  230. func MaxDataBytes(maxBytes, evidenceBytes int64, valsCount int) int64 {
  231. maxDataBytes := maxBytes -
  232. MaxOverheadForBlock -
  233. MaxHeaderBytes -
  234. MaxCommitBytes(valsCount) -
  235. evidenceBytes
  236. if maxDataBytes < 0 {
  237. panic(fmt.Sprintf(
  238. "Negative MaxDataBytes. Block.MaxBytes=%d is too small to accommodate header&lastCommit&evidence=%d",
  239. maxBytes,
  240. -(maxDataBytes - maxBytes),
  241. ))
  242. }
  243. return maxDataBytes
  244. }
  245. // MaxDataBytesNoEvidence returns the maximum size of block's data when
  246. // evidence count is unknown. MaxEvidencePerBlock will be used for the size
  247. // of evidence.
  248. //
  249. // XXX: Panics on negative result.
  250. func MaxDataBytesNoEvidence(maxBytes int64, valsCount int) int64 {
  251. maxDataBytes := maxBytes -
  252. MaxOverheadForBlock -
  253. MaxHeaderBytes -
  254. MaxCommitBytes(valsCount)
  255. if maxDataBytes < 0 {
  256. panic(fmt.Sprintf(
  257. "Negative MaxDataBytesUnknownEvidence. Block.MaxBytes=%d is too small to accommodate header&lastCommit&evidence=%d",
  258. maxBytes,
  259. -(maxDataBytes - maxBytes),
  260. ))
  261. }
  262. return maxDataBytes
  263. }
  264. // MakeBlock returns a new block with an empty header, except what can be
  265. // computed from itself.
  266. // It populates the same set of fields validated by ValidateBasic.
  267. func MakeBlock(height int64, txs []Tx, lastCommit *Commit, evidence []Evidence) *Block {
  268. block := &Block{
  269. Header: Header{
  270. Version: tmversion.Consensus{Block: version.BlockProtocol, App: 0},
  271. Height: height,
  272. },
  273. Data: Data{
  274. Txs: txs,
  275. },
  276. Evidence: EvidenceData{Evidence: evidence},
  277. LastCommit: lastCommit,
  278. }
  279. block.fillHeader()
  280. return block
  281. }
  282. //-----------------------------------------------------------------------------
  283. // Header defines the structure of a Tendermint block header.
  284. // NOTE: changes to the Header should be duplicated in:
  285. // - header.Hash()
  286. // - abci.Header
  287. // - https://github.com/tendermint/spec/blob/master/spec/blockchain/blockchain.md
  288. type Header struct {
  289. // basic block info
  290. Version tmversion.Consensus `json:"version"`
  291. ChainID string `json:"chain_id"`
  292. Height int64 `json:"height"`
  293. Time time.Time `json:"time"`
  294. // prev block info
  295. LastBlockID BlockID `json:"last_block_id"`
  296. // hashes of block data
  297. LastCommitHash tmbytes.HexBytes `json:"last_commit_hash"` // commit from validators from the last block
  298. DataHash tmbytes.HexBytes `json:"data_hash"` // transactions
  299. // hashes from the app output from the prev block
  300. ValidatorsHash tmbytes.HexBytes `json:"validators_hash"` // validators for the current block
  301. NextValidatorsHash tmbytes.HexBytes `json:"next_validators_hash"` // validators for the next block
  302. ConsensusHash tmbytes.HexBytes `json:"consensus_hash"` // consensus params for current block
  303. AppHash tmbytes.HexBytes `json:"app_hash"` // state after txs from the previous block
  304. // root hash of all results from the txs from the previous block
  305. LastResultsHash tmbytes.HexBytes `json:"last_results_hash"`
  306. // consensus info
  307. EvidenceHash tmbytes.HexBytes `json:"evidence_hash"` // evidence included in the block
  308. ProposerAddress Address `json:"proposer_address"` // original proposer of the block
  309. }
  310. // Populate the Header with state-derived data.
  311. // Call this after MakeBlock to complete the Header.
  312. func (h *Header) Populate(
  313. version tmversion.Consensus, chainID string,
  314. timestamp time.Time, lastBlockID BlockID,
  315. valHash, nextValHash []byte,
  316. consensusHash, appHash, lastResultsHash []byte,
  317. proposerAddress Address,
  318. ) {
  319. h.Version = version
  320. h.ChainID = chainID
  321. h.Time = timestamp
  322. h.LastBlockID = lastBlockID
  323. h.ValidatorsHash = valHash
  324. h.NextValidatorsHash = nextValHash
  325. h.ConsensusHash = consensusHash
  326. h.AppHash = appHash
  327. h.LastResultsHash = lastResultsHash
  328. h.ProposerAddress = proposerAddress
  329. }
  330. // ValidateBasic performs stateless validation on a Header returning an error
  331. // if any validation fails.
  332. //
  333. // NOTE: Timestamp validation is subtle and handled elsewhere.
  334. func (h Header) ValidateBasic() error {
  335. if h.Version.Block != version.BlockProtocol {
  336. return fmt.Errorf("block protocol is incorrect: got: %d, want: %d ", h.Version.Block, version.BlockProtocol)
  337. }
  338. if len(h.ChainID) > MaxChainIDLen {
  339. return fmt.Errorf("chainID is too long; got: %d, max: %d", len(h.ChainID), MaxChainIDLen)
  340. }
  341. if h.Height < 0 {
  342. return errors.New("negative Height")
  343. } else if h.Height == 0 {
  344. return errors.New("zero Height")
  345. }
  346. if err := h.LastBlockID.ValidateBasic(); err != nil {
  347. return fmt.Errorf("wrong LastBlockID: %w", err)
  348. }
  349. if err := ValidateHash(h.LastCommitHash); err != nil {
  350. return fmt.Errorf("wrong LastCommitHash: %v", err)
  351. }
  352. if err := ValidateHash(h.DataHash); err != nil {
  353. return fmt.Errorf("wrong DataHash: %v", err)
  354. }
  355. if err := ValidateHash(h.EvidenceHash); err != nil {
  356. return fmt.Errorf("wrong EvidenceHash: %v", err)
  357. }
  358. if len(h.ProposerAddress) != crypto.AddressSize {
  359. return fmt.Errorf(
  360. "invalid ProposerAddress length; got: %d, expected: %d",
  361. len(h.ProposerAddress), crypto.AddressSize,
  362. )
  363. }
  364. // Basic validation of hashes related to application data.
  365. // Will validate fully against state in state#ValidateBlock.
  366. if err := ValidateHash(h.ValidatorsHash); err != nil {
  367. return fmt.Errorf("wrong ValidatorsHash: %v", err)
  368. }
  369. if err := ValidateHash(h.NextValidatorsHash); err != nil {
  370. return fmt.Errorf("wrong NextValidatorsHash: %v", err)
  371. }
  372. if err := ValidateHash(h.ConsensusHash); err != nil {
  373. return fmt.Errorf("wrong ConsensusHash: %v", err)
  374. }
  375. // NOTE: AppHash is arbitrary length
  376. if err := ValidateHash(h.LastResultsHash); err != nil {
  377. return fmt.Errorf("wrong LastResultsHash: %v", err)
  378. }
  379. return nil
  380. }
  381. // Hash returns the hash of the header.
  382. // It computes a Merkle tree from the header fields
  383. // ordered as they appear in the Header.
  384. // Returns nil if ValidatorHash is missing,
  385. // since a Header is not valid unless there is
  386. // a ValidatorsHash (corresponding to the validator set).
  387. func (h *Header) Hash() tmbytes.HexBytes {
  388. if h == nil || len(h.ValidatorsHash) == 0 {
  389. return nil
  390. }
  391. hbz, err := h.Version.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,
  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 = ph.Version
  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. }