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.

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