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.

584 lines
16 KiB

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
  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. Data: Data{
  32. Txs: txs,
  33. },
  34. LastCommit: commit,
  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. if b == nil {
  42. return
  43. }
  44. b.Evidence.Evidence = append(b.Evidence.Evidence, evidence...)
  45. }
  46. // ValidateBasic performs basic validation that doesn't involve state data.
  47. // It checks the internal consistency of the block.
  48. func (b *Block) ValidateBasic() error {
  49. if b == nil {
  50. return errors.New("Nil blocks are invalid")
  51. }
  52. b.mtx.Lock()
  53. defer b.mtx.Unlock()
  54. newTxs := int64(len(b.Data.Txs))
  55. if b.NumTxs != newTxs {
  56. return fmt.Errorf("Wrong Block.Header.NumTxs. Expected %v, got %v", newTxs, b.NumTxs)
  57. }
  58. if !bytes.Equal(b.LastCommitHash, b.LastCommit.Hash()) {
  59. return fmt.Errorf("Wrong Block.Header.LastCommitHash. Expected %v, got %v", b.LastCommitHash, b.LastCommit.Hash())
  60. }
  61. if b.Header.Height != 1 {
  62. if err := b.LastCommit.ValidateBasic(); err != nil {
  63. return err
  64. }
  65. }
  66. if !bytes.Equal(b.DataHash, b.Data.Hash()) {
  67. return fmt.Errorf("Wrong Block.Header.DataHash. Expected %v, got %v", b.DataHash, b.Data.Hash())
  68. }
  69. if !bytes.Equal(b.EvidenceHash, b.Evidence.Hash()) {
  70. return errors.New(cmn.Fmt("Wrong Block.Header.EvidenceHash. Expected %v, got %v", b.EvidenceHash, b.Evidence.Hash()))
  71. }
  72. return nil
  73. }
  74. // fillHeader fills in any remaining header fields that are a function of the block data
  75. func (b *Block) fillHeader() {
  76. if b.LastCommitHash == nil {
  77. b.LastCommitHash = b.LastCommit.Hash()
  78. }
  79. if b.DataHash == nil {
  80. b.DataHash = b.Data.Hash()
  81. }
  82. if b.EvidenceHash == nil {
  83. b.EvidenceHash = b.Evidence.Hash()
  84. }
  85. }
  86. // Hash computes and returns the block hash.
  87. // If the block is incomplete, block hash is nil for safety.
  88. func (b *Block) Hash() cmn.HexBytes {
  89. if b == nil {
  90. return nil
  91. }
  92. b.mtx.Lock()
  93. defer b.mtx.Unlock()
  94. if b == nil || b.LastCommit == nil {
  95. return nil
  96. }
  97. b.fillHeader()
  98. return b.Header.Hash()
  99. }
  100. // MakePartSet returns a PartSet containing parts of a serialized block.
  101. // This is the form in which the block is gossipped to peers.
  102. // CONTRACT: partSize is greater than zero.
  103. func (b *Block) MakePartSet(partSize int) *PartSet {
  104. if b == nil {
  105. return nil
  106. }
  107. b.mtx.Lock()
  108. defer b.mtx.Unlock()
  109. // We prefix the byte length, so that unmarshaling
  110. // can easily happen via a reader.
  111. bz, err := cdc.MarshalBinary(b)
  112. if err != nil {
  113. panic(err)
  114. }
  115. return NewPartSetFromData(bz, partSize)
  116. }
  117. // HashesTo is a convenience function that checks if a block hashes to the given argument.
  118. // Returns false if the block is nil or the hash is empty.
  119. func (b *Block) HashesTo(hash []byte) bool {
  120. if len(hash) == 0 {
  121. return false
  122. }
  123. if b == nil {
  124. return false
  125. }
  126. return bytes.Equal(b.Hash(), hash)
  127. }
  128. // Size returns size of the block in bytes.
  129. func (b *Block) Size() int {
  130. bz, err := cdc.MarshalBinaryBare(b)
  131. if err != nil {
  132. return 0
  133. }
  134. return len(bz)
  135. }
  136. // String returns a string representation of the block
  137. func (b *Block) String() string {
  138. return b.StringIndented("")
  139. }
  140. // StringIndented returns a string representation of the block
  141. func (b *Block) StringIndented(indent string) string {
  142. if b == nil {
  143. return "nil-Block"
  144. }
  145. return fmt.Sprintf(`Block{
  146. %s %v
  147. %s %v
  148. %s %v
  149. %s %v
  150. %s}#%v`,
  151. indent, b.Header.StringIndented(indent+" "),
  152. indent, b.Data.StringIndented(indent+" "),
  153. indent, b.Evidence.StringIndented(indent+" "),
  154. indent, b.LastCommit.StringIndented(indent+" "),
  155. indent, b.Hash())
  156. }
  157. // StringShort returns a shortened string representation of the block
  158. func (b *Block) StringShort() string {
  159. if b == nil {
  160. return "nil-Block"
  161. }
  162. return fmt.Sprintf("Block#%v", b.Hash())
  163. }
  164. //-----------------------------------------------------------------------------
  165. // Header defines the structure of a Tendermint block header
  166. // TODO: limit header size
  167. // NOTE: changes to the Header should be duplicated in the abci Header
  168. type Header struct {
  169. // basic block info
  170. ChainID string `json:"chain_id"`
  171. Height int64 `json:"height"`
  172. Time time.Time `json:"time"`
  173. NumTxs int64 `json:"num_txs"`
  174. // prev block info
  175. LastBlockID BlockID `json:"last_block_id"`
  176. TotalTxs int64 `json:"total_txs"`
  177. // hashes of block data
  178. LastCommitHash cmn.HexBytes `json:"last_commit_hash"` // commit from validators from the last block
  179. DataHash cmn.HexBytes `json:"data_hash"` // transactions
  180. // hashes from the app output from the prev block
  181. ValidatorsHash cmn.HexBytes `json:"validators_hash"` // validators for the current block
  182. ConsensusHash cmn.HexBytes `json:"consensus_hash"` // consensus params for current block
  183. AppHash cmn.HexBytes `json:"app_hash"` // state after txs from the previous block
  184. LastResultsHash cmn.HexBytes `json:"last_results_hash"` // root hash of all results from the txs from the previous block
  185. // consensus info
  186. EvidenceHash cmn.HexBytes `json:"evidence_hash"` // evidence included in the block
  187. }
  188. // Hash returns the hash of the header.
  189. // Returns nil if ValidatorHash is missing,
  190. // since a Header is not valid unless there is
  191. // a ValidatorsHash (corresponding to the validator set).
  192. func (h *Header) Hash() cmn.HexBytes {
  193. if h == nil || len(h.ValidatorsHash) == 0 {
  194. return nil
  195. }
  196. return merkle.SimpleHashFromMap(map[string]merkle.Hasher{
  197. "ChainID": aminoHasher(h.ChainID),
  198. "Height": aminoHasher(h.Height),
  199. "Time": aminoHasher(h.Time),
  200. "NumTxs": aminoHasher(h.NumTxs),
  201. "TotalTxs": aminoHasher(h.TotalTxs),
  202. "LastBlockID": aminoHasher(h.LastBlockID),
  203. "LastCommit": aminoHasher(h.LastCommitHash),
  204. "Data": aminoHasher(h.DataHash),
  205. "Validators": aminoHasher(h.ValidatorsHash),
  206. "App": aminoHasher(h.AppHash),
  207. "Consensus": aminoHasher(h.ConsensusHash),
  208. "Results": aminoHasher(h.LastResultsHash),
  209. "Evidence": aminoHasher(h.EvidenceHash),
  210. })
  211. }
  212. // StringIndented returns a string representation of the header
  213. func (h *Header) StringIndented(indent string) string {
  214. if h == nil {
  215. return "nil-Header"
  216. }
  217. return fmt.Sprintf(`Header{
  218. %s ChainID: %v
  219. %s Height: %v
  220. %s Time: %v
  221. %s NumTxs: %v
  222. %s TotalTxs: %v
  223. %s LastBlockID: %v
  224. %s LastCommit: %v
  225. %s Data: %v
  226. %s Validators: %v
  227. %s App: %v
  228. %s Consensus: %v
  229. %s Results: %v
  230. %s Evidence: %v
  231. %s}#%v`,
  232. indent, h.ChainID,
  233. indent, h.Height,
  234. indent, h.Time,
  235. indent, h.NumTxs,
  236. indent, h.TotalTxs,
  237. indent, h.LastBlockID,
  238. indent, h.LastCommitHash,
  239. indent, h.DataHash,
  240. indent, h.ValidatorsHash,
  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. func (commit *Commit) ValidateBasic() error {
  327. if commit.BlockID.IsZero() {
  328. return errors.New("Commit cannot be for nil block")
  329. }
  330. if len(commit.Precommits) == 0 {
  331. return errors.New("No precommits in commit")
  332. }
  333. height, round := commit.Height(), commit.Round()
  334. // validate the precommits
  335. for _, precommit := range commit.Precommits {
  336. // It's OK for precommits to be missing.
  337. if precommit == nil {
  338. continue
  339. }
  340. // Ensure that all votes are precommits
  341. if precommit.Type != VoteTypePrecommit {
  342. return fmt.Errorf("Invalid commit vote. Expected precommit, got %v",
  343. precommit.Type)
  344. }
  345. // Ensure that all heights are the same
  346. if precommit.Height != height {
  347. return fmt.Errorf("Invalid commit precommit height. Expected %v, got %v",
  348. height, precommit.Height)
  349. }
  350. // Ensure that all rounds are the same
  351. if precommit.Round != round {
  352. return fmt.Errorf("Invalid commit precommit round. Expected %v, got %v",
  353. round, precommit.Round)
  354. }
  355. }
  356. return nil
  357. }
  358. // Hash returns the hash of the commit
  359. func (commit *Commit) Hash() cmn.HexBytes {
  360. if commit == nil {
  361. return nil
  362. }
  363. if commit.hash == nil {
  364. bs := make([]merkle.Hasher, len(commit.Precommits))
  365. for i, precommit := range commit.Precommits {
  366. bs[i] = aminoHasher(precommit)
  367. }
  368. commit.hash = merkle.SimpleHashFromHashers(bs)
  369. }
  370. return commit.hash
  371. }
  372. // StringIndented returns a string representation of the commit
  373. func (commit *Commit) StringIndented(indent string) string {
  374. if commit == nil {
  375. return "nil-Commit"
  376. }
  377. precommitStrings := make([]string, len(commit.Precommits))
  378. for i, precommit := range commit.Precommits {
  379. precommitStrings[i] = precommit.String()
  380. }
  381. return fmt.Sprintf(`Commit{
  382. %s BlockID: %v
  383. %s Precommits: %v
  384. %s}#%v`,
  385. indent, commit.BlockID,
  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 *Header `json:"header"`
  393. Commit *Commit `json:"commit"`
  394. }
  395. //-----------------------------------------------------------------------------
  396. // Data contains the set of transactions included in the block
  397. type Data struct {
  398. // Txs that will be applied by state @ block.Height+1.
  399. // NOTE: not all txs here are valid. We're just agreeing on the order first.
  400. // This means that block.AppHash does not include these txs.
  401. Txs Txs `json:"txs"`
  402. // Volatile
  403. hash cmn.HexBytes
  404. }
  405. // Hash returns the hash of the data
  406. func (data *Data) Hash() cmn.HexBytes {
  407. if data == nil {
  408. return (Txs{}).Hash()
  409. }
  410. if data.hash == nil {
  411. data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs
  412. }
  413. return data.hash
  414. }
  415. // StringIndented returns a string representation of the transactions
  416. func (data *Data) StringIndented(indent string) string {
  417. if data == nil {
  418. return "nil-Data"
  419. }
  420. txStrings := make([]string, cmn.MinInt(len(data.Txs), 21))
  421. for i, tx := range data.Txs {
  422. if i == 20 {
  423. txStrings[i] = fmt.Sprintf("... (%v total)", len(data.Txs))
  424. break
  425. }
  426. txStrings[i] = fmt.Sprintf("%X (%d bytes)", tx.Hash(), len(tx))
  427. }
  428. return fmt.Sprintf(`Data{
  429. %s %v
  430. %s}#%v`,
  431. indent, strings.Join(txStrings, "\n"+indent+" "),
  432. indent, data.hash)
  433. }
  434. //-----------------------------------------------------------------------------
  435. // EvidenceData contains any evidence of malicious wrong-doing by validators
  436. type EvidenceData struct {
  437. Evidence EvidenceList `json:"evidence"`
  438. // Volatile
  439. hash cmn.HexBytes
  440. }
  441. // Hash returns the hash of the data.
  442. func (data *EvidenceData) Hash() cmn.HexBytes {
  443. if data.hash == nil {
  444. data.hash = data.Evidence.Hash()
  445. }
  446. return data.hash
  447. }
  448. // StringIndented returns a string representation of the evidence.
  449. func (data *EvidenceData) StringIndented(indent string) string {
  450. if data == nil {
  451. return "nil-Evidence"
  452. }
  453. evStrings := make([]string, cmn.MinInt(len(data.Evidence), 21))
  454. for i, ev := range data.Evidence {
  455. if i == 20 {
  456. evStrings[i] = fmt.Sprintf("... (%v total)", len(data.Evidence))
  457. break
  458. }
  459. evStrings[i] = fmt.Sprintf("Evidence:%v", ev)
  460. }
  461. return fmt.Sprintf(`EvidenceData{
  462. %s %v
  463. %s}#%v`,
  464. indent, strings.Join(evStrings, "\n"+indent+" "),
  465. indent, data.hash)
  466. return ""
  467. }
  468. //--------------------------------------------------------------------------------
  469. // BlockID defines the unique ID of a block as its Hash and its PartSetHeader
  470. type BlockID struct {
  471. Hash cmn.HexBytes `json:"hash"`
  472. PartsHeader PartSetHeader `json:"parts"`
  473. }
  474. // IsZero returns true if this is the BlockID for a nil-block
  475. func (blockID BlockID) IsZero() bool {
  476. return len(blockID.Hash) == 0 && blockID.PartsHeader.IsZero()
  477. }
  478. // Equals returns true if the BlockID matches the given BlockID
  479. func (blockID BlockID) Equals(other BlockID) bool {
  480. return bytes.Equal(blockID.Hash, other.Hash) &&
  481. blockID.PartsHeader.Equals(other.PartsHeader)
  482. }
  483. // Key returns a machine-readable string representation of the BlockID
  484. func (blockID BlockID) Key() string {
  485. bz, err := cdc.MarshalBinaryBare(blockID.PartsHeader)
  486. if err != nil {
  487. panic(err)
  488. }
  489. return string(blockID.Hash) + string(bz)
  490. }
  491. // String returns a human readable string representation of the BlockID
  492. func (blockID BlockID) String() string {
  493. return fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartsHeader)
  494. }
  495. //-------------------------------------------------------
  496. type hasher struct {
  497. item interface{}
  498. }
  499. func (h hasher) Hash() []byte {
  500. hasher := tmhash.New()
  501. if h.item != nil && !cmn.IsTypedNil(h.item) && !cmn.IsEmpty(h.item) {
  502. bz, err := cdc.MarshalBinaryBare(h.item)
  503. if err != nil {
  504. panic(err)
  505. }
  506. _, err = hasher.Write(bz)
  507. if err != nil {
  508. panic(err)
  509. }
  510. }
  511. return hasher.Sum(nil)
  512. }
  513. func aminoHash(item interface{}) []byte {
  514. h := hasher{item}
  515. return h.Hash()
  516. }
  517. func aminoHasher(item interface{}) merkle.Hasher {
  518. return hasher{item}
  519. }