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.

544 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. } 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 h == nil || 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 == nil {
  374. return (Txs{}).Hash()
  375. }
  376. if data.hash == nil {
  377. data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs
  378. }
  379. return data.hash
  380. }
  381. // StringIndented returns a string representation of the transactions
  382. func (data *Data) StringIndented(indent string) string {
  383. if data == nil {
  384. return "nil-Data"
  385. }
  386. txStrings := make([]string, cmn.MinInt(len(data.Txs), 21))
  387. for i, tx := range data.Txs {
  388. if i == 20 {
  389. txStrings[i] = fmt.Sprintf("... (%v total)", len(data.Txs))
  390. break
  391. }
  392. txStrings[i] = fmt.Sprintf("Tx:%v", tx)
  393. }
  394. return fmt.Sprintf(`Data{
  395. %s %v
  396. %s}#%v`,
  397. indent, strings.Join(txStrings, "\n"+indent+" "),
  398. indent, data.hash)
  399. }
  400. //-----------------------------------------------------------------------------
  401. // EvidenceData contains any evidence of malicious wrong-doing by validators
  402. type EvidenceData struct {
  403. Evidence EvidenceList `json:"evidence"`
  404. // Volatile
  405. hash cmn.HexBytes
  406. }
  407. // Hash returns the hash of the data.
  408. func (data *EvidenceData) Hash() cmn.HexBytes {
  409. if data.hash == nil {
  410. data.hash = data.Evidence.Hash()
  411. }
  412. return data.hash
  413. }
  414. // StringIndented returns a string representation of the evidence.
  415. func (data *EvidenceData) StringIndented(indent string) string {
  416. if data == nil {
  417. return "nil-Evidence"
  418. }
  419. evStrings := make([]string, cmn.MinInt(len(data.Evidence), 21))
  420. for i, ev := range data.Evidence {
  421. if i == 20 {
  422. evStrings[i] = fmt.Sprintf("... (%v total)", len(data.Evidence))
  423. break
  424. }
  425. evStrings[i] = fmt.Sprintf("Evidence:%v", ev)
  426. }
  427. return fmt.Sprintf(`Data{
  428. %s %v
  429. %s}#%v`,
  430. indent, strings.Join(evStrings, "\n"+indent+" "),
  431. indent, data.hash)
  432. return ""
  433. }
  434. //--------------------------------------------------------------------------------
  435. // BlockID defines the unique ID of a block as its Hash and its PartSetHeader
  436. type BlockID struct {
  437. Hash cmn.HexBytes `json:"hash"`
  438. PartsHeader PartSetHeader `json:"parts"`
  439. }
  440. // IsZero returns true if this is the BlockID for a nil-block
  441. func (blockID BlockID) IsZero() bool {
  442. return len(blockID.Hash) == 0 && blockID.PartsHeader.IsZero()
  443. }
  444. // Equals returns true if the BlockID matches the given BlockID
  445. func (blockID BlockID) Equals(other BlockID) bool {
  446. return bytes.Equal(blockID.Hash, other.Hash) &&
  447. blockID.PartsHeader.Equals(other.PartsHeader)
  448. }
  449. // Key returns a machine-readable string representation of the BlockID
  450. func (blockID BlockID) Key() string {
  451. bz, err := wire.MarshalBinary(blockID.PartsHeader)
  452. if err != nil {
  453. panic(err)
  454. }
  455. return string(blockID.Hash) + string(bz)
  456. }
  457. // String returns a human readable string representation of the BlockID
  458. func (blockID BlockID) String() string {
  459. return fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartsHeader)
  460. }
  461. //-------------------------------------------------------
  462. type hasher struct {
  463. item interface{}
  464. }
  465. func (h hasher) Hash() []byte {
  466. hasher := ripemd160.New()
  467. bz, err := wire.MarshalBinary(h.item)
  468. if err != nil {
  469. panic(err)
  470. }
  471. _, err = hasher.Write(bz)
  472. if err != nil {
  473. panic(err)
  474. }
  475. return hasher.Sum(nil)
  476. }
  477. func tmHash(item interface{}) []byte {
  478. h := hasher{item}
  479. return h.Hash()
  480. }
  481. func wireHasher(item interface{}) merkle.Hasher {
  482. return hasher{item}
  483. }