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.

1223 lines
32 KiB

max-bytes PR follow-up (#2318) * ReapMaxTxs: return all txs if max is negative this mirrors ReapMaxBytes behavior See https://github.com/tendermint/tendermint/pull/2184#discussion_r214439950 * increase MaxAminoOverheadForBlock tested with: ``` func TestMaxAminoOverheadForBlock(t *testing.T) { maxChainID := "" for i := 0; i < MaxChainIDLen; i++ { maxChainID += "𠜎" } h := Header{ ChainID: maxChainID, Height: 10, Time: time.Now().UTC(), NumTxs: 100, TotalTxs: 200, LastBlockID: makeBlockID(make([]byte, 20), 300, make([]byte, 20)), LastCommitHash: tmhash.Sum([]byte("last_commit_hash")), DataHash: tmhash.Sum([]byte("data_hash")), ValidatorsHash: tmhash.Sum([]byte("validators_hash")), NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")), ConsensusHash: tmhash.Sum([]byte("consensus_hash")), AppHash: tmhash.Sum([]byte("app_hash")), LastResultsHash: tmhash.Sum([]byte("last_results_hash")), EvidenceHash: tmhash.Sum([]byte("evidence_hash")), ProposerAddress: tmhash.Sum([]byte("proposer_address")), } b := Block{ Header: h, Data: Data{Txs: makeTxs(10000, 100)}, Evidence: EvidenceData{}, LastCommit: &Commit{}, } bz, err := cdc.MarshalBinary(b) require.NoError(t, err) assert.Equal(t, MaxHeaderBytes+MaxAminoOverheadForBlock-2, len(bz)-1000000-20000-1) } ``` * fix MaxYYY constants calculation by using math.MaxInt64 See https://github.com/tendermint/tendermint/pull/2184#discussion_r214444244 * pass mempool filter as an option See https://github.com/tendermint/tendermint/pull/2184#discussion_r214445869 * fixes after Dev's comments
6 years ago
max-bytes PR follow-up (#2318) * ReapMaxTxs: return all txs if max is negative this mirrors ReapMaxBytes behavior See https://github.com/tendermint/tendermint/pull/2184#discussion_r214439950 * increase MaxAminoOverheadForBlock tested with: ``` func TestMaxAminoOverheadForBlock(t *testing.T) { maxChainID := "" for i := 0; i < MaxChainIDLen; i++ { maxChainID += "𠜎" } h := Header{ ChainID: maxChainID, Height: 10, Time: time.Now().UTC(), NumTxs: 100, TotalTxs: 200, LastBlockID: makeBlockID(make([]byte, 20), 300, make([]byte, 20)), LastCommitHash: tmhash.Sum([]byte("last_commit_hash")), DataHash: tmhash.Sum([]byte("data_hash")), ValidatorsHash: tmhash.Sum([]byte("validators_hash")), NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")), ConsensusHash: tmhash.Sum([]byte("consensus_hash")), AppHash: tmhash.Sum([]byte("app_hash")), LastResultsHash: tmhash.Sum([]byte("last_results_hash")), EvidenceHash: tmhash.Sum([]byte("evidence_hash")), ProposerAddress: tmhash.Sum([]byte("proposer_address")), } b := Block{ Header: h, Data: Data{Txs: makeTxs(10000, 100)}, Evidence: EvidenceData{}, LastCommit: &Commit{}, } bz, err := cdc.MarshalBinary(b) require.NoError(t, err) assert.Equal(t, MaxHeaderBytes+MaxAminoOverheadForBlock-2, len(bz)-1000000-20000-1) } ``` * fix MaxYYY constants calculation by using math.MaxInt64 See https://github.com/tendermint/tendermint/pull/2184#discussion_r214444244 * pass mempool filter as an option See https://github.com/tendermint/tendermint/pull/2184#discussion_r214445869 * fixes after Dev's comments
6 years ago
10 years ago
10 years ago
7 years ago
7 years ago
7 years ago
7 years ago
10 years ago
11 years ago
  1. package types
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "github.com/gogo/protobuf/proto"
  9. gogotypes "github.com/gogo/protobuf/types"
  10. "github.com/tendermint/tendermint/crypto"
  11. "github.com/tendermint/tendermint/crypto/merkle"
  12. "github.com/tendermint/tendermint/crypto/tmhash"
  13. "github.com/tendermint/tendermint/libs/bits"
  14. tmbytes "github.com/tendermint/tendermint/libs/bytes"
  15. tmmath "github.com/tendermint/tendermint/libs/math"
  16. tmsync "github.com/tendermint/tendermint/libs/sync"
  17. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  18. tmversion "github.com/tendermint/tendermint/proto/tendermint/version"
  19. "github.com/tendermint/tendermint/version"
  20. )
  21. const (
  22. // MaxHeaderBytes is a maximum header size.
  23. MaxHeaderBytes int64 = 626
  24. // MaxOverheadForBlock - maximum overhead to encode a block (up to
  25. // MaxBlockSizeBytes in size) not including it's parts except Data.
  26. // This means it also excludes the overhead for individual transactions.
  27. //
  28. // Uvarint length of MaxBlockSizeBytes: 4 bytes
  29. // 2 fields (2 embedded): 2 bytes
  30. // Uvarint length of Data.Txs: 4 bytes
  31. // Data.Txs field: 1 byte
  32. MaxOverheadForBlock int64 = 11
  33. )
  34. // Block defines the atomic unit of a Tendermint blockchain.
  35. type Block struct {
  36. mtx tmsync.Mutex
  37. Header `json:"header"`
  38. Data `json:"data"`
  39. Evidence EvidenceData `json:"evidence"`
  40. LastCommit *Commit `json:"last_commit"`
  41. }
  42. // ValidateBasic performs basic validation that doesn't involve state data.
  43. // It checks the internal consistency of the block.
  44. // Further validation is done using state#ValidateBlock.
  45. func (b *Block) ValidateBasic() error {
  46. if b == nil {
  47. return errors.New("nil block")
  48. }
  49. b.mtx.Lock()
  50. defer b.mtx.Unlock()
  51. if err := b.Header.ValidateBasic(); err != nil {
  52. return fmt.Errorf("invalid header: %w", err)
  53. }
  54. // Validate the last commit and its hash.
  55. if b.LastCommit == nil {
  56. return errors.New("nil LastCommit")
  57. }
  58. if err := b.LastCommit.ValidateBasic(); err != nil {
  59. return fmt.Errorf("wrong LastCommit: %v", err)
  60. }
  61. if w, g := b.LastCommit.Hash(), b.LastCommitHash; !bytes.Equal(w, g) {
  62. return fmt.Errorf("wrong Header.LastCommitHash. Expected %X, got %X", w, g)
  63. }
  64. // NOTE: b.Data.Txs may be nil, but b.Data.Hash() still works fine.
  65. if w, g := b.Data.Hash(), b.DataHash; !bytes.Equal(w, g) {
  66. return fmt.Errorf("wrong Header.DataHash. Expected %X, got %X", w, g)
  67. }
  68. // NOTE: b.Evidence.Evidence may be nil, but we're just looping.
  69. for i, ev := range b.Evidence.Evidence {
  70. if err := ev.ValidateBasic(); err != nil {
  71. return fmt.Errorf("invalid evidence (#%d): %v", i, err)
  72. }
  73. }
  74. if w, g := b.Evidence.Hash(), b.EvidenceHash; !bytes.Equal(w, g) {
  75. return fmt.Errorf("wrong Header.EvidenceHash. Expected %X, got %X", w, g)
  76. }
  77. return nil
  78. }
  79. // fillHeader fills in any remaining header fields that are a function of the block data
  80. func (b *Block) fillHeader() {
  81. if b.LastCommitHash == nil {
  82. b.LastCommitHash = b.LastCommit.Hash()
  83. }
  84. if b.DataHash == nil {
  85. b.DataHash = b.Data.Hash()
  86. }
  87. if b.EvidenceHash == nil {
  88. b.EvidenceHash = b.Evidence.Hash()
  89. }
  90. }
  91. // Hash computes and returns the block hash.
  92. // If the block is incomplete, block hash is nil for safety.
  93. func (b *Block) Hash() tmbytes.HexBytes {
  94. if b == nil {
  95. return nil
  96. }
  97. b.mtx.Lock()
  98. defer b.mtx.Unlock()
  99. if b.LastCommit == nil {
  100. return nil
  101. }
  102. b.fillHeader()
  103. return b.Header.Hash()
  104. }
  105. // MakePartSet returns a PartSet containing parts of a serialized block.
  106. // This is the form in which the block is gossipped to peers.
  107. // CONTRACT: partSize is greater than zero.
  108. func (b *Block) MakePartSet(partSize uint32) *PartSet {
  109. if b == nil {
  110. return nil
  111. }
  112. b.mtx.Lock()
  113. defer b.mtx.Unlock()
  114. pbb, err := b.ToProto()
  115. if err != nil {
  116. panic(err)
  117. }
  118. bz, err := proto.Marshal(pbb)
  119. if err != nil {
  120. panic(err)
  121. }
  122. return NewPartSetFromData(bz, partSize)
  123. }
  124. // HashesTo is a convenience function that checks if a block hashes to the given argument.
  125. // Returns false if the block is nil or the hash is empty.
  126. func (b *Block) HashesTo(hash []byte) bool {
  127. if len(hash) == 0 {
  128. return false
  129. }
  130. if b == nil {
  131. return false
  132. }
  133. return bytes.Equal(b.Hash(), hash)
  134. }
  135. // Size returns size of the block in bytes.
  136. func (b *Block) Size() int {
  137. pbb, err := b.ToProto()
  138. if err != nil {
  139. return 0
  140. }
  141. return pbb.Size()
  142. }
  143. // String returns a string representation of the block
  144. //
  145. // See StringIndented.
  146. func (b *Block) String() string {
  147. return b.StringIndented("")
  148. }
  149. // StringIndented returns an indented String.
  150. //
  151. // Header
  152. // Data
  153. // Evidence
  154. // LastCommit
  155. // Hash
  156. func (b *Block) StringIndented(indent string) string {
  157. if b == nil {
  158. return "nil-Block"
  159. }
  160. return fmt.Sprintf(`Block{
  161. %s %v
  162. %s %v
  163. %s %v
  164. %s %v
  165. %s}#%v`,
  166. indent, b.Header.StringIndented(indent+" "),
  167. indent, b.Data.StringIndented(indent+" "),
  168. indent, b.Evidence.StringIndented(indent+" "),
  169. indent, b.LastCommit.StringIndented(indent+" "),
  170. indent, b.Hash())
  171. }
  172. // StringShort returns a shortened string representation of the block.
  173. func (b *Block) StringShort() string {
  174. if b == nil {
  175. return "nil-Block"
  176. }
  177. return fmt.Sprintf("Block#%X", b.Hash())
  178. }
  179. // ToProto converts Block to protobuf
  180. func (b *Block) ToProto() (*tmproto.Block, error) {
  181. if b == nil {
  182. return nil, errors.New("nil Block")
  183. }
  184. pb := new(tmproto.Block)
  185. pb.Header = *b.Header.ToProto()
  186. pb.LastCommit = b.LastCommit.ToProto()
  187. pb.Data = b.Data.ToProto()
  188. protoEvidence, err := b.Evidence.ToProto()
  189. if err != nil {
  190. return nil, err
  191. }
  192. pb.Evidence = *protoEvidence
  193. return pb, nil
  194. }
  195. // FromProto sets a protobuf Block to the given pointer.
  196. // It returns an error if the block is invalid.
  197. func BlockFromProto(bp *tmproto.Block) (*Block, error) {
  198. if bp == nil {
  199. return nil, errors.New("nil block")
  200. }
  201. b := new(Block)
  202. h, err := HeaderFromProto(&bp.Header)
  203. if err != nil {
  204. return nil, err
  205. }
  206. b.Header = h
  207. data, err := DataFromProto(&bp.Data)
  208. if err != nil {
  209. return nil, err
  210. }
  211. b.Data = data
  212. if err := b.Evidence.FromProto(&bp.Evidence); err != nil {
  213. return nil, err
  214. }
  215. if bp.LastCommit != nil {
  216. lc, err := CommitFromProto(bp.LastCommit)
  217. if err != nil {
  218. return nil, err
  219. }
  220. b.LastCommit = lc
  221. }
  222. return b, b.ValidateBasic()
  223. }
  224. //-----------------------------------------------------------------------------
  225. // MaxDataBytes returns the maximum size of block's data.
  226. //
  227. // XXX: Panics on negative result.
  228. func MaxDataBytes(maxBytes, evidenceBytes int64, valsCount int) int64 {
  229. maxDataBytes := maxBytes -
  230. MaxOverheadForBlock -
  231. MaxHeaderBytes -
  232. 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. return c
  817. }
  818. // FromProto sets a protobuf Commit to the given pointer.
  819. // It returns an error if the commit is invalid.
  820. func CommitFromProto(cp *tmproto.Commit) (*Commit, error) {
  821. if cp == nil {
  822. return nil, errors.New("nil Commit")
  823. }
  824. var (
  825. commit = new(Commit)
  826. )
  827. bi, err := BlockIDFromProto(&cp.BlockID)
  828. if err != nil {
  829. return nil, err
  830. }
  831. sigs := make([]CommitSig, len(cp.Signatures))
  832. for i := range cp.Signatures {
  833. if err := sigs[i].FromProto(cp.Signatures[i]); err != nil {
  834. return nil, err
  835. }
  836. }
  837. commit.Signatures = sigs
  838. commit.Height = cp.Height
  839. commit.Round = cp.Round
  840. commit.BlockID = *bi
  841. return commit, commit.ValidateBasic()
  842. }
  843. //-----------------------------------------------------------------------------
  844. // Data contains the set of transactions included in the block
  845. type Data struct {
  846. // Txs that will be applied by state @ block.Height+1.
  847. // NOTE: not all txs here are valid. We're just agreeing on the order first.
  848. // This means that block.AppHash does not include these txs.
  849. Txs Txs `json:"txs"`
  850. // Volatile
  851. hash tmbytes.HexBytes
  852. }
  853. // Hash returns the hash of the data
  854. func (data *Data) Hash() tmbytes.HexBytes {
  855. if data == nil {
  856. return (Txs{}).Hash()
  857. }
  858. if data.hash == nil {
  859. data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs
  860. }
  861. return data.hash
  862. }
  863. // StringIndented returns an indented string representation of the transactions.
  864. func (data *Data) StringIndented(indent string) string {
  865. if data == nil {
  866. return "nil-Data"
  867. }
  868. txStrings := make([]string, tmmath.MinInt(len(data.Txs), 21))
  869. for i, tx := range data.Txs {
  870. if i == 20 {
  871. txStrings[i] = fmt.Sprintf("... (%v total)", len(data.Txs))
  872. break
  873. }
  874. txStrings[i] = fmt.Sprintf("%X (%d bytes)", tx.Hash(), len(tx))
  875. }
  876. return fmt.Sprintf(`Data{
  877. %s %v
  878. %s}#%v`,
  879. indent, strings.Join(txStrings, "\n"+indent+" "),
  880. indent, data.hash)
  881. }
  882. // ToProto converts Data to protobuf
  883. func (data *Data) ToProto() tmproto.Data {
  884. tp := new(tmproto.Data)
  885. if len(data.Txs) > 0 {
  886. txBzs := make([][]byte, len(data.Txs))
  887. for i := range data.Txs {
  888. txBzs[i] = data.Txs[i]
  889. }
  890. tp.Txs = txBzs
  891. }
  892. return *tp
  893. }
  894. // DataFromProto takes a protobuf representation of Data &
  895. // returns the native type.
  896. func DataFromProto(dp *tmproto.Data) (Data, error) {
  897. if dp == nil {
  898. return Data{}, errors.New("nil data")
  899. }
  900. data := new(Data)
  901. if len(dp.Txs) > 0 {
  902. txBzs := make(Txs, len(dp.Txs))
  903. for i := range dp.Txs {
  904. txBzs[i] = Tx(dp.Txs[i])
  905. }
  906. data.Txs = txBzs
  907. } else {
  908. data.Txs = Txs{}
  909. }
  910. return *data, nil
  911. }
  912. //-----------------------------------------------------------------------------
  913. // EvidenceData contains any evidence of malicious wrong-doing by validators
  914. type EvidenceData struct {
  915. Evidence EvidenceList `json:"evidence"`
  916. // Volatile. Used as cache
  917. hash tmbytes.HexBytes
  918. byteSize int64
  919. }
  920. // Hash returns the hash of the data.
  921. func (data *EvidenceData) Hash() tmbytes.HexBytes {
  922. if data.hash == nil {
  923. data.hash = data.Evidence.Hash()
  924. }
  925. return data.hash
  926. }
  927. // ByteSize returns the total byte size of all the evidence
  928. func (data *EvidenceData) ByteSize() int64 {
  929. if data.byteSize == 0 && len(data.Evidence) != 0 {
  930. pb, err := data.ToProto()
  931. if err != nil {
  932. panic(err)
  933. }
  934. data.byteSize = int64(pb.Size())
  935. }
  936. return data.byteSize
  937. }
  938. // StringIndented returns a string representation of the evidence.
  939. func (data *EvidenceData) StringIndented(indent string) string {
  940. if data == nil {
  941. return "nil-Evidence"
  942. }
  943. evStrings := make([]string, tmmath.MinInt(len(data.Evidence), 21))
  944. for i, ev := range data.Evidence {
  945. if i == 20 {
  946. evStrings[i] = fmt.Sprintf("... (%v total)", len(data.Evidence))
  947. break
  948. }
  949. evStrings[i] = fmt.Sprintf("Evidence:%v", ev)
  950. }
  951. return fmt.Sprintf(`EvidenceData{
  952. %s %v
  953. %s}#%v`,
  954. indent, strings.Join(evStrings, "\n"+indent+" "),
  955. indent, data.hash)
  956. }
  957. // ToProto converts EvidenceData to protobuf
  958. func (data *EvidenceData) ToProto() (*tmproto.EvidenceData, error) {
  959. if data == nil {
  960. return nil, errors.New("nil evidence data")
  961. }
  962. evi := new(tmproto.EvidenceData)
  963. eviBzs := make([]tmproto.Evidence, len(data.Evidence))
  964. for i := range data.Evidence {
  965. protoEvi, err := EvidenceToProto(data.Evidence[i])
  966. if err != nil {
  967. return nil, err
  968. }
  969. eviBzs[i] = *protoEvi
  970. }
  971. evi.Evidence = eviBzs
  972. return evi, nil
  973. }
  974. // FromProto sets a protobuf EvidenceData to the given pointer.
  975. func (data *EvidenceData) FromProto(eviData *tmproto.EvidenceData) error {
  976. if eviData == nil {
  977. return errors.New("nil evidenceData")
  978. }
  979. eviBzs := make(EvidenceList, len(eviData.Evidence))
  980. for i := range eviData.Evidence {
  981. evi, err := EvidenceFromProto(&eviData.Evidence[i])
  982. if err != nil {
  983. return err
  984. }
  985. eviBzs[i] = evi
  986. }
  987. data.Evidence = eviBzs
  988. data.byteSize = int64(eviData.Size())
  989. return nil
  990. }
  991. //--------------------------------------------------------------------------------
  992. // BlockID
  993. type BlockID struct {
  994. Hash tmbytes.HexBytes `json:"hash"`
  995. PartSetHeader PartSetHeader `json:"parts"`
  996. }
  997. // Equals returns true if the BlockID matches the given BlockID
  998. func (blockID BlockID) Equals(other BlockID) bool {
  999. return bytes.Equal(blockID.Hash, other.Hash) &&
  1000. blockID.PartSetHeader.Equals(other.PartSetHeader)
  1001. }
  1002. // Key returns a machine-readable string representation of the BlockID
  1003. func (blockID BlockID) Key() string {
  1004. pbph := blockID.PartSetHeader.ToProto()
  1005. bz, err := pbph.Marshal()
  1006. if err != nil {
  1007. panic(err)
  1008. }
  1009. return string(blockID.Hash) + string(bz)
  1010. }
  1011. // ValidateBasic performs basic validation.
  1012. func (blockID BlockID) ValidateBasic() error {
  1013. // Hash can be empty in case of POLBlockID in Proposal.
  1014. if err := ValidateHash(blockID.Hash); err != nil {
  1015. return fmt.Errorf("wrong Hash")
  1016. }
  1017. if err := blockID.PartSetHeader.ValidateBasic(); err != nil {
  1018. return fmt.Errorf("wrong PartSetHeader: %v", err)
  1019. }
  1020. return nil
  1021. }
  1022. // IsZero returns true if this is the BlockID of a nil block.
  1023. func (blockID BlockID) IsZero() bool {
  1024. return len(blockID.Hash) == 0 &&
  1025. blockID.PartSetHeader.IsZero()
  1026. }
  1027. // IsComplete returns true if this is a valid BlockID of a non-nil block.
  1028. func (blockID BlockID) IsComplete() bool {
  1029. return len(blockID.Hash) == tmhash.Size &&
  1030. blockID.PartSetHeader.Total > 0 &&
  1031. len(blockID.PartSetHeader.Hash) == tmhash.Size
  1032. }
  1033. // String returns a human readable string representation of the BlockID.
  1034. //
  1035. // 1. hash
  1036. // 2. part set header
  1037. //
  1038. // See PartSetHeader#String
  1039. func (blockID BlockID) String() string {
  1040. return fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartSetHeader)
  1041. }
  1042. // ToProto converts BlockID to protobuf
  1043. func (blockID *BlockID) ToProto() tmproto.BlockID {
  1044. if blockID == nil {
  1045. return tmproto.BlockID{}
  1046. }
  1047. return tmproto.BlockID{
  1048. Hash: blockID.Hash,
  1049. PartSetHeader: blockID.PartSetHeader.ToProto(),
  1050. }
  1051. }
  1052. // FromProto sets a protobuf BlockID to the given pointer.
  1053. // It returns an error if the block id is invalid.
  1054. func BlockIDFromProto(bID *tmproto.BlockID) (*BlockID, error) {
  1055. if bID == nil {
  1056. return nil, errors.New("nil BlockID")
  1057. }
  1058. blockID := new(BlockID)
  1059. ph, err := PartSetHeaderFromProto(&bID.PartSetHeader)
  1060. if err != nil {
  1061. return nil, err
  1062. }
  1063. blockID.PartSetHeader = *ph
  1064. blockID.Hash = bID.Hash
  1065. return blockID, blockID.ValidateBasic()
  1066. }