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.

545 lines
15 KiB

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