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.

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