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