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.

541 lines
15 KiB

6 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
6 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. // If all precommits are nil, it returns an empty precommit with height 0.
  232. func (commit *Commit) FirstPrecommit() *Vote {
  233. if len(commit.Precommits) == 0 {
  234. return nil
  235. }
  236. if commit.firstPrecommit != nil {
  237. return commit.firstPrecommit
  238. }
  239. for _, precommit := range commit.Precommits {
  240. if precommit != nil {
  241. commit.firstPrecommit = precommit
  242. return precommit
  243. }
  244. }
  245. return &Vote{
  246. Type: VoteTypePrecommit,
  247. }
  248. }
  249. // Height returns the height of the commit
  250. func (commit *Commit) Height() int64 {
  251. if len(commit.Precommits) == 0 {
  252. return 0
  253. }
  254. return commit.FirstPrecommit().Height
  255. }
  256. // Round returns the round of the commit
  257. func (commit *Commit) Round() int {
  258. if len(commit.Precommits) == 0 {
  259. return 0
  260. }
  261. return commit.FirstPrecommit().Round
  262. }
  263. // Type returns the vote type of the commit, which is always VoteTypePrecommit
  264. func (commit *Commit) Type() byte {
  265. return VoteTypePrecommit
  266. }
  267. // Size returns the number of votes in the commit
  268. func (commit *Commit) Size() int {
  269. if commit == nil {
  270. return 0
  271. }
  272. return len(commit.Precommits)
  273. }
  274. // BitArray returns a BitArray of which validators voted in this commit
  275. func (commit *Commit) BitArray() *cmn.BitArray {
  276. if commit.bitArray == nil {
  277. commit.bitArray = cmn.NewBitArray(len(commit.Precommits))
  278. for i, precommit := range commit.Precommits {
  279. // TODO: need to check the BlockID otherwise we could be counting conflicts,
  280. // not just the one with +2/3 !
  281. commit.bitArray.SetIndex(i, precommit != nil)
  282. }
  283. }
  284. return commit.bitArray
  285. }
  286. // GetByIndex returns the vote corresponding to a given validator index
  287. func (commit *Commit) GetByIndex(index int) *Vote {
  288. return commit.Precommits[index]
  289. }
  290. // IsCommit returns true if there is at least one vote
  291. func (commit *Commit) IsCommit() bool {
  292. return len(commit.Precommits) != 0
  293. }
  294. // ValidateBasic performs basic validation that doesn't involve state data.
  295. func (commit *Commit) ValidateBasic() error {
  296. if commit.BlockID.IsZero() {
  297. return errors.New("Commit cannot be for nil block")
  298. }
  299. if len(commit.Precommits) == 0 {
  300. return errors.New("No precommits in commit")
  301. }
  302. height, round := commit.Height(), commit.Round()
  303. // validate the precommits
  304. for _, precommit := range commit.Precommits {
  305. // It's OK for precommits to be missing.
  306. if precommit == nil {
  307. continue
  308. }
  309. // Ensure that all votes are precommits
  310. if precommit.Type != VoteTypePrecommit {
  311. return fmt.Errorf("Invalid commit vote. Expected precommit, got %v",
  312. precommit.Type)
  313. }
  314. // Ensure that all heights are the same
  315. if precommit.Height != height {
  316. return fmt.Errorf("Invalid commit precommit height. Expected %v, got %v",
  317. height, precommit.Height)
  318. }
  319. // Ensure that all rounds are the same
  320. if precommit.Round != round {
  321. return fmt.Errorf("Invalid commit precommit round. Expected %v, got %v",
  322. round, precommit.Round)
  323. }
  324. }
  325. return nil
  326. }
  327. // Hash returns the hash of the commit
  328. func (commit *Commit) Hash() cmn.HexBytes {
  329. if commit.hash == nil {
  330. bs := make([]merkle.Hasher, len(commit.Precommits))
  331. for i, precommit := range commit.Precommits {
  332. bs[i] = wireHasher(precommit)
  333. }
  334. commit.hash = merkle.SimpleHashFromHashers(bs)
  335. }
  336. return commit.hash
  337. }
  338. // StringIndented returns a string representation of the commit
  339. func (commit *Commit) StringIndented(indent string) string {
  340. if commit == nil {
  341. return "nil-Commit"
  342. }
  343. precommitStrings := make([]string, len(commit.Precommits))
  344. for i, precommit := range commit.Precommits {
  345. precommitStrings[i] = precommit.String()
  346. }
  347. return fmt.Sprintf(`Commit{
  348. %s BlockID: %v
  349. %s Precommits: %v
  350. %s}#%v`,
  351. indent, commit.BlockID,
  352. indent, strings.Join(precommitStrings, "\n"+indent+" "),
  353. indent, commit.hash)
  354. }
  355. //-----------------------------------------------------------------------------
  356. // SignedHeader is a header along with the commits that prove it
  357. type SignedHeader struct {
  358. Header *Header `json:"header"`
  359. Commit *Commit `json:"commit"`
  360. }
  361. //-----------------------------------------------------------------------------
  362. // Data contains the set of transactions included in the block
  363. type Data struct {
  364. // Txs that will be applied by state @ block.Height+1.
  365. // NOTE: not all txs here are valid. We're just agreeing on the order first.
  366. // This means that block.AppHash does not include these txs.
  367. Txs Txs `json:"txs"`
  368. // Volatile
  369. hash cmn.HexBytes
  370. }
  371. // Hash returns the hash of the data
  372. func (data *Data) Hash() cmn.HexBytes {
  373. if data.hash == nil {
  374. data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs
  375. }
  376. return data.hash
  377. }
  378. // StringIndented returns a string representation of the transactions
  379. func (data *Data) StringIndented(indent string) string {
  380. if data == nil {
  381. return "nil-Data"
  382. }
  383. txStrings := make([]string, cmn.MinInt(len(data.Txs), 21))
  384. for i, tx := range data.Txs {
  385. if i == 20 {
  386. txStrings[i] = fmt.Sprintf("... (%v total)", len(data.Txs))
  387. break
  388. }
  389. txStrings[i] = fmt.Sprintf("Tx:%v", tx)
  390. }
  391. return fmt.Sprintf(`Data{
  392. %s %v
  393. %s}#%v`,
  394. indent, strings.Join(txStrings, "\n"+indent+" "),
  395. indent, data.hash)
  396. }
  397. //-----------------------------------------------------------------------------
  398. // EvidenceData contains any evidence of malicious wrong-doing by validators
  399. type EvidenceData struct {
  400. Evidence EvidenceList `json:"evidence"`
  401. // Volatile
  402. hash cmn.HexBytes
  403. }
  404. // Hash returns the hash of the data.
  405. func (data *EvidenceData) Hash() cmn.HexBytes {
  406. if data.hash == nil {
  407. data.hash = data.Evidence.Hash()
  408. }
  409. return data.hash
  410. }
  411. // StringIndented returns a string representation of the evidence.
  412. func (data *EvidenceData) StringIndented(indent string) string {
  413. if data == nil {
  414. return "nil-Evidence"
  415. }
  416. evStrings := make([]string, cmn.MinInt(len(data.Evidence), 21))
  417. for i, ev := range data.Evidence {
  418. if i == 20 {
  419. evStrings[i] = fmt.Sprintf("... (%v total)", len(data.Evidence))
  420. break
  421. }
  422. evStrings[i] = fmt.Sprintf("Evidence:%v", ev)
  423. }
  424. return fmt.Sprintf(`Data{
  425. %s %v
  426. %s}#%v`,
  427. indent, strings.Join(evStrings, "\n"+indent+" "),
  428. indent, data.hash)
  429. return ""
  430. }
  431. //--------------------------------------------------------------------------------
  432. // BlockID defines the unique ID of a block as its Hash and its PartSetHeader
  433. type BlockID struct {
  434. Hash cmn.HexBytes `json:"hash"`
  435. PartsHeader PartSetHeader `json:"parts"`
  436. }
  437. // IsZero returns true if this is the BlockID for a nil-block
  438. func (blockID BlockID) IsZero() bool {
  439. return len(blockID.Hash) == 0 && blockID.PartsHeader.IsZero()
  440. }
  441. // Equals returns true if the BlockID matches the given BlockID
  442. func (blockID BlockID) Equals(other BlockID) bool {
  443. return bytes.Equal(blockID.Hash, other.Hash) &&
  444. blockID.PartsHeader.Equals(other.PartsHeader)
  445. }
  446. // Key returns a machine-readable string representation of the BlockID
  447. func (blockID BlockID) Key() string {
  448. bz, err := wire.MarshalBinary(blockID.PartsHeader)
  449. if err != nil {
  450. panic(err)
  451. }
  452. return string(blockID.Hash) + string(bz)
  453. }
  454. // String returns a human readable string representation of the BlockID
  455. func (blockID BlockID) String() string {
  456. return fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartsHeader)
  457. }
  458. //-------------------------------------------------------
  459. type hasher struct {
  460. item interface{}
  461. }
  462. func (h hasher) Hash() []byte {
  463. hasher := ripemd160.New()
  464. bz, err := wire.MarshalBinary(h.item)
  465. if err != nil {
  466. panic(err)
  467. }
  468. _, err = hasher.Write(bz)
  469. if err != nil {
  470. panic(err)
  471. }
  472. return hasher.Sum(nil)
  473. }
  474. func tmHash(item interface{}) []byte {
  475. h := hasher{item}
  476. return h.Hash()
  477. }
  478. func wireHasher(item interface{}) merkle.Hasher {
  479. return hasher{item}
  480. }