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.

84 lines
2.3 KiB

10 years ago
10 years ago
10 years ago
  1. package account
  2. import (
  3. "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/ed25519"
  4. . "github.com/tendermint/tendermint/common"
  5. "github.com/tendermint/tendermint/wire"
  6. )
  7. type PrivAccount struct {
  8. Address []byte `json:"address"`
  9. PubKey PubKey `json:"pub_key"`
  10. PrivKey PrivKey `json:"priv_key"`
  11. }
  12. func (pA *PrivAccount) Generate(index int) *PrivAccount {
  13. newPrivKey := pA.PrivKey.(PrivKeyEd25519).Generate(index)
  14. newPubKey := newPrivKey.PubKey()
  15. newAddress := newPubKey.Address()
  16. return &PrivAccount{
  17. Address: newAddress,
  18. PubKey: newPubKey,
  19. PrivKey: newPrivKey,
  20. }
  21. }
  22. func (pA *PrivAccount) Sign(chainID string, o Signable) Signature {
  23. return pA.PrivKey.Sign(SignBytes(chainID, o))
  24. }
  25. func (pA *PrivAccount) String() string {
  26. return Fmt("PrivAccount{%X}", pA.Address)
  27. }
  28. //----------------------------------------
  29. // Generates a new account with private key.
  30. func GenPrivAccount() *PrivAccount {
  31. privKeyBytes := new([64]byte)
  32. copy(privKeyBytes[:32], CRandBytes(32))
  33. pubKeyBytes := ed25519.MakePublicKey(privKeyBytes)
  34. pubKey := PubKeyEd25519(*pubKeyBytes)
  35. privKey := PrivKeyEd25519(*privKeyBytes)
  36. return &PrivAccount{
  37. Address: pubKey.Address(),
  38. PubKey: pubKey,
  39. PrivKey: privKey,
  40. }
  41. }
  42. // Generates 32 priv key bytes from secret
  43. func GenPrivKeyBytesFromSecret(secret string) []byte {
  44. return wire.BinarySha256(secret) // Not Ripemd160 because we want 32 bytes.
  45. }
  46. // Generates a new account with private key from SHA256 hash of a secret
  47. func GenPrivAccountFromSecret(secret string) *PrivAccount {
  48. privKey32 := GenPrivKeyBytesFromSecret(secret)
  49. privKeyBytes := new([64]byte)
  50. copy(privKeyBytes[:32], privKey32)
  51. pubKeyBytes := ed25519.MakePublicKey(privKeyBytes)
  52. pubKey := PubKeyEd25519(*pubKeyBytes)
  53. privKey := PrivKeyEd25519(*privKeyBytes)
  54. return &PrivAccount{
  55. Address: pubKey.Address(),
  56. PubKey: pubKey,
  57. PrivKey: privKey,
  58. }
  59. }
  60. func GenPrivAccountFromPrivKeyBytes(privKeyBytes []byte) *PrivAccount {
  61. if len(privKeyBytes) != 64 {
  62. PanicSanity(Fmt("Expected 64 bytes but got %v", len(privKeyBytes)))
  63. }
  64. var privKeyArray [64]byte
  65. copy(privKeyArray[:], privKeyBytes)
  66. pubKeyBytes := ed25519.MakePublicKey(&privKeyArray)
  67. pubKey := PubKeyEd25519(*pubKeyBytes)
  68. privKey := PrivKeyEd25519(privKeyArray)
  69. return &PrivAccount{
  70. Address: pubKey.Address(),
  71. PubKey: pubKey,
  72. PrivKey: privKey,
  73. }
  74. }