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.

449 lines
12 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
  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. }
  140. // Hash returns the hash of the header.
  141. // Returns nil if ValidatorHash is missing.
  142. func (h *Header) Hash() data.Bytes {
  143. if len(h.ValidatorsHash) == 0 {
  144. return nil
  145. }
  146. return merkle.SimpleHashFromMap(map[string]interface{}{
  147. "ChainID": h.ChainID,
  148. "Height": h.Height,
  149. "Time": h.Time,
  150. "NumTxs": h.NumTxs,
  151. "TotalTxs": h.TotalTxs,
  152. "LastBlockID": h.LastBlockID,
  153. "LastCommit": h.LastCommitHash,
  154. "Data": h.DataHash,
  155. "Validators": h.ValidatorsHash,
  156. "App": h.AppHash,
  157. "Consensus": h.ConsensusHash,
  158. })
  159. }
  160. // StringIndented returns a string representation of the header
  161. func (h *Header) StringIndented(indent string) string {
  162. if h == nil {
  163. return "nil-Header"
  164. }
  165. return fmt.Sprintf(`Header{
  166. %s ChainID: %v
  167. %s Height: %v
  168. %s Time: %v
  169. %s NumTxs: %v
  170. %s TotalTxs: %v
  171. %s LastBlockID: %v
  172. %s LastCommit: %v
  173. %s Data: %v
  174. %s Validators: %v
  175. %s App: %v
  176. %s Conensus: %v
  177. %s}#%v`,
  178. indent, h.ChainID,
  179. indent, h.Height,
  180. indent, h.Time,
  181. indent, h.NumTxs,
  182. indent, h.TotalTxs,
  183. indent, h.LastBlockID,
  184. indent, h.LastCommitHash,
  185. indent, h.DataHash,
  186. indent, h.ValidatorsHash,
  187. indent, h.AppHash,
  188. indent, h.ConsensusHash,
  189. indent, h.Hash())
  190. }
  191. //-------------------------------------
  192. // Commit contains the evidence that a block was committed by a set of validators.
  193. // NOTE: Commit is empty for height 1, but never nil.
  194. type Commit struct {
  195. // NOTE: The Precommits are in order of address to preserve the bonded ValidatorSet order.
  196. // Any peer with a block can gossip precommits by index with a peer without recalculating the
  197. // active ValidatorSet.
  198. BlockID BlockID `json:"blockID"`
  199. Precommits []*Vote `json:"precommits"`
  200. // Volatile
  201. firstPrecommit *Vote
  202. hash data.Bytes
  203. bitArray *cmn.BitArray
  204. }
  205. // FirstPrecommit returns the first non-nil precommit in the commit
  206. func (commit *Commit) FirstPrecommit() *Vote {
  207. if len(commit.Precommits) == 0 {
  208. return nil
  209. }
  210. if commit.firstPrecommit != nil {
  211. return commit.firstPrecommit
  212. }
  213. for _, precommit := range commit.Precommits {
  214. if precommit != nil {
  215. commit.firstPrecommit = precommit
  216. return precommit
  217. }
  218. }
  219. return nil
  220. }
  221. // Height returns the height of the commit
  222. func (commit *Commit) Height() int64 {
  223. if len(commit.Precommits) == 0 {
  224. return 0
  225. }
  226. return commit.FirstPrecommit().Height
  227. }
  228. // Round returns the round of the commit
  229. func (commit *Commit) Round() int {
  230. if len(commit.Precommits) == 0 {
  231. return 0
  232. }
  233. return commit.FirstPrecommit().Round
  234. }
  235. // Type returns the vote type of the commit, which is always VoteTypePrecommit
  236. func (commit *Commit) Type() byte {
  237. return VoteTypePrecommit
  238. }
  239. // Size returns the number of votes in the commit
  240. func (commit *Commit) Size() int {
  241. if commit == nil {
  242. return 0
  243. }
  244. return len(commit.Precommits)
  245. }
  246. // BitArray returns a BitArray of which validators voted in this commit
  247. func (commit *Commit) BitArray() *cmn.BitArray {
  248. if commit.bitArray == nil {
  249. commit.bitArray = cmn.NewBitArray(len(commit.Precommits))
  250. for i, precommit := range commit.Precommits {
  251. // TODO: need to check the BlockID otherwise we could be counting conflicts,
  252. // not just the one with +2/3 !
  253. commit.bitArray.SetIndex(i, precommit != nil)
  254. }
  255. }
  256. return commit.bitArray
  257. }
  258. // GetByIndex returns the vote corresponding to a given validator index
  259. func (commit *Commit) GetByIndex(index int) *Vote {
  260. return commit.Precommits[index]
  261. }
  262. // IsCommit returns true if there is at least one vote
  263. func (commit *Commit) IsCommit() bool {
  264. return len(commit.Precommits) != 0
  265. }
  266. // ValidateBasic performs basic validation that doesn't involve state data.
  267. func (commit *Commit) ValidateBasic() error {
  268. if commit.BlockID.IsZero() {
  269. return errors.New("Commit cannot be for nil block")
  270. }
  271. if len(commit.Precommits) == 0 {
  272. return errors.New("No precommits in commit")
  273. }
  274. height, round := commit.Height(), commit.Round()
  275. // validate the precommits
  276. for _, precommit := range commit.Precommits {
  277. // It's OK for precommits to be missing.
  278. if precommit == nil {
  279. continue
  280. }
  281. // Ensure that all votes are precommits
  282. if precommit.Type != VoteTypePrecommit {
  283. return fmt.Errorf("Invalid commit vote. Expected precommit, got %v",
  284. precommit.Type)
  285. }
  286. // Ensure that all heights are the same
  287. if precommit.Height != height {
  288. return fmt.Errorf("Invalid commit precommit height. Expected %v, got %v",
  289. height, precommit.Height)
  290. }
  291. // Ensure that all rounds are the same
  292. if precommit.Round != round {
  293. return fmt.Errorf("Invalid commit precommit round. Expected %v, got %v",
  294. round, precommit.Round)
  295. }
  296. }
  297. return nil
  298. }
  299. // Hash returns the hash of the commit
  300. func (commit *Commit) Hash() data.Bytes {
  301. if commit.hash == nil {
  302. bs := make([]interface{}, len(commit.Precommits))
  303. for i, precommit := range commit.Precommits {
  304. bs[i] = precommit
  305. }
  306. commit.hash = merkle.SimpleHashFromBinaries(bs)
  307. }
  308. return commit.hash
  309. }
  310. // StringIndented returns a string representation of the commit
  311. func (commit *Commit) StringIndented(indent string) string {
  312. if commit == nil {
  313. return "nil-Commit"
  314. }
  315. precommitStrings := make([]string, len(commit.Precommits))
  316. for i, precommit := range commit.Precommits {
  317. precommitStrings[i] = precommit.String()
  318. }
  319. return fmt.Sprintf(`Commit{
  320. %s BlockID: %v
  321. %s Precommits: %v
  322. %s}#%v`,
  323. indent, commit.BlockID,
  324. indent, strings.Join(precommitStrings, "\n"+indent+" "),
  325. indent, commit.hash)
  326. }
  327. //-----------------------------------------------------------------------------
  328. // SignedHeader is a header along with the commits that prove it
  329. type SignedHeader struct {
  330. Header *Header `json:"header"`
  331. Commit *Commit `json:"commit"`
  332. }
  333. //-----------------------------------------------------------------------------
  334. // Data contains the set of transactions included in the block
  335. type Data struct {
  336. // Txs that will be applied by state @ block.Height+1.
  337. // NOTE: not all txs here are valid. We're just agreeing on the order first.
  338. // This means that block.AppHash does not include these txs.
  339. Txs Txs `json:"txs"`
  340. // Volatile
  341. hash data.Bytes
  342. }
  343. // Hash returns the hash of the data
  344. func (data *Data) Hash() data.Bytes {
  345. if data.hash == nil {
  346. data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs
  347. }
  348. return data.hash
  349. }
  350. // StringIndented returns a string representation of the transactions
  351. func (data *Data) StringIndented(indent string) string {
  352. if data == nil {
  353. return "nil-Data"
  354. }
  355. txStrings := make([]string, cmn.MinInt(len(data.Txs), 21))
  356. for i, tx := range data.Txs {
  357. if i == 20 {
  358. txStrings[i] = fmt.Sprintf("... (%v total)", len(data.Txs))
  359. break
  360. }
  361. txStrings[i] = fmt.Sprintf("Tx:%v", tx)
  362. }
  363. return fmt.Sprintf(`Data{
  364. %s %v
  365. %s}#%v`,
  366. indent, strings.Join(txStrings, "\n"+indent+" "),
  367. indent, data.hash)
  368. }
  369. //--------------------------------------------------------------------------------
  370. // BlockID defines the unique ID of a block as its Hash and its PartSetHeader
  371. type BlockID struct {
  372. Hash data.Bytes `json:"hash"`
  373. PartsHeader PartSetHeader `json:"parts"`
  374. }
  375. // IsZero returns true if this is the BlockID for a nil-block
  376. func (blockID BlockID) IsZero() bool {
  377. return len(blockID.Hash) == 0 && blockID.PartsHeader.IsZero()
  378. }
  379. // Equals returns true if the BlockID matches the given BlockID
  380. func (blockID BlockID) Equals(other BlockID) bool {
  381. return bytes.Equal(blockID.Hash, other.Hash) &&
  382. blockID.PartsHeader.Equals(other.PartsHeader)
  383. }
  384. // Key returns a machine-readable string representation of the BlockID
  385. func (blockID BlockID) Key() string {
  386. return string(blockID.Hash) + string(wire.BinaryBytes(blockID.PartsHeader))
  387. }
  388. // WriteSignBytes writes the canonical bytes of the BlockID to the given writer for digital signing
  389. func (blockID BlockID) WriteSignBytes(w io.Writer, n *int, err *error) {
  390. if blockID.IsZero() {
  391. wire.WriteTo([]byte("null"), w, n, err)
  392. } else {
  393. wire.WriteJSON(CanonicalBlockID(blockID), w, n, err)
  394. }
  395. }
  396. // String returns a human readable string representation of the BlockID
  397. func (blockID BlockID) String() string {
  398. return fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartsHeader)
  399. }