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.

543 lines
15 KiB

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