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.

453 lines
13 KiB

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