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.

479 lines
14 KiB

7 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
  1. package types
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "strings"
  8. "time"
  9. wire "github.com/tendermint/go-wire"
  10. "github.com/tendermint/go-wire/data"
  11. cmn "github.com/tendermint/tmlibs/common"
  12. "github.com/tendermint/tmlibs/merkle"
  13. )
  14. // Block defines the atomic unit of a Tendermint blockchain.
  15. type Block struct {
  16. *Header `json:"header"`
  17. *Data `json:"data"`
  18. LastCommit *Commit `json:"last_commit"`
  19. }
  20. // MakeBlock returns a new block and corresponding partset from the given information.
  21. // TODO: Add version information to the Block struct.
  22. func MakeBlock(height int64, chainID string, txs []Tx,
  23. totalTxs int64, commit *Commit,
  24. prevBlockID BlockID, valHash, appHash, consensusHash []byte,
  25. partSize int) (*Block, *PartSet) {
  26. newTxs := int64(len(txs))
  27. block := &Block{
  28. Header: &Header{
  29. ChainID: chainID,
  30. Height: height,
  31. Time: time.Now(),
  32. NumTxs: newTxs,
  33. TotalTxs: totalTxs + newTxs,
  34. LastBlockID: prevBlockID,
  35. ValidatorsHash: valHash,
  36. AppHash: appHash, // state merkle root of txs from the previous block.
  37. ConsensusHash: consensusHash,
  38. },
  39. LastCommit: commit,
  40. Data: &Data{
  41. Txs: txs,
  42. },
  43. }
  44. block.FillHeader()
  45. return block, block.MakePartSet(partSize)
  46. }
  47. // ValidateBasic performs basic validation that doesn't involve state data.
  48. func (b *Block) ValidateBasic(chainID string, lastBlockHeight int64,
  49. lastBlockTotalTx int64, lastBlockID BlockID,
  50. lastBlockTime time.Time, appHash, consensusHash []byte) error {
  51. if b.ChainID != chainID {
  52. return errors.New(cmn.Fmt("Wrong Block.Header.ChainID. Expected %v, got %v", chainID, b.ChainID))
  53. }
  54. if b.Height != lastBlockHeight+1 {
  55. return errors.New(cmn.Fmt("Wrong Block.Header.Height. Expected %v, got %v", lastBlockHeight+1, b.Height))
  56. }
  57. /* TODO: Determine bounds for Time
  58. See blockchain/reactor "stopSyncingDurationMinutes"
  59. if !b.Time.After(lastBlockTime) {
  60. return errors.New("Invalid Block.Header.Time")
  61. }
  62. */
  63. newTxs := int64(len(b.Data.Txs))
  64. if b.NumTxs != newTxs {
  65. return errors.New(cmn.Fmt("Wrong Block.Header.NumTxs. Expected %v, got %v", newTxs, b.NumTxs))
  66. }
  67. if b.TotalTxs != lastBlockTotalTx+newTxs {
  68. return errors.New(cmn.Fmt("Wrong Block.Header.TotalTxs. Expected %v, got %v", lastBlockTotalTx+newTxs, b.TotalTxs))
  69. }
  70. if !b.LastBlockID.Equals(lastBlockID) {
  71. return errors.New(cmn.Fmt("Wrong Block.Header.LastBlockID. Expected %v, got %v", lastBlockID, b.LastBlockID))
  72. }
  73. if !bytes.Equal(b.LastCommitHash, b.LastCommit.Hash()) {
  74. return errors.New(cmn.Fmt("Wrong Block.Header.LastCommitHash. Expected %v, got %v", b.LastCommitHash, b.LastCommit.Hash()))
  75. }
  76. if b.Header.Height != 1 {
  77. if err := b.LastCommit.ValidateBasic(); err != nil {
  78. return err
  79. }
  80. }
  81. if !bytes.Equal(b.DataHash, b.Data.Hash()) {
  82. return errors.New(cmn.Fmt("Wrong Block.Header.DataHash. Expected %v, got %v", b.DataHash, b.Data.Hash()))
  83. }
  84. if !bytes.Equal(b.AppHash, appHash) {
  85. return errors.New(cmn.Fmt("Wrong Block.Header.AppHash. Expected %X, got %v", appHash, b.AppHash))
  86. }
  87. if !bytes.Equal(b.ConsensusHash, consensusHash) {
  88. return errors.New(cmn.Fmt("Wrong Block.Header.ConsensusHash. Expected %X, got %v", consensusHash, b.ConsensusHash))
  89. }
  90. // NOTE: the AppHash and ValidatorsHash are validated later.
  91. return nil
  92. }
  93. // FillHeader fills in any remaining header fields that are a function of the block data
  94. func (b *Block) FillHeader() {
  95. if b.LastCommitHash == nil {
  96. b.LastCommitHash = b.LastCommit.Hash()
  97. }
  98. if b.DataHash == nil {
  99. b.DataHash = b.Data.Hash()
  100. }
  101. }
  102. // Hash computes and returns the block hash.
  103. // If the block is incomplete, block hash is nil for safety.
  104. func (b *Block) Hash() data.Bytes {
  105. // fmt.Println(">>", b.Data)
  106. if b == nil || b.Header == nil || b.Data == nil || b.LastCommit == nil {
  107. return nil
  108. }
  109. b.FillHeader()
  110. return b.Header.Hash()
  111. }
  112. // MakePartSet returns a PartSet containing parts of a serialized block.
  113. // This is the form in which the block is gossipped to peers.
  114. func (b *Block) MakePartSet(partSize int) *PartSet {
  115. return NewPartSetFromData(wire.BinaryBytes(b), partSize)
  116. }
  117. // HashesTo is a convenience function that checks if a block hashes to the given argument.
  118. // A nil block never hashes to anything, and nothing hashes to a nil hash.
  119. func (b *Block) HashesTo(hash []byte) bool {
  120. if len(hash) == 0 {
  121. return false
  122. }
  123. if b == nil {
  124. return false
  125. }
  126. return bytes.Equal(b.Hash(), hash)
  127. }
  128. // String returns a string representation of the block
  129. func (b *Block) String() string {
  130. return b.StringIndented("")
  131. }
  132. // StringIndented returns a string representation of the block
  133. func (b *Block) StringIndented(indent string) string {
  134. if b == nil {
  135. return "nil-Block"
  136. }
  137. return fmt.Sprintf(`Block{
  138. %s %v
  139. %s %v
  140. %s %v
  141. %s}#%v`,
  142. indent, b.Header.StringIndented(indent+" "),
  143. indent, b.Data.StringIndented(indent+" "),
  144. indent, b.LastCommit.StringIndented(indent+" "),
  145. indent, b.Hash())
  146. }
  147. // StringShort returns a shortened string representation of the block
  148. func (b *Block) StringShort() string {
  149. if b == nil {
  150. return "nil-Block"
  151. } else {
  152. return fmt.Sprintf("Block#%v", b.Hash())
  153. }
  154. }
  155. //-----------------------------------------------------------------------------
  156. // Header defines the structure of a Tendermint block header
  157. type Header struct {
  158. ChainID string `json:"chain_id"`
  159. Height int64 `json:"height"`
  160. Time time.Time `json:"time"`
  161. NumTxs int64 `json:"num_txs"` // XXX: Can we get rid of this?
  162. TotalTxs int64 `json:"total_txs"`
  163. LastBlockID BlockID `json:"last_block_id"`
  164. LastCommitHash data.Bytes `json:"last_commit_hash"` // commit from validators from the last block
  165. DataHash data.Bytes `json:"data_hash"` // transactions
  166. ValidatorsHash data.Bytes `json:"validators_hash"` // validators for the current block
  167. AppHash data.Bytes `json:"app_hash"` // state after txs from the previous block
  168. ConsensusHash data.Bytes `json:"consensus_hash"` // consensus params for current block
  169. }
  170. // Hash returns the hash of the header.
  171. // Returns nil if ValidatorHash is missing.
  172. func (h *Header) Hash() data.Bytes {
  173. if len(h.ValidatorsHash) == 0 {
  174. return nil
  175. }
  176. return merkle.SimpleHashFromMap(map[string]interface{}{
  177. "ChainID": h.ChainID,
  178. "Height": h.Height,
  179. "Time": h.Time,
  180. "NumTxs": h.NumTxs,
  181. "TotalTxs": h.TotalTxs,
  182. "LastBlockID": h.LastBlockID,
  183. "LastCommit": h.LastCommitHash,
  184. "Data": h.DataHash,
  185. "Validators": h.ValidatorsHash,
  186. "App": h.AppHash,
  187. "Consensus": h.ConsensusHash,
  188. })
  189. }
  190. // StringIndented returns a string representation of the header
  191. func (h *Header) StringIndented(indent string) string {
  192. if h == nil {
  193. return "nil-Header"
  194. }
  195. return fmt.Sprintf(`Header{
  196. %s ChainID: %v
  197. %s Height: %v
  198. %s Time: %v
  199. %s NumTxs: %v
  200. %s TotalTxs: %v
  201. %s LastBlockID: %v
  202. %s LastCommit: %v
  203. %s Data: %v
  204. %s Validators: %v
  205. %s App: %v
  206. %s Conensus: %v
  207. %s}#%v`,
  208. indent, h.ChainID,
  209. indent, h.Height,
  210. indent, h.Time,
  211. indent, h.NumTxs,
  212. indent, h.TotalTxs,
  213. indent, h.LastBlockID,
  214. indent, h.LastCommitHash,
  215. indent, h.DataHash,
  216. indent, h.ValidatorsHash,
  217. indent, h.AppHash,
  218. indent, h.ConsensusHash,
  219. indent, h.Hash())
  220. }
  221. //-------------------------------------
  222. // Commit contains the evidence that a block was committed by a set of validators.
  223. // NOTE: Commit is empty for height 1, but never nil.
  224. type Commit struct {
  225. // NOTE: The Precommits are in order of address to preserve the bonded ValidatorSet order.
  226. // Any peer with a block can gossip precommits by index with a peer without recalculating the
  227. // active ValidatorSet.
  228. BlockID BlockID `json:"blockID"`
  229. Precommits []*Vote `json:"precommits"`
  230. // Volatile
  231. firstPrecommit *Vote
  232. hash data.Bytes
  233. bitArray *cmn.BitArray
  234. }
  235. // FirstPrecommit returns the first non-nil precommit in the commit
  236. func (commit *Commit) FirstPrecommit() *Vote {
  237. if len(commit.Precommits) == 0 {
  238. return nil
  239. }
  240. if commit.firstPrecommit != nil {
  241. return commit.firstPrecommit
  242. }
  243. for _, precommit := range commit.Precommits {
  244. if precommit != nil {
  245. commit.firstPrecommit = precommit
  246. return precommit
  247. }
  248. }
  249. return nil
  250. }
  251. // Height returns the height of the commit
  252. func (commit *Commit) Height() int64 {
  253. if len(commit.Precommits) == 0 {
  254. return 0
  255. }
  256. return commit.FirstPrecommit().Height
  257. }
  258. // Round returns the round of the commit
  259. func (commit *Commit) Round() int {
  260. if len(commit.Precommits) == 0 {
  261. return 0
  262. }
  263. return commit.FirstPrecommit().Round
  264. }
  265. // Type returns the vote type of the commit, which is always VoteTypePrecommit
  266. func (commit *Commit) Type() byte {
  267. return VoteTypePrecommit
  268. }
  269. // Size returns the number of votes in the commit
  270. func (commit *Commit) Size() int {
  271. if commit == nil {
  272. return 0
  273. }
  274. return len(commit.Precommits)
  275. }
  276. // BitArray returns a BitArray of which validators voted in this commit
  277. func (commit *Commit) BitArray() *cmn.BitArray {
  278. if commit.bitArray == nil {
  279. commit.bitArray = cmn.NewBitArray(len(commit.Precommits))
  280. for i, precommit := range commit.Precommits {
  281. // TODO: need to check the BlockID otherwise we could be counting conflicts,
  282. // not just the one with +2/3 !
  283. commit.bitArray.SetIndex(i, precommit != nil)
  284. }
  285. }
  286. return commit.bitArray
  287. }
  288. // GetByIndex returns the vote corresponding to a given validator index
  289. func (commit *Commit) GetByIndex(index int) *Vote {
  290. return commit.Precommits[index]
  291. }
  292. // IsCommit returns true if there is at least one vote
  293. func (commit *Commit) IsCommit() bool {
  294. return len(commit.Precommits) != 0
  295. }
  296. // ValidateBasic performs basic validation that doesn't involve state data.
  297. func (commit *Commit) ValidateBasic() error {
  298. if commit.BlockID.IsZero() {
  299. return errors.New("Commit cannot be for nil block")
  300. }
  301. if len(commit.Precommits) == 0 {
  302. return errors.New("No precommits in commit")
  303. }
  304. height, round := commit.Height(), commit.Round()
  305. // validate the precommits
  306. for _, precommit := range commit.Precommits {
  307. // It's OK for precommits to be missing.
  308. if precommit == nil {
  309. continue
  310. }
  311. // Ensure that all votes are precommits
  312. if precommit.Type != VoteTypePrecommit {
  313. return fmt.Errorf("Invalid commit vote. Expected precommit, got %v",
  314. precommit.Type)
  315. }
  316. // Ensure that all heights are the same
  317. if precommit.Height != height {
  318. return fmt.Errorf("Invalid commit precommit height. Expected %v, got %v",
  319. height, precommit.Height)
  320. }
  321. // Ensure that all rounds are the same
  322. if precommit.Round != round {
  323. return fmt.Errorf("Invalid commit precommit round. Expected %v, got %v",
  324. round, precommit.Round)
  325. }
  326. }
  327. return nil
  328. }
  329. // Hash returns the hash of the commit
  330. func (commit *Commit) Hash() data.Bytes {
  331. if commit.hash == nil {
  332. bs := make([]interface{}, len(commit.Precommits))
  333. for i, precommit := range commit.Precommits {
  334. bs[i] = precommit
  335. }
  336. commit.hash = merkle.SimpleHashFromBinaries(bs)
  337. }
  338. return commit.hash
  339. }
  340. // StringIndented returns a string representation of the commit
  341. func (commit *Commit) StringIndented(indent string) string {
  342. if commit == nil {
  343. return "nil-Commit"
  344. }
  345. precommitStrings := make([]string, len(commit.Precommits))
  346. for i, precommit := range commit.Precommits {
  347. precommitStrings[i] = precommit.String()
  348. }
  349. return fmt.Sprintf(`Commit{
  350. %s BlockID: %v
  351. %s Precommits: %v
  352. %s}#%v`,
  353. indent, commit.BlockID,
  354. indent, strings.Join(precommitStrings, "\n"+indent+" "),
  355. indent, commit.hash)
  356. }
  357. //-----------------------------------------------------------------------------
  358. // SignedHeader is a header along with the commits that prove it
  359. type SignedHeader struct {
  360. Header *Header `json:"header"`
  361. Commit *Commit `json:"commit"`
  362. }
  363. //-----------------------------------------------------------------------------
  364. // Data contains the set of transactions included in the block
  365. type Data struct {
  366. // Txs that will be applied by state @ block.Height+1.
  367. // NOTE: not all txs here are valid. We're just agreeing on the order first.
  368. // This means that block.AppHash does not include these txs.
  369. Txs Txs `json:"txs"`
  370. // Volatile
  371. hash data.Bytes
  372. }
  373. // Hash returns the hash of the data
  374. func (data *Data) Hash() data.Bytes {
  375. if data.hash == nil {
  376. data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs
  377. }
  378. return data.hash
  379. }
  380. // StringIndented returns a string representation of the transactions
  381. func (data *Data) StringIndented(indent string) string {
  382. if data == nil {
  383. return "nil-Data"
  384. }
  385. txStrings := make([]string, cmn.MinInt(len(data.Txs), 21))
  386. for i, tx := range data.Txs {
  387. if i == 20 {
  388. txStrings[i] = fmt.Sprintf("... (%v total)", len(data.Txs))
  389. break
  390. }
  391. txStrings[i] = fmt.Sprintf("Tx:%v", tx)
  392. }
  393. return fmt.Sprintf(`Data{
  394. %s %v
  395. %s}#%v`,
  396. indent, strings.Join(txStrings, "\n"+indent+" "),
  397. indent, data.hash)
  398. }
  399. //--------------------------------------------------------------------------------
  400. // BlockID defines the unique ID of a block as its Hash and its PartSetHeader
  401. type BlockID struct {
  402. Hash data.Bytes `json:"hash"`
  403. PartsHeader PartSetHeader `json:"parts"`
  404. }
  405. // IsZero returns true if this is the BlockID for a nil-block
  406. func (blockID BlockID) IsZero() bool {
  407. return len(blockID.Hash) == 0 && blockID.PartsHeader.IsZero()
  408. }
  409. // Equals returns true if the BlockID matches the given BlockID
  410. func (blockID BlockID) Equals(other BlockID) bool {
  411. return bytes.Equal(blockID.Hash, other.Hash) &&
  412. blockID.PartsHeader.Equals(other.PartsHeader)
  413. }
  414. // Key returns a machine-readable string representation of the BlockID
  415. func (blockID BlockID) Key() string {
  416. return string(blockID.Hash) + string(wire.BinaryBytes(blockID.PartsHeader))
  417. }
  418. // WriteSignBytes writes the canonical bytes of the BlockID to the given writer for digital signing
  419. func (blockID BlockID) WriteSignBytes(w io.Writer, n *int, err *error) {
  420. if blockID.IsZero() {
  421. wire.WriteTo([]byte("null"), w, n, err)
  422. } else {
  423. wire.WriteJSON(CanonicalBlockID(blockID), w, n, err)
  424. }
  425. }
  426. // String returns a human readable string representation of the BlockID
  427. func (blockID BlockID) String() string {
  428. return fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartsHeader)
  429. }