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.

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