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.

568 lines
15 KiB

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