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.

581 lines
16 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
10 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. // 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. // CONTRACT: partSize is greater than zero.
  100. func (b *Block) MakePartSet(partSize int) *PartSet {
  101. if b == nil {
  102. return nil
  103. }
  104. b.mtx.Lock()
  105. defer b.mtx.Unlock()
  106. // We prefix the byte length, so that unmarshaling
  107. // can easily happen via a reader.
  108. bz, err := cdc.MarshalBinary(b)
  109. if err != nil {
  110. panic(err)
  111. }
  112. return NewPartSetFromData(bz, partSize)
  113. }
  114. // HashesTo is a convenience function that checks if a block hashes to the given argument.
  115. // Returns false if the block is nil or the hash is empty.
  116. func (b *Block) HashesTo(hash []byte) bool {
  117. if len(hash) == 0 {
  118. return false
  119. }
  120. if b == nil {
  121. return false
  122. }
  123. return bytes.Equal(b.Hash(), hash)
  124. }
  125. // Size returns size of the block in bytes.
  126. func (b *Block) Size() int {
  127. bz, err := cdc.MarshalBinaryBare(b)
  128. if err != nil {
  129. return 0
  130. }
  131. return len(bz)
  132. }
  133. // String returns a string representation of the block
  134. func (b *Block) String() string {
  135. return b.StringIndented("")
  136. }
  137. // StringIndented returns a string representation of the block
  138. func (b *Block) StringIndented(indent string) string {
  139. if b == nil {
  140. return "nil-Block"
  141. }
  142. return fmt.Sprintf(`Block{
  143. %s %v
  144. %s %v
  145. %s %v
  146. %s %v
  147. %s}#%v`,
  148. indent, b.Header.StringIndented(indent+" "),
  149. indent, b.Data.StringIndented(indent+" "),
  150. indent, b.Evidence.StringIndented(indent+" "),
  151. indent, b.LastCommit.StringIndented(indent+" "),
  152. indent, b.Hash())
  153. }
  154. // StringShort returns a shortened string representation of the block
  155. func (b *Block) StringShort() string {
  156. if b == nil {
  157. return "nil-Block"
  158. }
  159. return fmt.Sprintf("Block#%v", b.Hash())
  160. }
  161. //-----------------------------------------------------------------------------
  162. // Header defines the structure of a Tendermint block header
  163. // TODO: limit header size
  164. // NOTE: changes to the Header should be duplicated in the abci Header
  165. type Header struct {
  166. // basic block info
  167. ChainID string `json:"chain_id"`
  168. Height int64 `json:"height"`
  169. Time time.Time `json:"time"`
  170. NumTxs int64 `json:"num_txs"`
  171. // prev block info
  172. LastBlockID BlockID `json:"last_block_id"`
  173. TotalTxs int64 `json:"total_txs"`
  174. // hashes of block data
  175. LastCommitHash cmn.HexBytes `json:"last_commit_hash"` // commit from validators from the last block
  176. DataHash cmn.HexBytes `json:"data_hash"` // transactions
  177. // hashes from the app output from the prev block
  178. ValidatorsHash cmn.HexBytes `json:"validators_hash"` // validators for the current 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 ValidatorsHash (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. "App": aminoHasher(h.AppHash),
  204. "Consensus": aminoHasher(h.ConsensusHash),
  205. "Results": aminoHasher(h.LastResultsHash),
  206. "Evidence": aminoHasher(h.EvidenceHash),
  207. })
  208. }
  209. // StringIndented returns a string representation of the header
  210. func (h *Header) StringIndented(indent string) string {
  211. if h == nil {
  212. return "nil-Header"
  213. }
  214. return fmt.Sprintf(`Header{
  215. %s ChainID: %v
  216. %s Height: %v
  217. %s Time: %v
  218. %s NumTxs: %v
  219. %s TotalTxs: %v
  220. %s LastBlockID: %v
  221. %s LastCommit: %v
  222. %s Data: %v
  223. %s Validators: %v
  224. %s App: %v
  225. %s Consensus: %v
  226. %s Results: %v
  227. %s Evidence: %v
  228. %s}#%v`,
  229. indent, h.ChainID,
  230. indent, h.Height,
  231. indent, h.Time,
  232. indent, h.NumTxs,
  233. indent, h.TotalTxs,
  234. indent, h.LastBlockID,
  235. indent, h.LastCommitHash,
  236. indent, h.DataHash,
  237. indent, h.ValidatorsHash,
  238. indent, h.AppHash,
  239. indent, h.ConsensusHash,
  240. indent, h.LastResultsHash,
  241. indent, h.EvidenceHash,
  242. indent, h.Hash())
  243. }
  244. //-------------------------------------
  245. // Commit contains the evidence that a block was committed by a set of validators.
  246. // NOTE: Commit is empty for height 1, but never nil.
  247. type Commit struct {
  248. // NOTE: The Precommits are in order of address to preserve the bonded ValidatorSet order.
  249. // Any peer with a block can gossip precommits by index with a peer without recalculating the
  250. // active ValidatorSet.
  251. BlockID BlockID `json:"block_id"`
  252. Precommits []*Vote `json:"precommits"`
  253. // Volatile
  254. firstPrecommit *Vote
  255. hash cmn.HexBytes
  256. bitArray *cmn.BitArray
  257. }
  258. // FirstPrecommit returns the first non-nil precommit in the commit.
  259. // If all precommits are nil, it returns an empty precommit with height 0.
  260. func (commit *Commit) FirstPrecommit() *Vote {
  261. if len(commit.Precommits) == 0 {
  262. return nil
  263. }
  264. if commit.firstPrecommit != nil {
  265. return commit.firstPrecommit
  266. }
  267. for _, precommit := range commit.Precommits {
  268. if precommit != nil {
  269. commit.firstPrecommit = precommit
  270. return precommit
  271. }
  272. }
  273. return &Vote{
  274. Type: VoteTypePrecommit,
  275. }
  276. }
  277. // Height returns the height of the commit
  278. func (commit *Commit) Height() int64 {
  279. if len(commit.Precommits) == 0 {
  280. return 0
  281. }
  282. return commit.FirstPrecommit().Height
  283. }
  284. // Round returns the round of the commit
  285. func (commit *Commit) Round() int {
  286. if len(commit.Precommits) == 0 {
  287. return 0
  288. }
  289. return commit.FirstPrecommit().Round
  290. }
  291. // Type returns the vote type of the commit, which is always VoteTypePrecommit
  292. func (commit *Commit) Type() byte {
  293. return VoteTypePrecommit
  294. }
  295. // Size returns the number of votes in the commit
  296. func (commit *Commit) Size() int {
  297. if commit == nil {
  298. return 0
  299. }
  300. return len(commit.Precommits)
  301. }
  302. // BitArray returns a BitArray of which validators voted in this commit
  303. func (commit *Commit) BitArray() *cmn.BitArray {
  304. if commit.bitArray == nil {
  305. commit.bitArray = cmn.NewBitArray(len(commit.Precommits))
  306. for i, precommit := range commit.Precommits {
  307. // TODO: need to check the BlockID otherwise we could be counting conflicts,
  308. // not just the one with +2/3 !
  309. commit.bitArray.SetIndex(i, precommit != nil)
  310. }
  311. }
  312. return commit.bitArray
  313. }
  314. // GetByIndex returns the vote corresponding to a given validator index
  315. func (commit *Commit) GetByIndex(index int) *Vote {
  316. return commit.Precommits[index]
  317. }
  318. // IsCommit returns true if there is at least one vote
  319. func (commit *Commit) IsCommit() bool {
  320. return len(commit.Precommits) != 0
  321. }
  322. // ValidateBasic performs basic validation that doesn't involve state data.
  323. func (commit *Commit) ValidateBasic() error {
  324. if commit.BlockID.IsZero() {
  325. return errors.New("Commit cannot be for nil block")
  326. }
  327. if len(commit.Precommits) == 0 {
  328. return errors.New("No precommits in commit")
  329. }
  330. height, round := commit.Height(), commit.Round()
  331. // validate the precommits
  332. for _, precommit := range commit.Precommits {
  333. // It's OK for precommits to be missing.
  334. if precommit == nil {
  335. continue
  336. }
  337. // Ensure that all votes are precommits
  338. if precommit.Type != VoteTypePrecommit {
  339. return fmt.Errorf("Invalid commit vote. Expected precommit, got %v",
  340. precommit.Type)
  341. }
  342. // Ensure that all heights are the same
  343. if precommit.Height != height {
  344. return fmt.Errorf("Invalid commit precommit height. Expected %v, got %v",
  345. height, precommit.Height)
  346. }
  347. // Ensure that all rounds are the same
  348. if precommit.Round != round {
  349. return fmt.Errorf("Invalid commit precommit round. Expected %v, got %v",
  350. round, precommit.Round)
  351. }
  352. }
  353. return nil
  354. }
  355. // Hash returns the hash of the commit
  356. func (commit *Commit) Hash() cmn.HexBytes {
  357. if commit == nil {
  358. return nil
  359. }
  360. if commit.hash == nil {
  361. bs := make([]merkle.Hasher, len(commit.Precommits))
  362. for i, precommit := range commit.Precommits {
  363. bs[i] = aminoHasher(precommit)
  364. }
  365. commit.hash = merkle.SimpleHashFromHashers(bs)
  366. }
  367. return commit.hash
  368. }
  369. // StringIndented returns a string representation of the commit
  370. func (commit *Commit) StringIndented(indent string) string {
  371. if commit == nil {
  372. return "nil-Commit"
  373. }
  374. precommitStrings := make([]string, len(commit.Precommits))
  375. for i, precommit := range commit.Precommits {
  376. precommitStrings[i] = precommit.String()
  377. }
  378. return fmt.Sprintf(`Commit{
  379. %s BlockID: %v
  380. %s Precommits: %v
  381. %s}#%v`,
  382. indent, commit.BlockID,
  383. indent, strings.Join(precommitStrings, "\n"+indent+" "),
  384. indent, commit.hash)
  385. }
  386. //-----------------------------------------------------------------------------
  387. // SignedHeader is a header along with the commits that prove it
  388. type SignedHeader struct {
  389. Header *Header `json:"header"`
  390. Commit *Commit `json:"commit"`
  391. }
  392. //-----------------------------------------------------------------------------
  393. // Data contains the set of transactions included in the block
  394. type Data struct {
  395. // Txs that will be applied by state @ block.Height+1.
  396. // NOTE: not all txs here are valid. We're just agreeing on the order first.
  397. // This means that block.AppHash does not include these txs.
  398. Txs Txs `json:"txs"`
  399. // Volatile
  400. hash cmn.HexBytes
  401. }
  402. // Hash returns the hash of the data
  403. func (data *Data) Hash() cmn.HexBytes {
  404. if data == nil {
  405. return (Txs{}).Hash()
  406. }
  407. if data.hash == nil {
  408. data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs
  409. }
  410. return data.hash
  411. }
  412. // StringIndented returns a string representation of the transactions
  413. func (data *Data) StringIndented(indent string) string {
  414. if data == nil {
  415. return "nil-Data"
  416. }
  417. txStrings := make([]string, cmn.MinInt(len(data.Txs), 21))
  418. for i, tx := range data.Txs {
  419. if i == 20 {
  420. txStrings[i] = fmt.Sprintf("... (%v total)", len(data.Txs))
  421. break
  422. }
  423. txStrings[i] = fmt.Sprintf("%X (%d bytes)", tx.Hash(), len(tx))
  424. }
  425. return fmt.Sprintf(`Data{
  426. %s %v
  427. %s}#%v`,
  428. indent, strings.Join(txStrings, "\n"+indent+" "),
  429. indent, data.hash)
  430. }
  431. //-----------------------------------------------------------------------------
  432. // EvidenceData contains any evidence of malicious wrong-doing by validators
  433. type EvidenceData struct {
  434. Evidence EvidenceList `json:"evidence"`
  435. // Volatile
  436. hash cmn.HexBytes
  437. }
  438. // Hash returns the hash of the data.
  439. func (data *EvidenceData) Hash() cmn.HexBytes {
  440. if data.hash == nil {
  441. data.hash = data.Evidence.Hash()
  442. }
  443. return data.hash
  444. }
  445. // StringIndented returns a string representation of the evidence.
  446. func (data *EvidenceData) StringIndented(indent string) string {
  447. if data == nil {
  448. return "nil-Evidence"
  449. }
  450. evStrings := make([]string, cmn.MinInt(len(data.Evidence), 21))
  451. for i, ev := range data.Evidence {
  452. if i == 20 {
  453. evStrings[i] = fmt.Sprintf("... (%v total)", len(data.Evidence))
  454. break
  455. }
  456. evStrings[i] = fmt.Sprintf("Evidence:%v", ev)
  457. }
  458. return fmt.Sprintf(`EvidenceData{
  459. %s %v
  460. %s}#%v`,
  461. indent, strings.Join(evStrings, "\n"+indent+" "),
  462. indent, data.hash)
  463. return ""
  464. }
  465. //--------------------------------------------------------------------------------
  466. // BlockID defines the unique ID of a block as its Hash and its PartSetHeader
  467. type BlockID struct {
  468. Hash cmn.HexBytes `json:"hash"`
  469. PartsHeader PartSetHeader `json:"parts"`
  470. }
  471. // IsZero returns true if this is the BlockID for a nil-block
  472. func (blockID BlockID) IsZero() bool {
  473. return len(blockID.Hash) == 0 && blockID.PartsHeader.IsZero()
  474. }
  475. // Equals returns true if the BlockID matches the given BlockID
  476. func (blockID BlockID) Equals(other BlockID) bool {
  477. return bytes.Equal(blockID.Hash, other.Hash) &&
  478. blockID.PartsHeader.Equals(other.PartsHeader)
  479. }
  480. // Key returns a machine-readable string representation of the BlockID
  481. func (blockID BlockID) Key() string {
  482. bz, err := cdc.MarshalBinaryBare(blockID.PartsHeader)
  483. if err != nil {
  484. panic(err)
  485. }
  486. return string(blockID.Hash) + string(bz)
  487. }
  488. // String returns a human readable string representation of the BlockID
  489. func (blockID BlockID) String() string {
  490. return fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartsHeader)
  491. }
  492. //-------------------------------------------------------
  493. type hasher struct {
  494. item interface{}
  495. }
  496. func (h hasher) Hash() []byte {
  497. hasher := tmhash.New()
  498. if h.item != nil && !cmn.IsTypedNil(h.item) && !cmn.IsEmpty(h.item) {
  499. bz, err := cdc.MarshalBinaryBare(h.item)
  500. if err != nil {
  501. panic(err)
  502. }
  503. _, err = hasher.Write(bz)
  504. if err != nil {
  505. panic(err)
  506. }
  507. }
  508. return hasher.Sum(nil)
  509. }
  510. func aminoHash(item interface{}) []byte {
  511. h := hasher{item}
  512. return h.Hash()
  513. }
  514. func aminoHasher(item interface{}) merkle.Hasher {
  515. return hasher{item}
  516. }