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.

1242 lines
32 KiB

max-bytes PR follow-up (#2318) * ReapMaxTxs: return all txs if max is negative this mirrors ReapMaxBytes behavior See https://github.com/tendermint/tendermint/pull/2184#discussion_r214439950 * increase MaxAminoOverheadForBlock tested with: ``` func TestMaxAminoOverheadForBlock(t *testing.T) { maxChainID := "" for i := 0; i < MaxChainIDLen; i++ { maxChainID += "𠜎" } h := Header{ ChainID: maxChainID, Height: 10, Time: time.Now().UTC(), NumTxs: 100, TotalTxs: 200, LastBlockID: makeBlockID(make([]byte, 20), 300, make([]byte, 20)), LastCommitHash: tmhash.Sum([]byte("last_commit_hash")), DataHash: tmhash.Sum([]byte("data_hash")), ValidatorsHash: tmhash.Sum([]byte("validators_hash")), NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")), ConsensusHash: tmhash.Sum([]byte("consensus_hash")), AppHash: tmhash.Sum([]byte("app_hash")), LastResultsHash: tmhash.Sum([]byte("last_results_hash")), EvidenceHash: tmhash.Sum([]byte("evidence_hash")), ProposerAddress: tmhash.Sum([]byte("proposer_address")), } b := Block{ Header: h, Data: Data{Txs: makeTxs(10000, 100)}, Evidence: EvidenceData{}, LastCommit: &Commit{}, } bz, err := cdc.MarshalBinary(b) require.NoError(t, err) assert.Equal(t, MaxHeaderBytes+MaxAminoOverheadForBlock-2, len(bz)-1000000-20000-1) } ``` * fix MaxYYY constants calculation by using math.MaxInt64 See https://github.com/tendermint/tendermint/pull/2184#discussion_r214444244 * pass mempool filter as an option See https://github.com/tendermint/tendermint/pull/2184#discussion_r214445869 * fixes after Dev's comments
6 years ago
max-bytes PR follow-up (#2318) * ReapMaxTxs: return all txs if max is negative this mirrors ReapMaxBytes behavior See https://github.com/tendermint/tendermint/pull/2184#discussion_r214439950 * increase MaxAminoOverheadForBlock tested with: ``` func TestMaxAminoOverheadForBlock(t *testing.T) { maxChainID := "" for i := 0; i < MaxChainIDLen; i++ { maxChainID += "𠜎" } h := Header{ ChainID: maxChainID, Height: 10, Time: time.Now().UTC(), NumTxs: 100, TotalTxs: 200, LastBlockID: makeBlockID(make([]byte, 20), 300, make([]byte, 20)), LastCommitHash: tmhash.Sum([]byte("last_commit_hash")), DataHash: tmhash.Sum([]byte("data_hash")), ValidatorsHash: tmhash.Sum([]byte("validators_hash")), NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")), ConsensusHash: tmhash.Sum([]byte("consensus_hash")), AppHash: tmhash.Sum([]byte("app_hash")), LastResultsHash: tmhash.Sum([]byte("last_results_hash")), EvidenceHash: tmhash.Sum([]byte("evidence_hash")), ProposerAddress: tmhash.Sum([]byte("proposer_address")), } b := Block{ Header: h, Data: Data{Txs: makeTxs(10000, 100)}, Evidence: EvidenceData{}, LastCommit: &Commit{}, } bz, err := cdc.MarshalBinary(b) require.NoError(t, err) assert.Equal(t, MaxHeaderBytes+MaxAminoOverheadForBlock-2, len(bz)-1000000-20000-1) } ``` * fix MaxYYY constants calculation by using math.MaxInt64 See https://github.com/tendermint/tendermint/pull/2184#discussion_r214444244 * pass mempool filter as an option See https://github.com/tendermint/tendermint/pull/2184#discussion_r214445869 * fixes after Dev's comments
6 years ago
10 years ago
10 years ago
7 years ago
7 years ago
7 years ago
7 years ago
10 years ago
11 years ago
  1. package types
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "github.com/gogo/protobuf/proto"
  9. gogotypes "github.com/gogo/protobuf/types"
  10. "github.com/tendermint/tendermint/crypto"
  11. "github.com/tendermint/tendermint/crypto/merkle"
  12. "github.com/tendermint/tendermint/crypto/tmhash"
  13. "github.com/tendermint/tendermint/libs/bits"
  14. tmbytes "github.com/tendermint/tendermint/libs/bytes"
  15. tmmath "github.com/tendermint/tendermint/libs/math"
  16. tmsync "github.com/tendermint/tendermint/libs/sync"
  17. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  18. tmversion "github.com/tendermint/tendermint/proto/tendermint/version"
  19. "github.com/tendermint/tendermint/version"
  20. )
  21. const (
  22. // MaxHeaderBytes is a maximum header size.
  23. MaxHeaderBytes int64 = 626
  24. // MaxOverheadForBlock - maximum overhead to encode a block (up to
  25. // MaxBlockSizeBytes in size) not including it's parts except Data.
  26. // This means it also excludes the overhead for individual transactions.
  27. //
  28. // Uvarint length of MaxBlockSizeBytes: 4 bytes
  29. // 2 fields (2 embedded): 2 bytes
  30. // Uvarint length of Data.Txs: 4 bytes
  31. // Data.Txs field: 1 byte
  32. MaxOverheadForBlock int64 = 11
  33. )
  34. // Block defines the atomic unit of a Tendermint blockchain.
  35. type Block struct {
  36. mtx tmsync.Mutex
  37. Header `json:"header"`
  38. Data `json:"data"`
  39. Evidence EvidenceData `json:"evidence"`
  40. LastCommit *Commit `json:"last_commit"`
  41. }
  42. // ValidateBasic performs basic validation that doesn't involve state data.
  43. // It checks the internal consistency of the block.
  44. // Further validation is done using state#ValidateBlock.
  45. func (b *Block) ValidateBasic() error {
  46. if b == nil {
  47. return errors.New("nil block")
  48. }
  49. b.mtx.Lock()
  50. defer b.mtx.Unlock()
  51. if err := b.Header.ValidateBasic(); err != nil {
  52. return fmt.Errorf("invalid header: %w", err)
  53. }
  54. // Validate the last commit and its hash.
  55. if b.LastCommit == nil {
  56. return errors.New("nil LastCommit")
  57. }
  58. if err := b.LastCommit.ValidateBasic(); err != nil {
  59. return fmt.Errorf("wrong LastCommit: %v", err)
  60. }
  61. if !bytes.Equal(b.LastCommitHash, b.LastCommit.Hash()) {
  62. return fmt.Errorf("wrong Header.LastCommitHash. Expected %v, got %v",
  63. b.LastCommit.Hash(),
  64. b.LastCommitHash,
  65. )
  66. }
  67. // NOTE: b.Data.Txs may be nil, but b.Data.Hash() still works fine.
  68. if !bytes.Equal(b.DataHash, b.Data.Hash()) {
  69. return fmt.Errorf(
  70. "wrong Header.DataHash. Expected %v, got %v",
  71. b.Data.Hash(),
  72. b.DataHash,
  73. )
  74. }
  75. // NOTE: b.Evidence.Evidence may be nil, but we're just looping.
  76. for i, ev := range b.Evidence.Evidence {
  77. if err := ev.ValidateBasic(); err != nil {
  78. return fmt.Errorf("invalid evidence (#%d): %v", i, err)
  79. }
  80. }
  81. if !bytes.Equal(b.EvidenceHash, b.Evidence.Hash()) {
  82. return fmt.Errorf("wrong Header.EvidenceHash. Expected %v, got %v",
  83. b.EvidenceHash,
  84. b.Evidence.Hash(),
  85. )
  86. }
  87. return nil
  88. }
  89. // fillHeader fills in any remaining header fields that are a function of the block data
  90. func (b *Block) fillHeader() {
  91. if b.LastCommitHash == nil {
  92. b.LastCommitHash = b.LastCommit.Hash()
  93. }
  94. if b.DataHash == nil {
  95. b.DataHash = b.Data.Hash()
  96. }
  97. if b.EvidenceHash == nil {
  98. b.EvidenceHash = b.Evidence.Hash()
  99. }
  100. }
  101. // Hash computes and returns the block hash.
  102. // If the block is incomplete, block hash is nil for safety.
  103. func (b *Block) Hash() tmbytes.HexBytes {
  104. if b == nil {
  105. return nil
  106. }
  107. b.mtx.Lock()
  108. defer b.mtx.Unlock()
  109. if b.LastCommit == nil {
  110. return nil
  111. }
  112. b.fillHeader()
  113. return b.Header.Hash()
  114. }
  115. // MakePartSet returns a PartSet containing parts of a serialized block.
  116. // This is the form in which the block is gossipped to peers.
  117. // CONTRACT: partSize is greater than zero.
  118. func (b *Block) MakePartSet(partSize uint32) *PartSet {
  119. if b == nil {
  120. return nil
  121. }
  122. b.mtx.Lock()
  123. defer b.mtx.Unlock()
  124. pbb, err := b.ToProto()
  125. if err != nil {
  126. panic(err)
  127. }
  128. bz, err := proto.Marshal(pbb)
  129. if err != nil {
  130. panic(err)
  131. }
  132. return NewPartSetFromData(bz, partSize)
  133. }
  134. // HashesTo is a convenience function that checks if a block hashes to the given argument.
  135. // Returns false if the block is nil or the hash is empty.
  136. func (b *Block) HashesTo(hash []byte) bool {
  137. if len(hash) == 0 {
  138. return false
  139. }
  140. if b == nil {
  141. return false
  142. }
  143. return bytes.Equal(b.Hash(), hash)
  144. }
  145. // Size returns size of the block in bytes.
  146. func (b *Block) Size() int {
  147. pbb, err := b.ToProto()
  148. if err != nil {
  149. return 0
  150. }
  151. return pbb.Size()
  152. }
  153. // String returns a string representation of the block
  154. //
  155. // See StringIndented.
  156. func (b *Block) String() string {
  157. return b.StringIndented("")
  158. }
  159. // StringIndented returns an indented String.
  160. //
  161. // Header
  162. // Data
  163. // Evidence
  164. // LastCommit
  165. // Hash
  166. func (b *Block) StringIndented(indent string) string {
  167. if b == nil {
  168. return "nil-Block"
  169. }
  170. return fmt.Sprintf(`Block{
  171. %s %v
  172. %s %v
  173. %s %v
  174. %s %v
  175. %s}#%v`,
  176. indent, b.Header.StringIndented(indent+" "),
  177. indent, b.Data.StringIndented(indent+" "),
  178. indent, b.Evidence.StringIndented(indent+" "),
  179. indent, b.LastCommit.StringIndented(indent+" "),
  180. indent, b.Hash())
  181. }
  182. // StringShort returns a shortened string representation of the block.
  183. func (b *Block) StringShort() string {
  184. if b == nil {
  185. return "nil-Block"
  186. }
  187. return fmt.Sprintf("Block#%X", b.Hash())
  188. }
  189. // ToProto converts Block to protobuf
  190. func (b *Block) ToProto() (*tmproto.Block, error) {
  191. if b == nil {
  192. return nil, errors.New("nil Block")
  193. }
  194. pb := new(tmproto.Block)
  195. pb.Header = *b.Header.ToProto()
  196. pb.LastCommit = b.LastCommit.ToProto()
  197. pb.Data = b.Data.ToProto()
  198. protoEvidence, err := b.Evidence.ToProto()
  199. if err != nil {
  200. return nil, err
  201. }
  202. pb.Evidence = *protoEvidence
  203. return pb, nil
  204. }
  205. // FromProto sets a protobuf Block to the given pointer.
  206. // It returns an error if the block is invalid.
  207. func BlockFromProto(bp *tmproto.Block) (*Block, error) {
  208. if bp == nil {
  209. return nil, errors.New("nil block")
  210. }
  211. b := new(Block)
  212. h, err := HeaderFromProto(&bp.Header)
  213. if err != nil {
  214. return nil, err
  215. }
  216. b.Header = h
  217. data, err := DataFromProto(&bp.Data)
  218. if err != nil {
  219. return nil, err
  220. }
  221. b.Data = data
  222. if err := b.Evidence.FromProto(&bp.Evidence); err != nil {
  223. return nil, err
  224. }
  225. if bp.LastCommit != nil {
  226. lc, err := CommitFromProto(bp.LastCommit)
  227. if err != nil {
  228. return nil, err
  229. }
  230. b.LastCommit = lc
  231. }
  232. return b, b.ValidateBasic()
  233. }
  234. //-----------------------------------------------------------------------------
  235. // MaxDataBytes returns the maximum size of block's data.
  236. //
  237. // XXX: Panics on negative result.
  238. func MaxDataBytes(maxBytes int64, valsCount, evidenceCount int) int64 {
  239. maxDataBytes := maxBytes -
  240. MaxOverheadForBlock -
  241. MaxHeaderBytes -
  242. int64(valsCount)*MaxVoteBytes -
  243. int64(evidenceCount)*MaxEvidenceBytes
  244. if maxDataBytes < 0 {
  245. panic(fmt.Sprintf(
  246. "Negative MaxDataBytes. Block.MaxBytes=%d is too small to accommodate header&lastCommit&evidence=%d",
  247. maxBytes,
  248. -(maxDataBytes - maxBytes),
  249. ))
  250. }
  251. return maxDataBytes
  252. }
  253. // MaxDataBytesUnknownEvidence returns the maximum size of block's data when
  254. // evidence count is unknown. MaxEvidencePerBlock will be used for the size
  255. // of evidence.
  256. //
  257. // XXX: Panics on negative result.
  258. func MaxDataBytesUnknownEvidence(maxBytes int64, valsCount int, maxNumEvidence uint32) int64 {
  259. maxEvidenceBytes := int64(maxNumEvidence) * MaxEvidenceBytes
  260. maxDataBytes := maxBytes -
  261. MaxOverheadForBlock -
  262. MaxHeaderBytes -
  263. int64(valsCount)*MaxVoteBytes -
  264. maxEvidenceBytes
  265. if maxDataBytes < 0 {
  266. panic(fmt.Sprintf(
  267. "Negative MaxDataBytesUnknownEvidence. Block.MaxBytes=%d is too small to accommodate header&lastCommit&evidence=%d",
  268. maxBytes,
  269. -(maxDataBytes - maxBytes),
  270. ))
  271. }
  272. return maxDataBytes
  273. }
  274. //-----------------------------------------------------------------------------
  275. // Header defines the structure of a Tendermint block header.
  276. // NOTE: changes to the Header should be duplicated in:
  277. // - header.Hash()
  278. // - abci.Header
  279. // - https://github.com/tendermint/spec/blob/master/spec/blockchain/blockchain.md
  280. type Header struct {
  281. // basic block info
  282. Version tmversion.Consensus `json:"version"`
  283. ChainID string `json:"chain_id"`
  284. Height int64 `json:"height"`
  285. Time time.Time `json:"time"`
  286. // prev block info
  287. LastBlockID BlockID `json:"last_block_id"`
  288. // hashes of block data
  289. LastCommitHash tmbytes.HexBytes `json:"last_commit_hash"` // commit from validators from the last block
  290. DataHash tmbytes.HexBytes `json:"data_hash"` // transactions
  291. // hashes from the app output from the prev block
  292. ValidatorsHash tmbytes.HexBytes `json:"validators_hash"` // validators for the current block
  293. NextValidatorsHash tmbytes.HexBytes `json:"next_validators_hash"` // validators for the next block
  294. ConsensusHash tmbytes.HexBytes `json:"consensus_hash"` // consensus params for current block
  295. AppHash tmbytes.HexBytes `json:"app_hash"` // state after txs from the previous block
  296. // root hash of all results from the txs from the previous block
  297. LastResultsHash tmbytes.HexBytes `json:"last_results_hash"`
  298. // consensus info
  299. EvidenceHash tmbytes.HexBytes `json:"evidence_hash"` // evidence included in the block
  300. ProposerAddress Address `json:"proposer_address"` // original proposer of the block
  301. }
  302. // Populate the Header with state-derived data.
  303. // Call this after MakeBlock to complete the Header.
  304. func (h *Header) Populate(
  305. version tmversion.Consensus, chainID string,
  306. timestamp time.Time, lastBlockID BlockID,
  307. valHash, nextValHash []byte,
  308. consensusHash, appHash, lastResultsHash []byte,
  309. proposerAddress Address,
  310. ) {
  311. h.Version = version
  312. h.ChainID = chainID
  313. h.Time = timestamp
  314. h.LastBlockID = lastBlockID
  315. h.ValidatorsHash = valHash
  316. h.NextValidatorsHash = nextValHash
  317. h.ConsensusHash = consensusHash
  318. h.AppHash = appHash
  319. h.LastResultsHash = lastResultsHash
  320. h.ProposerAddress = proposerAddress
  321. }
  322. // ValidateBasic performs stateless validation on a Header returning an error
  323. // if any validation fails.
  324. //
  325. // NOTE: Timestamp validation is subtle and handled elsewhere.
  326. func (h Header) ValidateBasic() error {
  327. if h.Version.Block != version.BlockProtocol {
  328. return fmt.Errorf("block protocol is incorrect: got: %d, want: %d ", h.Version.Block, version.BlockProtocol)
  329. }
  330. if len(h.ChainID) > MaxChainIDLen {
  331. return fmt.Errorf("chainID is too long; got: %d, max: %d", len(h.ChainID), MaxChainIDLen)
  332. }
  333. if h.Height < 0 {
  334. return errors.New("negative Height")
  335. } else if h.Height == 0 {
  336. return errors.New("zero Height")
  337. }
  338. if err := h.LastBlockID.ValidateBasic(); err != nil {
  339. return fmt.Errorf("wrong LastBlockID: %w", err)
  340. }
  341. if err := ValidateHash(h.LastCommitHash); err != nil {
  342. return fmt.Errorf("wrong LastCommitHash: %v", err)
  343. }
  344. if err := ValidateHash(h.DataHash); err != nil {
  345. return fmt.Errorf("wrong DataHash: %v", err)
  346. }
  347. if err := ValidateHash(h.EvidenceHash); err != nil {
  348. return fmt.Errorf("wrong EvidenceHash: %v", err)
  349. }
  350. if len(h.ProposerAddress) != crypto.AddressSize {
  351. return fmt.Errorf(
  352. "invalid ProposerAddress length; got: %d, expected: %d",
  353. len(h.ProposerAddress), crypto.AddressSize,
  354. )
  355. }
  356. // Basic validation of hashes related to application data.
  357. // Will validate fully against state in state#ValidateBlock.
  358. if err := ValidateHash(h.ValidatorsHash); err != nil {
  359. return fmt.Errorf("wrong ValidatorsHash: %v", err)
  360. }
  361. if err := ValidateHash(h.NextValidatorsHash); err != nil {
  362. return fmt.Errorf("wrong NextValidatorsHash: %v", err)
  363. }
  364. if err := ValidateHash(h.ConsensusHash); err != nil {
  365. return fmt.Errorf("wrong ConsensusHash: %v", err)
  366. }
  367. // NOTE: AppHash is arbitrary length
  368. if err := ValidateHash(h.LastResultsHash); err != nil {
  369. return fmt.Errorf("wrong LastResultsHash: %v", err)
  370. }
  371. return nil
  372. }
  373. // Hash returns the hash of the header.
  374. // It computes a Merkle tree from the header fields
  375. // ordered as they appear in the Header.
  376. // Returns nil if ValidatorHash is missing,
  377. // since a Header is not valid unless there is
  378. // a ValidatorsHash (corresponding to the validator set).
  379. func (h *Header) Hash() tmbytes.HexBytes {
  380. if h == nil || len(h.ValidatorsHash) == 0 {
  381. return nil
  382. }
  383. hbz, err := h.Version.Marshal()
  384. if err != nil {
  385. return nil
  386. }
  387. pbt, err := gogotypes.StdTimeMarshal(h.Time)
  388. if err != nil {
  389. return nil
  390. }
  391. pbbi := h.LastBlockID.ToProto()
  392. bzbi, err := pbbi.Marshal()
  393. if err != nil {
  394. return nil
  395. }
  396. return merkle.HashFromByteSlices([][]byte{
  397. hbz,
  398. cdcEncode(h.ChainID),
  399. cdcEncode(h.Height),
  400. pbt,
  401. bzbi,
  402. cdcEncode(h.LastCommitHash),
  403. cdcEncode(h.DataHash),
  404. cdcEncode(h.ValidatorsHash),
  405. cdcEncode(h.NextValidatorsHash),
  406. cdcEncode(h.ConsensusHash),
  407. cdcEncode(h.AppHash),
  408. cdcEncode(h.LastResultsHash),
  409. cdcEncode(h.EvidenceHash),
  410. cdcEncode(h.ProposerAddress),
  411. })
  412. }
  413. // StringIndented returns an indented string representation of the header.
  414. func (h *Header) StringIndented(indent string) string {
  415. if h == nil {
  416. return "nil-Header"
  417. }
  418. return fmt.Sprintf(`Header{
  419. %s Version: %v
  420. %s ChainID: %v
  421. %s Height: %v
  422. %s Time: %v
  423. %s LastBlockID: %v
  424. %s LastCommit: %v
  425. %s Data: %v
  426. %s Validators: %v
  427. %s NextValidators: %v
  428. %s App: %v
  429. %s Consensus: %v
  430. %s Results: %v
  431. %s Evidence: %v
  432. %s Proposer: %v
  433. %s}#%v`,
  434. indent, h.Version,
  435. indent, h.ChainID,
  436. indent, h.Height,
  437. indent, h.Time,
  438. indent, h.LastBlockID,
  439. indent, h.LastCommitHash,
  440. indent, h.DataHash,
  441. indent, h.ValidatorsHash,
  442. indent, h.NextValidatorsHash,
  443. indent, h.AppHash,
  444. indent, h.ConsensusHash,
  445. indent, h.LastResultsHash,
  446. indent, h.EvidenceHash,
  447. indent, h.ProposerAddress,
  448. indent, h.Hash())
  449. }
  450. // ToProto converts Header to protobuf
  451. func (h *Header) ToProto() *tmproto.Header {
  452. if h == nil {
  453. return nil
  454. }
  455. return &tmproto.Header{
  456. Version: h.Version,
  457. ChainID: h.ChainID,
  458. Height: h.Height,
  459. Time: h.Time,
  460. LastBlockId: h.LastBlockID.ToProto(),
  461. ValidatorsHash: h.ValidatorsHash,
  462. NextValidatorsHash: h.NextValidatorsHash,
  463. ConsensusHash: h.ConsensusHash,
  464. AppHash: h.AppHash,
  465. DataHash: h.DataHash,
  466. EvidenceHash: h.EvidenceHash,
  467. LastResultsHash: h.LastResultsHash,
  468. LastCommitHash: h.LastCommitHash,
  469. ProposerAddress: h.ProposerAddress,
  470. }
  471. }
  472. // FromProto sets a protobuf Header to the given pointer.
  473. // It returns an error if the header is invalid.
  474. func HeaderFromProto(ph *tmproto.Header) (Header, error) {
  475. if ph == nil {
  476. return Header{}, errors.New("nil Header")
  477. }
  478. h := new(Header)
  479. bi, err := BlockIDFromProto(&ph.LastBlockId)
  480. if err != nil {
  481. return Header{}, err
  482. }
  483. h.Version = ph.Version
  484. h.ChainID = ph.ChainID
  485. h.Height = ph.Height
  486. h.Time = ph.Time
  487. h.Height = ph.Height
  488. h.LastBlockID = *bi
  489. h.ValidatorsHash = ph.ValidatorsHash
  490. h.NextValidatorsHash = ph.NextValidatorsHash
  491. h.ConsensusHash = ph.ConsensusHash
  492. h.AppHash = ph.AppHash
  493. h.DataHash = ph.DataHash
  494. h.EvidenceHash = ph.EvidenceHash
  495. h.LastResultsHash = ph.LastResultsHash
  496. h.LastCommitHash = ph.LastCommitHash
  497. h.ProposerAddress = ph.ProposerAddress
  498. return *h, h.ValidateBasic()
  499. }
  500. //-------------------------------------
  501. // BlockIDFlag indicates which BlockID the signature is for.
  502. type BlockIDFlag byte
  503. const (
  504. // BlockIDFlagAbsent - no vote was received from a validator.
  505. BlockIDFlagAbsent BlockIDFlag = iota + 1
  506. // BlockIDFlagCommit - voted for the Commit.BlockID.
  507. BlockIDFlagCommit
  508. // BlockIDFlagNil - voted for nil.
  509. BlockIDFlagNil
  510. )
  511. // CommitSig is a part of the Vote included in a Commit.
  512. type CommitSig struct {
  513. BlockIDFlag BlockIDFlag `json:"block_id_flag"`
  514. ValidatorAddress Address `json:"validator_address"`
  515. Timestamp time.Time `json:"timestamp"`
  516. Signature []byte `json:"signature"`
  517. }
  518. // NewCommitSigForBlock returns new CommitSig with BlockIDFlagCommit.
  519. func NewCommitSigForBlock(signature []byte, valAddr Address, ts time.Time) CommitSig {
  520. return CommitSig{
  521. BlockIDFlag: BlockIDFlagCommit,
  522. ValidatorAddress: valAddr,
  523. Timestamp: ts,
  524. Signature: signature,
  525. }
  526. }
  527. // ForBlock returns true if CommitSig is for the block.
  528. func (cs CommitSig) ForBlock() bool {
  529. return cs.BlockIDFlag == BlockIDFlagCommit
  530. }
  531. // NewCommitSigAbsent returns new CommitSig with BlockIDFlagAbsent. Other
  532. // fields are all empty.
  533. func NewCommitSigAbsent() CommitSig {
  534. return CommitSig{
  535. BlockIDFlag: BlockIDFlagAbsent,
  536. }
  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. if commit.hash != nil {
  829. c.Hash = commit.hash
  830. }
  831. c.BitArray = commit.bitArray.ToProto()
  832. return c
  833. }
  834. // FromProto sets a protobuf Commit to the given pointer.
  835. // It returns an error if the commit is invalid.
  836. func CommitFromProto(cp *tmproto.Commit) (*Commit, error) {
  837. if cp == nil {
  838. return nil, errors.New("nil Commit")
  839. }
  840. var (
  841. commit = new(Commit)
  842. bitArray *bits.BitArray
  843. )
  844. bi, err := BlockIDFromProto(&cp.BlockID)
  845. if err != nil {
  846. return nil, err
  847. }
  848. bitArray.FromProto(cp.BitArray)
  849. sigs := make([]CommitSig, len(cp.Signatures))
  850. for i := range cp.Signatures {
  851. if err := sigs[i].FromProto(cp.Signatures[i]); err != nil {
  852. return nil, err
  853. }
  854. }
  855. commit.Signatures = sigs
  856. commit.Height = cp.Height
  857. commit.Round = cp.Round
  858. commit.BlockID = *bi
  859. commit.hash = cp.Hash
  860. commit.bitArray = bitArray
  861. return commit, commit.ValidateBasic()
  862. }
  863. //-----------------------------------------------------------------------------
  864. // Data contains the set of transactions included in the block
  865. type Data struct {
  866. // Txs that will be applied by state @ block.Height+1.
  867. // NOTE: not all txs here are valid. We're just agreeing on the order first.
  868. // This means that block.AppHash does not include these txs.
  869. Txs Txs `json:"txs"`
  870. // Volatile
  871. hash tmbytes.HexBytes
  872. }
  873. // Hash returns the hash of the data
  874. func (data *Data) Hash() tmbytes.HexBytes {
  875. if data == nil {
  876. return (Txs{}).Hash()
  877. }
  878. if data.hash == nil {
  879. data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs
  880. }
  881. return data.hash
  882. }
  883. // StringIndented returns an indented string representation of the transactions.
  884. func (data *Data) StringIndented(indent string) string {
  885. if data == nil {
  886. return "nil-Data"
  887. }
  888. txStrings := make([]string, tmmath.MinInt(len(data.Txs), 21))
  889. for i, tx := range data.Txs {
  890. if i == 20 {
  891. txStrings[i] = fmt.Sprintf("... (%v total)", len(data.Txs))
  892. break
  893. }
  894. txStrings[i] = fmt.Sprintf("%X (%d bytes)", tx.Hash(), len(tx))
  895. }
  896. return fmt.Sprintf(`Data{
  897. %s %v
  898. %s}#%v`,
  899. indent, strings.Join(txStrings, "\n"+indent+" "),
  900. indent, data.hash)
  901. }
  902. // ToProto converts Data to protobuf
  903. func (data *Data) ToProto() tmproto.Data {
  904. tp := new(tmproto.Data)
  905. if len(data.Txs) > 0 {
  906. txBzs := make([][]byte, len(data.Txs))
  907. for i := range data.Txs {
  908. txBzs[i] = data.Txs[i]
  909. }
  910. tp.Txs = txBzs
  911. }
  912. if data.hash != nil {
  913. tp.Hash = data.hash
  914. }
  915. return *tp
  916. }
  917. // DataFromProto takes a protobuf representation of Data &
  918. // returns the native type.
  919. func DataFromProto(dp *tmproto.Data) (Data, error) {
  920. if dp == nil {
  921. return Data{}, errors.New("nil data")
  922. }
  923. data := new(Data)
  924. if len(dp.Txs) > 0 {
  925. txBzs := make(Txs, len(dp.Txs))
  926. for i := range dp.Txs {
  927. txBzs[i] = Tx(dp.Txs[i])
  928. }
  929. data.Txs = txBzs
  930. } else {
  931. data.Txs = Txs{}
  932. }
  933. data.hash = dp.Hash
  934. return *data, nil
  935. }
  936. //-----------------------------------------------------------------------------
  937. // EvidenceData contains any evidence of malicious wrong-doing by validators
  938. type EvidenceData struct {
  939. Evidence EvidenceList `json:"evidence"`
  940. // Volatile
  941. hash tmbytes.HexBytes
  942. }
  943. // Hash returns the hash of the data.
  944. func (data *EvidenceData) Hash() tmbytes.HexBytes {
  945. if data.hash == nil {
  946. data.hash = data.Evidence.Hash()
  947. }
  948. return data.hash
  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. if data.hash != nil {
  985. evi.Hash = data.hash
  986. }
  987. return evi, nil
  988. }
  989. // FromProto sets a protobuf EvidenceData to the given pointer.
  990. func (data *EvidenceData) FromProto(eviData *tmproto.EvidenceData) error {
  991. if eviData == nil {
  992. return errors.New("nil evidenceData")
  993. }
  994. eviBzs := make(EvidenceList, len(eviData.Evidence))
  995. for i := range eviData.Evidence {
  996. evi, err := EvidenceFromProto(&eviData.Evidence[i])
  997. if err != nil {
  998. return err
  999. }
  1000. eviBzs[i] = evi
  1001. }
  1002. data.Evidence = eviBzs
  1003. data.hash = eviData.GetHash()
  1004. return nil
  1005. }
  1006. //--------------------------------------------------------------------------------
  1007. // BlockID
  1008. type BlockID struct {
  1009. Hash tmbytes.HexBytes `json:"hash"`
  1010. PartSetHeader PartSetHeader `json:"parts"`
  1011. }
  1012. // Equals returns true if the BlockID matches the given BlockID
  1013. func (blockID BlockID) Equals(other BlockID) bool {
  1014. return bytes.Equal(blockID.Hash, other.Hash) &&
  1015. blockID.PartSetHeader.Equals(other.PartSetHeader)
  1016. }
  1017. // Key returns a machine-readable string representation of the BlockID
  1018. func (blockID BlockID) Key() string {
  1019. pbph := blockID.PartSetHeader.ToProto()
  1020. bz, err := pbph.Marshal()
  1021. if err != nil {
  1022. panic(err)
  1023. }
  1024. return string(blockID.Hash) + string(bz)
  1025. }
  1026. // ValidateBasic performs basic validation.
  1027. func (blockID BlockID) ValidateBasic() error {
  1028. // Hash can be empty in case of POLBlockID in Proposal.
  1029. if err := ValidateHash(blockID.Hash); err != nil {
  1030. return fmt.Errorf("wrong Hash")
  1031. }
  1032. if err := blockID.PartSetHeader.ValidateBasic(); err != nil {
  1033. return fmt.Errorf("wrong PartSetHeader: %v", err)
  1034. }
  1035. return nil
  1036. }
  1037. // IsZero returns true if this is the BlockID of a nil block.
  1038. func (blockID BlockID) IsZero() bool {
  1039. return len(blockID.Hash) == 0 &&
  1040. blockID.PartSetHeader.IsZero()
  1041. }
  1042. // IsComplete returns true if this is a valid BlockID of a non-nil block.
  1043. func (blockID BlockID) IsComplete() bool {
  1044. return len(blockID.Hash) == tmhash.Size &&
  1045. blockID.PartSetHeader.Total > 0 &&
  1046. len(blockID.PartSetHeader.Hash) == tmhash.Size
  1047. }
  1048. // String returns a human readable string representation of the BlockID.
  1049. //
  1050. // 1. hash
  1051. // 2. part set header
  1052. //
  1053. // See PartSetHeader#String
  1054. func (blockID BlockID) String() string {
  1055. return fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartSetHeader)
  1056. }
  1057. // ToProto converts BlockID to protobuf
  1058. func (blockID *BlockID) ToProto() tmproto.BlockID {
  1059. if blockID == nil {
  1060. return tmproto.BlockID{}
  1061. }
  1062. return tmproto.BlockID{
  1063. Hash: blockID.Hash,
  1064. PartSetHeader: blockID.PartSetHeader.ToProto(),
  1065. }
  1066. }
  1067. // FromProto sets a protobuf BlockID to the given pointer.
  1068. // It returns an error if the block id is invalid.
  1069. func BlockIDFromProto(bID *tmproto.BlockID) (*BlockID, error) {
  1070. if bID == nil {
  1071. return nil, errors.New("nil BlockID")
  1072. }
  1073. blockID := new(BlockID)
  1074. ph, err := PartSetHeaderFromProto(&bID.PartSetHeader)
  1075. if err != nil {
  1076. return nil, err
  1077. }
  1078. blockID.PartSetHeader = *ph
  1079. blockID.Hash = bID.Hash
  1080. return blockID, blockID.ValidateBasic()
  1081. }