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.

81 lines
2.4 KiB

  1. package types
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "time"
  6. "github.com/pkg/errors"
  7. "github.com/tendermint/go-crypto"
  8. "github.com/tendermint/go-wire/data"
  9. cmn "github.com/tendermint/tmlibs/common"
  10. )
  11. //------------------------------------------------------------
  12. // we store the gendoc in the db
  13. var GenDocKey = []byte("GenDocKey")
  14. //------------------------------------------------------------
  15. // core types for a genesis definition
  16. // GenesisValidator is an initial validator.
  17. type GenesisValidator struct {
  18. PubKey crypto.PubKey `json:"pub_key"`
  19. Amount int64 `json:"amount"`
  20. Name string `json:"name"`
  21. }
  22. // GenesisDoc defines the initial conditions for a tendermint blockchain, in particular its validator set.
  23. type GenesisDoc struct {
  24. GenesisTime time.Time `json:"genesis_time"`
  25. ChainID string `json:"chain_id"`
  26. Validators []GenesisValidator `json:"validators"`
  27. AppHash data.Bytes `json:"app_hash"`
  28. }
  29. // SaveAs is a utility method for saving GenensisDoc as a JSON file.
  30. func (genDoc *GenesisDoc) SaveAs(file string) error {
  31. genDocBytes, err := json.Marshal(genDoc)
  32. if err != nil {
  33. return err
  34. }
  35. return cmn.WriteFile(file, genDocBytes, 0644)
  36. }
  37. // ValidatorHash returns the hash of the validator set contained in the GenesisDoc
  38. func (genDoc *GenesisDoc) ValidatorHash() []byte {
  39. vals := make([]*Validator, len(genDoc.Validators))
  40. for i, v := range genDoc.Validators {
  41. vals[i] = NewValidator(v.PubKey, v.Amount)
  42. }
  43. vset := NewValidatorSet(vals)
  44. return vset.Hash()
  45. }
  46. //------------------------------------------------------------
  47. // Make genesis state from file
  48. // GenesisDocFromJSON unmarshalls JSON data into a GenesisDoc.
  49. func GenesisDocFromJSON(jsonBlob []byte) (*GenesisDoc, error) {
  50. genDoc := GenesisDoc{}
  51. err := json.Unmarshal(jsonBlob, &genDoc)
  52. return &genDoc, err
  53. }
  54. // GenesisDocFromFile reads JSON data from a file and unmarshalls it into a GenesisDoc.
  55. func GenesisDocFromFile(genDocFile string) (*GenesisDoc, error) {
  56. jsonBlob, err := ioutil.ReadFile(genDocFile)
  57. if err != nil {
  58. return nil, errors.Wrap(err, "Couldn't read GenesisDoc file")
  59. }
  60. genDoc, err := GenesisDocFromJSON(jsonBlob)
  61. if err != nil {
  62. return nil, errors.Wrap(err, "Error reading GenesisDoc")
  63. }
  64. if genDoc.ChainID == "" {
  65. return nil, errors.Errorf("Genesis doc %v must include non-empty chain_id", genDocFile)
  66. }
  67. return genDoc, nil
  68. }