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.

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