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.

355 lines
8.8 KiB

10 years ago
10 years ago
10 years ago
10 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. "strings"
  7. "time"
  8. . "github.com/tendermint/go-common"
  9. "github.com/tendermint/go-merkle"
  10. "github.com/tendermint/go-wire"
  11. )
  12. const MaxBlockSize = 22020096 // 21MB TODO make it configurable
  13. type Block struct {
  14. *Header `json:"header"`
  15. *Data `json:"data"`
  16. LastValidation *Validation `json:"last_validation"`
  17. }
  18. // Basic validation that doesn't involve state data.
  19. func (b *Block) ValidateBasic(chainID string, lastBlockHeight int, lastBlockHash []byte,
  20. lastBlockParts PartSetHeader, lastBlockTime time.Time) error {
  21. if b.ChainID != chainID {
  22. return errors.New(Fmt("Wrong Block.Header.ChainID. Expected %v, got %v", chainID, b.ChainID))
  23. }
  24. if b.Height != lastBlockHeight+1 {
  25. return errors.New(Fmt("Wrong Block.Header.Height. Expected %v, got %v", lastBlockHeight+1, b.Height))
  26. }
  27. /* TODO: Determine bounds for Time
  28. See blockchain/reactor "stopSyncingDurationMinutes"
  29. if !b.Time.After(lastBlockTime) {
  30. return errors.New("Invalid Block.Header.Time")
  31. }
  32. */
  33. // TODO: validate Fees
  34. if b.NumTxs != len(b.Data.Txs) {
  35. return errors.New(Fmt("Wrong Block.Header.NumTxs. Expected %v, got %v", len(b.Data.Txs), b.NumTxs))
  36. }
  37. if !bytes.Equal(b.LastBlockHash, lastBlockHash) {
  38. return errors.New(Fmt("Wrong Block.Header.LastBlockHash. Expected %X, got %X", lastBlockHash, b.LastBlockHash))
  39. }
  40. if !b.LastBlockParts.Equals(lastBlockParts) {
  41. return errors.New(Fmt("Wrong Block.Header.LastBlockParts. Expected %v, got %v", lastBlockParts, b.LastBlockParts))
  42. }
  43. if !bytes.Equal(b.LastValidationHash, b.LastValidation.Hash()) {
  44. return errors.New(Fmt("Wrong Block.Header.LastValidationHash. Expected %X, got %X", b.LastValidationHash, b.LastValidation.Hash()))
  45. }
  46. if b.Header.Height != 1 {
  47. if err := b.LastValidation.ValidateBasic(); err != nil {
  48. return err
  49. }
  50. }
  51. if !bytes.Equal(b.DataHash, b.Data.Hash()) {
  52. return errors.New(Fmt("Wrong Block.Header.DataHash. Expected %X, got %X", b.DataHash, b.Data.Hash()))
  53. }
  54. // NOTE: the AppHash and ValidatorsHash are validated later.
  55. return nil
  56. }
  57. func (b *Block) FillHeader() {
  58. b.LastValidationHash = b.LastValidation.Hash()
  59. b.DataHash = b.Data.Hash()
  60. }
  61. // Computes and returns the block hash.
  62. // If the block is incomplete, block hash is nil for safety.
  63. func (b *Block) Hash() []byte {
  64. if b.Header == nil || b.Data == nil || b.LastValidation == nil {
  65. return nil
  66. }
  67. b.FillHeader()
  68. return b.Header.Hash()
  69. }
  70. func (b *Block) MakePartSet() *PartSet {
  71. return NewPartSetFromData(wire.BinaryBytes(b))
  72. }
  73. // Convenience.
  74. // A nil block never hashes to anything.
  75. // Nothing hashes to a nil hash.
  76. func (b *Block) HashesTo(hash []byte) bool {
  77. if len(hash) == 0 {
  78. return false
  79. }
  80. if b == nil {
  81. return false
  82. }
  83. return bytes.Equal(b.Hash(), hash)
  84. }
  85. func (b *Block) String() string {
  86. return b.StringIndented("")
  87. }
  88. func (b *Block) StringIndented(indent string) string {
  89. if b == nil {
  90. return "nil-Block"
  91. }
  92. return fmt.Sprintf(`Block{
  93. %s %v
  94. %s %v
  95. %s %v
  96. %s}#%X`,
  97. indent, b.Header.StringIndented(indent+" "),
  98. indent, b.Data.StringIndented(indent+" "),
  99. indent, b.LastValidation.StringIndented(indent+" "),
  100. indent, b.Hash())
  101. }
  102. func (b *Block) StringShort() string {
  103. if b == nil {
  104. return "nil-Block"
  105. } else {
  106. return fmt.Sprintf("Block#%X", b.Hash())
  107. }
  108. }
  109. //-----------------------------------------------------------------------------
  110. type Header struct {
  111. ChainID string `json:"chain_id"`
  112. Height int `json:"height"`
  113. Time time.Time `json:"time"`
  114. Fees int64 `json:"fees"`
  115. NumTxs int `json:"num_txs"`
  116. LastBlockHash []byte `json:"last_block_hash"`
  117. LastBlockParts PartSetHeader `json:"last_block_parts"`
  118. LastValidationHash []byte `json:"last_validation_hash"`
  119. DataHash []byte `json:"data_hash"`
  120. ValidatorsHash []byte `json:"validators_hash"`
  121. AppHash []byte `json:"app_hash"`
  122. }
  123. // NOTE: hash is nil if required fields are missing.
  124. func (h *Header) Hash() []byte {
  125. if len(h.ValidatorsHash) == 0 {
  126. return nil
  127. }
  128. return merkle.SimpleHashFromMap(map[string]interface{}{
  129. "ChainID": h.ChainID,
  130. "Height": h.Height,
  131. "Time": h.Time,
  132. "Fees": h.Fees,
  133. "NumTxs": h.NumTxs,
  134. "LastBlock": h.LastBlockHash,
  135. "LastBlockParts": h.LastBlockParts,
  136. "LastValidation": h.LastValidationHash,
  137. "Data": h.DataHash,
  138. "Validators": h.ValidatorsHash,
  139. "App": h.AppHash,
  140. })
  141. }
  142. func (h *Header) StringIndented(indent string) string {
  143. if h == nil {
  144. return "nil-Header"
  145. }
  146. return fmt.Sprintf(`Header{
  147. %s ChainID: %v
  148. %s Height: %v
  149. %s Time: %v
  150. %s Fees: %v
  151. %s NumTxs: %v
  152. %s LastBlock: %X
  153. %s LastBlockParts: %v
  154. %s LastValidation: %X
  155. %s Data: %X
  156. %s Validators: %X
  157. %s App: %X
  158. %s}#%X`,
  159. indent, h.ChainID,
  160. indent, h.Height,
  161. indent, h.Time,
  162. indent, h.Fees,
  163. indent, h.NumTxs,
  164. indent, h.LastBlockHash,
  165. indent, h.LastBlockParts,
  166. indent, h.LastValidationHash,
  167. indent, h.DataHash,
  168. indent, h.ValidatorsHash,
  169. indent, h.AppHash,
  170. indent, h.Hash())
  171. }
  172. //-------------------------------------
  173. // NOTE: Validation is empty for height 1, but never nil.
  174. type Validation struct {
  175. // NOTE: The Precommits are in order of address to preserve the bonded ValidatorSet order.
  176. // Any peer with a block can gossip precommits by index with a peer without recalculating the
  177. // active ValidatorSet.
  178. Precommits []*Vote `json:"precommits"`
  179. // Volatile
  180. firstPrecommit *Vote
  181. hash []byte
  182. bitArray *BitArray
  183. }
  184. func (v *Validation) FirstPrecommit() *Vote {
  185. if len(v.Precommits) == 0 {
  186. return nil
  187. }
  188. if v.firstPrecommit != nil {
  189. return v.firstPrecommit
  190. }
  191. for _, precommit := range v.Precommits {
  192. if precommit != nil {
  193. v.firstPrecommit = precommit
  194. return precommit
  195. }
  196. }
  197. return nil
  198. }
  199. func (v *Validation) Height() int {
  200. if len(v.Precommits) == 0 {
  201. return 0
  202. }
  203. return v.FirstPrecommit().Height
  204. }
  205. func (v *Validation) Round() int {
  206. if len(v.Precommits) == 0 {
  207. return 0
  208. }
  209. return v.FirstPrecommit().Round
  210. }
  211. func (v *Validation) Type() byte {
  212. return VoteTypePrecommit
  213. }
  214. func (v *Validation) Size() int {
  215. if v == nil {
  216. return 0
  217. }
  218. return len(v.Precommits)
  219. }
  220. func (v *Validation) BitArray() *BitArray {
  221. if v.bitArray == nil {
  222. v.bitArray = NewBitArray(len(v.Precommits))
  223. for i, precommit := range v.Precommits {
  224. v.bitArray.SetIndex(i, precommit != nil)
  225. }
  226. }
  227. return v.bitArray
  228. }
  229. func (v *Validation) GetByIndex(index int) *Vote {
  230. return v.Precommits[index]
  231. }
  232. func (v *Validation) IsCommit() bool {
  233. if len(v.Precommits) == 0 {
  234. return false
  235. }
  236. return true
  237. }
  238. func (v *Validation) ValidateBasic() error {
  239. if len(v.Precommits) == 0 {
  240. return errors.New("No precommits in validation")
  241. }
  242. height, round := v.Height(), v.Round()
  243. for _, precommit := range v.Precommits {
  244. // It's OK for precommits to be missing.
  245. if precommit == nil {
  246. continue
  247. }
  248. // Ensure that all votes are precommits
  249. if precommit.Type != VoteTypePrecommit {
  250. return fmt.Errorf("Invalid validation vote. Expected precommit, got %v",
  251. precommit.Type)
  252. }
  253. // Ensure that all heights are the same
  254. if precommit.Height != height {
  255. return fmt.Errorf("Invalid validation precommit height. Expected %v, got %v",
  256. height, precommit.Height)
  257. }
  258. // Ensure that all rounds are the same
  259. if precommit.Round != round {
  260. return fmt.Errorf("Invalid validation precommit round. Expected %v, got %v",
  261. round, precommit.Round)
  262. }
  263. }
  264. return nil
  265. }
  266. func (v *Validation) Hash() []byte {
  267. if v.hash == nil {
  268. bs := make([]interface{}, len(v.Precommits))
  269. for i, precommit := range v.Precommits {
  270. bs[i] = precommit
  271. }
  272. v.hash = merkle.SimpleHashFromBinaries(bs)
  273. }
  274. return v.hash
  275. }
  276. func (v *Validation) StringIndented(indent string) string {
  277. if v == nil {
  278. return "nil-Validation"
  279. }
  280. precommitStrings := make([]string, len(v.Precommits))
  281. for i, precommit := range v.Precommits {
  282. precommitStrings[i] = precommit.String()
  283. }
  284. return fmt.Sprintf(`Validation{
  285. %s Precommits: %v
  286. %s}#%X`,
  287. indent, strings.Join(precommitStrings, "\n"+indent+" "),
  288. indent, v.hash)
  289. }
  290. //-----------------------------------------------------------------------------
  291. type Data struct {
  292. Txs []Tx `json:"txs"`
  293. // Volatile
  294. hash []byte
  295. }
  296. func (data *Data) Hash() []byte {
  297. if data.hash == nil {
  298. txs := make([]interface{}, len(data.Txs))
  299. for i, tx := range data.Txs {
  300. txs[i] = tx
  301. }
  302. data.hash = merkle.SimpleHashFromBinaries(txs) // NOTE: leaves are TxIDs.
  303. }
  304. return data.hash
  305. }
  306. func (data *Data) StringIndented(indent string) string {
  307. if data == nil {
  308. return "nil-Data"
  309. }
  310. txStrings := make([]string, len(data.Txs))
  311. for i, tx := range data.Txs {
  312. txStrings[i] = fmt.Sprintf("Tx:%v", tx)
  313. }
  314. return fmt.Sprintf(`Data{
  315. %s %v
  316. %s}#%X`,
  317. indent, strings.Join(txStrings, "\n"+indent+" "),
  318. indent, data.hash)
  319. }