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.

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