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.

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