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.

669 lines
18 KiB

10 years ago
10 years ago
7 years ago
10 years ago
10 years ago
6 years ago
7 years ago
7 years ago
10 years ago
9 years ago
7 years ago
7 years ago
10 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package types
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/tendermint/tendermint/crypto/merkle"
  10. "github.com/tendermint/tendermint/crypto/tmhash"
  11. cmn "github.com/tendermint/tendermint/libs/common"
  12. )
  13. const (
  14. // MaxHeaderBytes is a maximum header size (including amino overhead).
  15. MaxHeaderBytes = 478
  16. // MaxAminoOverheadForBlock - amino overhead to encode the block.
  17. MaxAminoOverheadForBlock = 4
  18. )
  19. // Block defines the atomic unit of a Tendermint blockchain.
  20. // TODO: add Version byte
  21. type Block struct {
  22. mtx sync.Mutex
  23. Header `json:"header"`
  24. Data `json:"data"`
  25. Evidence EvidenceData `json:"evidence"`
  26. LastCommit *Commit `json:"last_commit"`
  27. }
  28. // MakeBlock returns a new block with an empty header, except what can be
  29. // computed from itself.
  30. // It populates the same set of fields validated by ValidateBasic.
  31. func MakeBlock(height int64, txs []Tx, lastCommit *Commit, evidence []Evidence) *Block {
  32. block := &Block{
  33. Header: Header{
  34. Height: height,
  35. Time: time.Now(),
  36. NumTxs: int64(len(txs)),
  37. },
  38. Data: Data{
  39. Txs: txs,
  40. },
  41. Evidence: EvidenceData{Evidence: evidence},
  42. LastCommit: lastCommit,
  43. }
  44. block.fillHeader()
  45. return block
  46. }
  47. // ValidateBasic performs basic validation that doesn't involve state data.
  48. // It checks the internal consistency of the block.
  49. func (b *Block) ValidateBasic() error {
  50. if b == nil {
  51. return errors.New("Nil blocks are invalid")
  52. }
  53. b.mtx.Lock()
  54. defer b.mtx.Unlock()
  55. newTxs := int64(len(b.Data.Txs))
  56. if b.NumTxs != newTxs {
  57. return fmt.Errorf(
  58. "Wrong Block.Header.NumTxs. Expected %v, got %v",
  59. newTxs,
  60. b.NumTxs,
  61. )
  62. }
  63. if !bytes.Equal(b.LastCommitHash, b.LastCommit.Hash()) {
  64. return fmt.Errorf(
  65. "Wrong Block.Header.LastCommitHash. Expected %v, got %v",
  66. b.LastCommitHash,
  67. b.LastCommit.Hash(),
  68. )
  69. }
  70. if b.Header.Height != 1 {
  71. if err := b.LastCommit.ValidateBasic(); err != nil {
  72. return err
  73. }
  74. }
  75. if !bytes.Equal(b.DataHash, b.Data.Hash()) {
  76. return fmt.Errorf(
  77. "Wrong Block.Header.DataHash. Expected %v, got %v",
  78. b.DataHash,
  79. b.Data.Hash(),
  80. )
  81. }
  82. if !bytes.Equal(b.EvidenceHash, b.Evidence.Hash()) {
  83. return fmt.Errorf(
  84. "Wrong Block.Header.EvidenceHash. Expected %v, got %v",
  85. b.EvidenceHash,
  86. b.Evidence.Hash(),
  87. )
  88. }
  89. return nil
  90. }
  91. // fillHeader fills in any remaining header fields that are a function of the block data
  92. func (b *Block) fillHeader() {
  93. if b.LastCommitHash == nil {
  94. b.LastCommitHash = b.LastCommit.Hash()
  95. }
  96. if b.DataHash == nil {
  97. b.DataHash = b.Data.Hash()
  98. }
  99. if b.EvidenceHash == nil {
  100. b.EvidenceHash = b.Evidence.Hash()
  101. }
  102. }
  103. // Hash computes and returns the block hash.
  104. // If the block is incomplete, block hash is nil for safety.
  105. func (b *Block) Hash() cmn.HexBytes {
  106. if b == nil {
  107. return nil
  108. }
  109. b.mtx.Lock()
  110. defer b.mtx.Unlock()
  111. if b == nil || b.LastCommit == nil {
  112. return nil
  113. }
  114. b.fillHeader()
  115. return b.Header.Hash()
  116. }
  117. // MakePartSet returns a PartSet containing parts of a serialized block.
  118. // This is the form in which the block is gossipped to peers.
  119. // CONTRACT: partSize is greater than zero.
  120. func (b *Block) MakePartSet(partSize int) *PartSet {
  121. if b == nil {
  122. return nil
  123. }
  124. b.mtx.Lock()
  125. defer b.mtx.Unlock()
  126. // We prefix the byte length, so that unmarshaling
  127. // can easily happen via a reader.
  128. bz, err := cdc.MarshalBinary(b)
  129. if err != nil {
  130. panic(err)
  131. }
  132. return NewPartSetFromData(bz, partSize)
  133. }
  134. // HashesTo is a convenience function that checks if a block hashes to the given argument.
  135. // Returns false if the block is nil or the hash is empty.
  136. func (b *Block) HashesTo(hash []byte) bool {
  137. if len(hash) == 0 {
  138. return false
  139. }
  140. if b == nil {
  141. return false
  142. }
  143. return bytes.Equal(b.Hash(), hash)
  144. }
  145. // Size returns size of the block in bytes.
  146. func (b *Block) Size() int {
  147. bz, err := cdc.MarshalBinaryBare(b)
  148. if err != nil {
  149. return 0
  150. }
  151. return len(bz)
  152. }
  153. // String returns a string representation of the block
  154. func (b *Block) String() string {
  155. return b.StringIndented("")
  156. }
  157. // StringIndented returns a string representation of the block
  158. func (b *Block) StringIndented(indent string) string {
  159. if b == nil {
  160. return "nil-Block"
  161. }
  162. return fmt.Sprintf(`Block{
  163. %s %v
  164. %s %v
  165. %s %v
  166. %s %v
  167. %s}#%v`,
  168. indent, b.Header.StringIndented(indent+" "),
  169. indent, b.Data.StringIndented(indent+" "),
  170. indent, b.Evidence.StringIndented(indent+" "),
  171. indent, b.LastCommit.StringIndented(indent+" "),
  172. indent, b.Hash())
  173. }
  174. // StringShort returns a shortened string representation of the block
  175. func (b *Block) StringShort() string {
  176. if b == nil {
  177. return "nil-Block"
  178. }
  179. return fmt.Sprintf("Block#%v", b.Hash())
  180. }
  181. //-----------------------------------------------------------------------------
  182. // Header defines the structure of a Tendermint block header
  183. // TODO: limit header size
  184. // NOTE: changes to the Header should be duplicated in the abci Header
  185. type Header struct {
  186. // basic block info
  187. ChainID string `json:"chain_id"`
  188. Height int64 `json:"height"`
  189. Time time.Time `json:"time"`
  190. NumTxs int64 `json:"num_txs"`
  191. TotalTxs int64 `json:"total_txs"`
  192. // prev block info
  193. LastBlockID BlockID `json:"last_block_id"`
  194. // hashes of block data
  195. LastCommitHash cmn.HexBytes `json:"last_commit_hash"` // commit from validators from the last block
  196. DataHash cmn.HexBytes `json:"data_hash"` // transactions
  197. // hashes from the app output from the prev block
  198. ValidatorsHash cmn.HexBytes `json:"validators_hash"` // validators for the current block
  199. NextValidatorsHash cmn.HexBytes `json:"next_validators_hash"` // validators for the next block
  200. ConsensusHash cmn.HexBytes `json:"consensus_hash"` // consensus params for current block
  201. AppHash cmn.HexBytes `json:"app_hash"` // state after txs from the previous block
  202. LastResultsHash cmn.HexBytes `json:"last_results_hash"` // root hash of all results from the txs from the previous block
  203. // consensus info
  204. EvidenceHash cmn.HexBytes `json:"evidence_hash"` // evidence included in the block
  205. ProposerAddress Address `json:"proposer_address"` // original proposer of the block
  206. }
  207. // Hash returns the hash of the header.
  208. // Returns nil if ValidatorHash is missing,
  209. // since a Header is not valid unless there is
  210. // a ValidatorsHash (corresponding to the validator set).
  211. func (h *Header) Hash() cmn.HexBytes {
  212. if h == nil || len(h.ValidatorsHash) == 0 {
  213. return nil
  214. }
  215. return merkle.SimpleHashFromMap(map[string]merkle.Hasher{
  216. "ChainID": aminoHasher(h.ChainID),
  217. "Height": aminoHasher(h.Height),
  218. "Time": aminoHasher(h.Time),
  219. "NumTxs": aminoHasher(h.NumTxs),
  220. "TotalTxs": aminoHasher(h.TotalTxs),
  221. "LastBlockID": aminoHasher(h.LastBlockID),
  222. "LastCommit": aminoHasher(h.LastCommitHash),
  223. "Data": aminoHasher(h.DataHash),
  224. "Validators": aminoHasher(h.ValidatorsHash),
  225. "NextValidators": aminoHasher(h.NextValidatorsHash),
  226. "App": aminoHasher(h.AppHash),
  227. "Consensus": aminoHasher(h.ConsensusHash),
  228. "Results": aminoHasher(h.LastResultsHash),
  229. "Evidence": aminoHasher(h.EvidenceHash),
  230. "Proposer": aminoHasher(h.ProposerAddress),
  231. })
  232. }
  233. // StringIndented returns a string representation of the header
  234. func (h *Header) StringIndented(indent string) string {
  235. if h == nil {
  236. return "nil-Header"
  237. }
  238. return fmt.Sprintf(`Header{
  239. %s ChainID: %v
  240. %s Height: %v
  241. %s Time: %v
  242. %s NumTxs: %v
  243. %s TotalTxs: %v
  244. %s LastBlockID: %v
  245. %s LastCommit: %v
  246. %s Data: %v
  247. %s Validators: %v
  248. %s NextValidators: %v
  249. %s App: %v
  250. %s Consensus: %v
  251. %s Results: %v
  252. %s Evidence: %v
  253. %s Proposer: %v
  254. %s}#%v`,
  255. indent, h.ChainID,
  256. indent, h.Height,
  257. indent, h.Time,
  258. indent, h.NumTxs,
  259. indent, h.TotalTxs,
  260. indent, h.LastBlockID,
  261. indent, h.LastCommitHash,
  262. indent, h.DataHash,
  263. indent, h.ValidatorsHash,
  264. indent, h.NextValidatorsHash,
  265. indent, h.AppHash,
  266. indent, h.ConsensusHash,
  267. indent, h.LastResultsHash,
  268. indent, h.EvidenceHash,
  269. indent, h.ProposerAddress,
  270. indent, h.Hash())
  271. }
  272. //-------------------------------------
  273. // Commit contains the evidence that a block was committed by a set of validators.
  274. // NOTE: Commit is empty for height 1, but never nil.
  275. type Commit struct {
  276. // NOTE: The Precommits are in order of address to preserve the bonded ValidatorSet order.
  277. // Any peer with a block can gossip precommits by index with a peer without recalculating the
  278. // active ValidatorSet.
  279. BlockID BlockID `json:"block_id"`
  280. Precommits []*Vote `json:"precommits"`
  281. // Volatile
  282. firstPrecommit *Vote
  283. hash cmn.HexBytes
  284. bitArray *cmn.BitArray
  285. }
  286. // FirstPrecommit returns the first non-nil precommit in the commit.
  287. // If all precommits are nil, it returns an empty precommit with height 0.
  288. func (commit *Commit) FirstPrecommit() *Vote {
  289. if len(commit.Precommits) == 0 {
  290. return nil
  291. }
  292. if commit.firstPrecommit != nil {
  293. return commit.firstPrecommit
  294. }
  295. for _, precommit := range commit.Precommits {
  296. if precommit != nil {
  297. commit.firstPrecommit = precommit
  298. return precommit
  299. }
  300. }
  301. return &Vote{
  302. Type: VoteTypePrecommit,
  303. }
  304. }
  305. // Height returns the height of the commit
  306. func (commit *Commit) Height() int64 {
  307. if len(commit.Precommits) == 0 {
  308. return 0
  309. }
  310. return commit.FirstPrecommit().Height
  311. }
  312. // Round returns the round of the commit
  313. func (commit *Commit) Round() int {
  314. if len(commit.Precommits) == 0 {
  315. return 0
  316. }
  317. return commit.FirstPrecommit().Round
  318. }
  319. // Type returns the vote type of the commit, which is always VoteTypePrecommit
  320. func (commit *Commit) Type() byte {
  321. return VoteTypePrecommit
  322. }
  323. // Size returns the number of votes in the commit
  324. func (commit *Commit) Size() int {
  325. if commit == nil {
  326. return 0
  327. }
  328. return len(commit.Precommits)
  329. }
  330. // BitArray returns a BitArray of which validators voted in this commit
  331. func (commit *Commit) BitArray() *cmn.BitArray {
  332. if commit.bitArray == nil {
  333. commit.bitArray = cmn.NewBitArray(len(commit.Precommits))
  334. for i, precommit := range commit.Precommits {
  335. // TODO: need to check the BlockID otherwise we could be counting conflicts,
  336. // not just the one with +2/3 !
  337. commit.bitArray.SetIndex(i, precommit != nil)
  338. }
  339. }
  340. return commit.bitArray
  341. }
  342. // GetByIndex returns the vote corresponding to a given validator index
  343. func (commit *Commit) GetByIndex(index int) *Vote {
  344. return commit.Precommits[index]
  345. }
  346. // IsCommit returns true if there is at least one vote
  347. func (commit *Commit) IsCommit() bool {
  348. return len(commit.Precommits) != 0
  349. }
  350. // ValidateBasic performs basic validation that doesn't involve state data.
  351. // Does not actually check the cryptographic signatures.
  352. func (commit *Commit) ValidateBasic() error {
  353. if commit.BlockID.IsZero() {
  354. return errors.New("Commit cannot be for nil block")
  355. }
  356. if len(commit.Precommits) == 0 {
  357. return errors.New("No precommits in commit")
  358. }
  359. height, round := commit.Height(), commit.Round()
  360. // Validate the precommits.
  361. for _, precommit := range commit.Precommits {
  362. // It's OK for precommits to be missing.
  363. if precommit == nil {
  364. continue
  365. }
  366. // Ensure that all votes are precommits.
  367. if precommit.Type != VoteTypePrecommit {
  368. return fmt.Errorf("Invalid commit vote. Expected precommit, got %v",
  369. precommit.Type)
  370. }
  371. // Ensure that all heights are the same.
  372. if precommit.Height != height {
  373. return fmt.Errorf("Invalid commit precommit height. Expected %v, got %v",
  374. height, precommit.Height)
  375. }
  376. // Ensure that all rounds are the same.
  377. if precommit.Round != round {
  378. return fmt.Errorf("Invalid commit precommit round. Expected %v, got %v",
  379. round, precommit.Round)
  380. }
  381. }
  382. return nil
  383. }
  384. // Hash returns the hash of the commit
  385. func (commit *Commit) Hash() cmn.HexBytes {
  386. if commit == nil {
  387. return nil
  388. }
  389. if commit.hash == nil {
  390. bs := make([]merkle.Hasher, len(commit.Precommits))
  391. for i, precommit := range commit.Precommits {
  392. bs[i] = aminoHasher(precommit)
  393. }
  394. commit.hash = merkle.SimpleHashFromHashers(bs)
  395. }
  396. return commit.hash
  397. }
  398. // StringIndented returns a string representation of the commit
  399. func (commit *Commit) StringIndented(indent string) string {
  400. if commit == nil {
  401. return "nil-Commit"
  402. }
  403. precommitStrings := make([]string, len(commit.Precommits))
  404. for i, precommit := range commit.Precommits {
  405. precommitStrings[i] = precommit.String()
  406. }
  407. return fmt.Sprintf(`Commit{
  408. %s BlockID: %v
  409. %s Precommits:
  410. %s %v
  411. %s}#%v`,
  412. indent, commit.BlockID,
  413. indent,
  414. indent, strings.Join(precommitStrings, "\n"+indent+" "),
  415. indent, commit.hash)
  416. }
  417. //-----------------------------------------------------------------------------
  418. // SignedHeader is a header along with the commits that prove it.
  419. type SignedHeader struct {
  420. *Header `json:"header"`
  421. Commit *Commit `json:"commit"`
  422. }
  423. // ValidateBasic does basic consistency checks and makes sure the header
  424. // and commit are consistent.
  425. //
  426. // NOTE: This does not actually check the cryptographic signatures. Make
  427. // sure to use a Verifier to validate the signatures actually provide a
  428. // significantly strong proof for this header's validity.
  429. func (sh SignedHeader) ValidateBasic(chainID string) error {
  430. // Make sure the header is consistent with the commit.
  431. if sh.Header == nil {
  432. return errors.New("SignedHeader missing header.")
  433. }
  434. if sh.Commit == nil {
  435. return errors.New("SignedHeader missing commit (precommit votes).")
  436. }
  437. // Check ChainID.
  438. if sh.ChainID != chainID {
  439. return fmt.Errorf("Header belongs to another chain '%s' not '%s'",
  440. sh.ChainID, chainID)
  441. }
  442. // Check Height.
  443. if sh.Commit.Height() != sh.Height {
  444. return fmt.Errorf("SignedHeader header and commit height mismatch: %v vs %v",
  445. sh.Height, sh.Commit.Height())
  446. }
  447. // Check Hash.
  448. hhash := sh.Hash()
  449. chash := sh.Commit.BlockID.Hash
  450. if !bytes.Equal(hhash, chash) {
  451. return fmt.Errorf("SignedHeader commit signs block %X, header is block %X",
  452. chash, hhash)
  453. }
  454. // ValidateBasic on the Commit.
  455. err := sh.Commit.ValidateBasic()
  456. if err != nil {
  457. return cmn.ErrorWrap(err, "commit.ValidateBasic failed during SignedHeader.ValidateBasic")
  458. }
  459. return nil
  460. }
  461. func (sh SignedHeader) String() string {
  462. return sh.StringIndented("")
  463. }
  464. // StringIndented returns a string representation of the SignedHeader.
  465. func (sh SignedHeader) StringIndented(indent string) string {
  466. return fmt.Sprintf(`SignedHeader{
  467. %s %v
  468. %s %v
  469. %s}`,
  470. indent, sh.Header.StringIndented(indent+" "),
  471. indent, sh.Commit.StringIndented(indent+" "),
  472. indent)
  473. return ""
  474. }
  475. //-----------------------------------------------------------------------------
  476. // Data contains the set of transactions included in the block
  477. type Data struct {
  478. // Txs that will be applied by state @ block.Height+1.
  479. // NOTE: not all txs here are valid. We're just agreeing on the order first.
  480. // This means that block.AppHash does not include these txs.
  481. Txs Txs `json:"txs"`
  482. // Volatile
  483. hash cmn.HexBytes
  484. }
  485. // Hash returns the hash of the data
  486. func (data *Data) Hash() cmn.HexBytes {
  487. if data == nil {
  488. return (Txs{}).Hash()
  489. }
  490. if data.hash == nil {
  491. data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs
  492. }
  493. return data.hash
  494. }
  495. // StringIndented returns a string representation of the transactions
  496. func (data *Data) StringIndented(indent string) string {
  497. if data == nil {
  498. return "nil-Data"
  499. }
  500. txStrings := make([]string, cmn.MinInt(len(data.Txs), 21))
  501. for i, tx := range data.Txs {
  502. if i == 20 {
  503. txStrings[i] = fmt.Sprintf("... (%v total)", len(data.Txs))
  504. break
  505. }
  506. txStrings[i] = fmt.Sprintf("%X (%d bytes)", tx.Hash(), len(tx))
  507. }
  508. return fmt.Sprintf(`Data{
  509. %s %v
  510. %s}#%v`,
  511. indent, strings.Join(txStrings, "\n"+indent+" "),
  512. indent, data.hash)
  513. }
  514. //-----------------------------------------------------------------------------
  515. // EvidenceData contains any evidence of malicious wrong-doing by validators
  516. type EvidenceData struct {
  517. Evidence EvidenceList `json:"evidence"`
  518. // Volatile
  519. hash cmn.HexBytes
  520. }
  521. // Hash returns the hash of the data.
  522. func (data *EvidenceData) Hash() cmn.HexBytes {
  523. if data.hash == nil {
  524. data.hash = data.Evidence.Hash()
  525. }
  526. return data.hash
  527. }
  528. // StringIndented returns a string representation of the evidence.
  529. func (data *EvidenceData) StringIndented(indent string) string {
  530. if data == nil {
  531. return "nil-Evidence"
  532. }
  533. evStrings := make([]string, cmn.MinInt(len(data.Evidence), 21))
  534. for i, ev := range data.Evidence {
  535. if i == 20 {
  536. evStrings[i] = fmt.Sprintf("... (%v total)", len(data.Evidence))
  537. break
  538. }
  539. evStrings[i] = fmt.Sprintf("Evidence:%v", ev)
  540. }
  541. return fmt.Sprintf(`EvidenceData{
  542. %s %v
  543. %s}#%v`,
  544. indent, strings.Join(evStrings, "\n"+indent+" "),
  545. indent, data.hash)
  546. return ""
  547. }
  548. //--------------------------------------------------------------------------------
  549. // BlockID defines the unique ID of a block as its Hash and its PartSetHeader
  550. type BlockID struct {
  551. Hash cmn.HexBytes `json:"hash"`
  552. PartsHeader PartSetHeader `json:"parts"`
  553. }
  554. // IsZero returns true if this is the BlockID for a nil-block
  555. func (blockID BlockID) IsZero() bool {
  556. return len(blockID.Hash) == 0 && blockID.PartsHeader.IsZero()
  557. }
  558. // Equals returns true if the BlockID matches the given BlockID
  559. func (blockID BlockID) Equals(other BlockID) bool {
  560. return bytes.Equal(blockID.Hash, other.Hash) &&
  561. blockID.PartsHeader.Equals(other.PartsHeader)
  562. }
  563. // Key returns a machine-readable string representation of the BlockID
  564. func (blockID BlockID) Key() string {
  565. bz, err := cdc.MarshalBinaryBare(blockID.PartsHeader)
  566. if err != nil {
  567. panic(err)
  568. }
  569. return string(blockID.Hash) + string(bz)
  570. }
  571. // String returns a human readable string representation of the BlockID
  572. func (blockID BlockID) String() string {
  573. return fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartsHeader)
  574. }
  575. //-------------------------------------------------------
  576. type hasher struct {
  577. item interface{}
  578. }
  579. func (h hasher) Hash() []byte {
  580. hasher := tmhash.New()
  581. if h.item != nil && !cmn.IsTypedNil(h.item) && !cmn.IsEmpty(h.item) {
  582. bz, err := cdc.MarshalBinaryBare(h.item)
  583. if err != nil {
  584. panic(err)
  585. }
  586. _, err = hasher.Write(bz)
  587. if err != nil {
  588. panic(err)
  589. }
  590. }
  591. return hasher.Sum(nil)
  592. }
  593. func aminoHash(item interface{}) []byte {
  594. h := hasher{item}
  595. return h.Hash()
  596. }
  597. func aminoHasher(item interface{}) merkle.Hasher {
  598. return hasher{item}
  599. }