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.

538 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
9 years ago
7 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. "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. } else {
  132. return fmt.Sprintf("Block#%v", b.Hash())
  133. }
  134. }
  135. //-----------------------------------------------------------------------------
  136. // Header defines the structure of a Tendermint block header
  137. // TODO: limit header size
  138. // NOTE: changes to the Header should be duplicated in the abci Header
  139. type Header struct {
  140. // basic block info
  141. ChainID string `json:"chain_id"`
  142. Height int64 `json:"height"`
  143. Time time.Time `json:"time"`
  144. NumTxs int64 `json:"num_txs"`
  145. // prev block info
  146. LastBlockID BlockID `json:"last_block_id"`
  147. TotalTxs int64 `json:"total_txs"`
  148. // hashes of block data
  149. LastCommitHash cmn.HexBytes `json:"last_commit_hash"` // commit from validators from the last block
  150. DataHash cmn.HexBytes `json:"data_hash"` // transactions
  151. // hashes from the app output from the prev block
  152. ValidatorsHash cmn.HexBytes `json:"validators_hash"` // validators for the current block
  153. ConsensusHash cmn.HexBytes `json:"consensus_hash"` // consensus params for current block
  154. AppHash cmn.HexBytes `json:"app_hash"` // state after txs from the previous block
  155. LastResultsHash cmn.HexBytes `json:"last_results_hash"` // root hash of all results from the txs from the previous block
  156. // consensus info
  157. EvidenceHash cmn.HexBytes `json:"evidence_hash"` // evidence included in the block
  158. }
  159. // Hash returns the hash of the header.
  160. // Returns nil if ValidatorHash is missing.
  161. func (h *Header) Hash() cmn.HexBytes {
  162. if len(h.ValidatorsHash) == 0 {
  163. return nil
  164. }
  165. return merkle.SimpleHashFromMap(map[string]merkle.Hasher{
  166. "ChainID": wireHasher(h.ChainID),
  167. "Height": wireHasher(h.Height),
  168. "Time": wireHasher(h.Time),
  169. "NumTxs": wireHasher(h.NumTxs),
  170. "TotalTxs": wireHasher(h.TotalTxs),
  171. "LastBlockID": wireHasher(h.LastBlockID),
  172. "LastCommit": wireHasher(h.LastCommitHash),
  173. "Data": wireHasher(h.DataHash),
  174. "Validators": wireHasher(h.ValidatorsHash),
  175. "App": wireHasher(h.AppHash),
  176. "Consensus": wireHasher(h.ConsensusHash),
  177. "Results": wireHasher(h.LastResultsHash),
  178. "Evidence": wireHasher(h.EvidenceHash),
  179. })
  180. }
  181. // StringIndented returns a string representation of the header
  182. func (h *Header) StringIndented(indent string) string {
  183. if h == nil {
  184. return "nil-Header"
  185. }
  186. return fmt.Sprintf(`Header{
  187. %s ChainID: %v
  188. %s Height: %v
  189. %s Time: %v
  190. %s NumTxs: %v
  191. %s TotalTxs: %v
  192. %s LastBlockID: %v
  193. %s LastCommit: %v
  194. %s Data: %v
  195. %s Validators: %v
  196. %s App: %v
  197. %s Conensus: %v
  198. %s Results: %v
  199. %s Evidence: %v
  200. %s}#%v`,
  201. indent, h.ChainID,
  202. indent, h.Height,
  203. indent, h.Time,
  204. indent, h.NumTxs,
  205. indent, h.TotalTxs,
  206. indent, h.LastBlockID,
  207. indent, h.LastCommitHash,
  208. indent, h.DataHash,
  209. indent, h.ValidatorsHash,
  210. indent, h.AppHash,
  211. indent, h.ConsensusHash,
  212. indent, h.LastResultsHash,
  213. indent, h.EvidenceHash,
  214. indent, h.Hash())
  215. }
  216. //-------------------------------------
  217. // Commit contains the evidence that a block was committed by a set of validators.
  218. // NOTE: Commit is empty for height 1, but never nil.
  219. type Commit struct {
  220. // NOTE: The Precommits are in order of address to preserve the bonded ValidatorSet order.
  221. // Any peer with a block can gossip precommits by index with a peer without recalculating the
  222. // active ValidatorSet.
  223. BlockID BlockID `json:"blockID"`
  224. Precommits []*Vote `json:"precommits"`
  225. // Volatile
  226. firstPrecommit *Vote
  227. hash cmn.HexBytes
  228. bitArray *cmn.BitArray
  229. }
  230. // FirstPrecommit returns the first non-nil precommit in the commit
  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 nil
  245. }
  246. // Height returns the height of the commit
  247. func (commit *Commit) Height() int64 {
  248. if len(commit.Precommits) == 0 {
  249. return 0
  250. }
  251. return commit.FirstPrecommit().Height
  252. }
  253. // Round returns the round of the commit
  254. func (commit *Commit) Round() int {
  255. if len(commit.Precommits) == 0 {
  256. return 0
  257. }
  258. return commit.FirstPrecommit().Round
  259. }
  260. // Type returns the vote type of the commit, which is always VoteTypePrecommit
  261. func (commit *Commit) Type() byte {
  262. return VoteTypePrecommit
  263. }
  264. // Size returns the number of votes in the commit
  265. func (commit *Commit) Size() int {
  266. if commit == nil {
  267. return 0
  268. }
  269. return len(commit.Precommits)
  270. }
  271. // BitArray returns a BitArray of which validators voted in this commit
  272. func (commit *Commit) BitArray() *cmn.BitArray {
  273. if commit.bitArray == nil {
  274. commit.bitArray = cmn.NewBitArray(len(commit.Precommits))
  275. for i, precommit := range commit.Precommits {
  276. // TODO: need to check the BlockID otherwise we could be counting conflicts,
  277. // not just the one with +2/3 !
  278. commit.bitArray.SetIndex(i, precommit != nil)
  279. }
  280. }
  281. return commit.bitArray
  282. }
  283. // GetByIndex returns the vote corresponding to a given validator index
  284. func (commit *Commit) GetByIndex(index int) *Vote {
  285. return commit.Precommits[index]
  286. }
  287. // IsCommit returns true if there is at least one vote
  288. func (commit *Commit) IsCommit() bool {
  289. return len(commit.Precommits) != 0
  290. }
  291. // ValidateBasic performs basic validation that doesn't involve state data.
  292. func (commit *Commit) ValidateBasic() error {
  293. if commit.BlockID.IsZero() {
  294. return errors.New("Commit cannot be for nil block")
  295. }
  296. if len(commit.Precommits) == 0 {
  297. return errors.New("No precommits in commit")
  298. }
  299. height, round := commit.Height(), commit.Round()
  300. // validate the precommits
  301. for _, precommit := range commit.Precommits {
  302. // It's OK for precommits to be missing.
  303. if precommit == nil {
  304. continue
  305. }
  306. // Ensure that all votes are precommits
  307. if precommit.Type != VoteTypePrecommit {
  308. return fmt.Errorf("Invalid commit vote. Expected precommit, got %v",
  309. precommit.Type)
  310. }
  311. // Ensure that all heights are the same
  312. if precommit.Height != height {
  313. return fmt.Errorf("Invalid commit precommit height. Expected %v, got %v",
  314. height, precommit.Height)
  315. }
  316. // Ensure that all rounds are the same
  317. if precommit.Round != round {
  318. return fmt.Errorf("Invalid commit precommit round. Expected %v, got %v",
  319. round, precommit.Round)
  320. }
  321. }
  322. return nil
  323. }
  324. // Hash returns the hash of the commit
  325. func (commit *Commit) Hash() cmn.HexBytes {
  326. if commit.hash == nil {
  327. bs := make([]merkle.Hasher, len(commit.Precommits))
  328. for i, precommit := range commit.Precommits {
  329. bs[i] = wireHasher(precommit)
  330. }
  331. commit.hash = merkle.SimpleHashFromHashers(bs)
  332. }
  333. return commit.hash
  334. }
  335. // StringIndented returns a string representation of the commit
  336. func (commit *Commit) StringIndented(indent string) string {
  337. if commit == nil {
  338. return "nil-Commit"
  339. }
  340. precommitStrings := make([]string, len(commit.Precommits))
  341. for i, precommit := range commit.Precommits {
  342. precommitStrings[i] = precommit.String()
  343. }
  344. return fmt.Sprintf(`Commit{
  345. %s BlockID: %v
  346. %s Precommits: %v
  347. %s}#%v`,
  348. indent, commit.BlockID,
  349. indent, strings.Join(precommitStrings, "\n"+indent+" "),
  350. indent, commit.hash)
  351. }
  352. //-----------------------------------------------------------------------------
  353. // SignedHeader is a header along with the commits that prove it
  354. type SignedHeader struct {
  355. Header *Header `json:"header"`
  356. Commit *Commit `json:"commit"`
  357. }
  358. //-----------------------------------------------------------------------------
  359. // Data contains the set of transactions included in the block
  360. type Data struct {
  361. // Txs that will be applied by state @ block.Height+1.
  362. // NOTE: not all txs here are valid. We're just agreeing on the order first.
  363. // This means that block.AppHash does not include these txs.
  364. Txs Txs `json:"txs"`
  365. // Volatile
  366. hash cmn.HexBytes
  367. }
  368. // Hash returns the hash of the data
  369. func (data *Data) Hash() cmn.HexBytes {
  370. if data.hash == nil {
  371. data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs
  372. }
  373. return data.hash
  374. }
  375. // StringIndented returns a string representation of the transactions
  376. func (data *Data) StringIndented(indent string) string {
  377. if data == nil {
  378. return "nil-Data"
  379. }
  380. txStrings := make([]string, cmn.MinInt(len(data.Txs), 21))
  381. for i, tx := range data.Txs {
  382. if i == 20 {
  383. txStrings[i] = fmt.Sprintf("... (%v total)", len(data.Txs))
  384. break
  385. }
  386. txStrings[i] = fmt.Sprintf("Tx:%v", tx)
  387. }
  388. return fmt.Sprintf(`Data{
  389. %s %v
  390. %s}#%v`,
  391. indent, strings.Join(txStrings, "\n"+indent+" "),
  392. indent, data.hash)
  393. }
  394. //-----------------------------------------------------------------------------
  395. // EvidenceData contains any evidence of malicious wrong-doing by validators
  396. type EvidenceData struct {
  397. Evidence EvidenceList `json:"evidence"`
  398. // Volatile
  399. hash cmn.HexBytes
  400. }
  401. // Hash returns the hash of the data.
  402. func (data *EvidenceData) Hash() cmn.HexBytes {
  403. if data.hash == nil {
  404. data.hash = data.Evidence.Hash()
  405. }
  406. return data.hash
  407. }
  408. // StringIndented returns a string representation of the evidence.
  409. func (data *EvidenceData) StringIndented(indent string) string {
  410. if data == nil {
  411. return "nil-Evidence"
  412. }
  413. evStrings := make([]string, cmn.MinInt(len(data.Evidence), 21))
  414. for i, ev := range data.Evidence {
  415. if i == 20 {
  416. evStrings[i] = fmt.Sprintf("... (%v total)", len(data.Evidence))
  417. break
  418. }
  419. evStrings[i] = fmt.Sprintf("Evidence:%v", ev)
  420. }
  421. return fmt.Sprintf(`Data{
  422. %s %v
  423. %s}#%v`,
  424. indent, strings.Join(evStrings, "\n"+indent+" "),
  425. indent, data.hash)
  426. return ""
  427. }
  428. //--------------------------------------------------------------------------------
  429. // BlockID defines the unique ID of a block as its Hash and its PartSetHeader
  430. type BlockID struct {
  431. Hash cmn.HexBytes `json:"hash"`
  432. PartsHeader PartSetHeader `json:"parts"`
  433. }
  434. // IsZero returns true if this is the BlockID for a nil-block
  435. func (blockID BlockID) IsZero() bool {
  436. return len(blockID.Hash) == 0 && blockID.PartsHeader.IsZero()
  437. }
  438. // Equals returns true if the BlockID matches the given BlockID
  439. func (blockID BlockID) Equals(other BlockID) bool {
  440. return bytes.Equal(blockID.Hash, other.Hash) &&
  441. blockID.PartsHeader.Equals(other.PartsHeader)
  442. }
  443. // Key returns a machine-readable string representation of the BlockID
  444. func (blockID BlockID) Key() string {
  445. bz, err := wire.MarshalBinary(blockID.PartsHeader)
  446. if err != nil {
  447. panic(err)
  448. }
  449. return string(blockID.Hash) + string(bz)
  450. }
  451. // String returns a human readable string representation of the BlockID
  452. func (blockID BlockID) String() string {
  453. return fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartsHeader)
  454. }
  455. //-------------------------------------------------------
  456. type hasher struct {
  457. item interface{}
  458. }
  459. func (h hasher) Hash() []byte {
  460. hasher := ripemd160.New()
  461. bz, err := wire.MarshalBinary(h.item)
  462. if err != nil {
  463. panic(err)
  464. }
  465. _, err = hasher.Write(bz)
  466. if err != nil {
  467. panic(err)
  468. }
  469. return hasher.Sum(nil)
  470. }
  471. func tmHash(item interface{}) []byte {
  472. h := hasher{item}
  473. return h.Hash()
  474. }
  475. func wireHasher(item interface{}) merkle.Hasher {
  476. return hasher{item}
  477. }