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.

640 lines
18 KiB

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