tendermint/account/priv_account.go

85 lines
2.3 KiB
Go
Raw Normal View History

2014-12-17 01:37:13 -08:00
package account
import (
2015-06-09 20:17:19 -07:00
"github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/ed25519"
2015-04-01 17:30:16 -07:00
. "github.com/tendermint/tendermint/common"
2015-08-14 14:11:11 -07:00
"github.com/tendermint/tendermint/wire"
)
type PrivAccount struct {
2015-05-01 17:26:49 -07:00
Address []byte `json:"address"`
PubKey PubKey `json:"pub_key"`
PrivKey PrivKey `json:"priv_key"`
}
2015-07-11 18:01:21 -07:00
func (pA *PrivAccount) Generate(index int) *PrivAccount {
newPrivKey := pA.PrivKey.(PrivKeyEd25519).Generate(index)
newPubKey := newPrivKey.PubKey()
newAddress := newPubKey.Address()
return &PrivAccount{
Address: newAddress,
PubKey: newPubKey,
PrivKey: newPrivKey,
}
}
func (pA *PrivAccount) Sign(chainID string, o Signable) Signature {
return pA.PrivKey.Sign(SignBytes(chainID, o))
}
func (pA *PrivAccount) String() string {
return Fmt("PrivAccount{%X}", pA.Address)
}
//----------------------------------------
// Generates a new account with private key.
func GenPrivAccount() *PrivAccount {
privKeyBytes := new([64]byte)
copy(privKeyBytes[:32], CRandBytes(32))
pubKeyBytes := ed25519.MakePublicKey(privKeyBytes)
2015-07-17 14:19:16 -07:00
pubKey := PubKeyEd25519(*pubKeyBytes)
privKey := PrivKeyEd25519(*privKeyBytes)
return &PrivAccount{
Address: pubKey.Address(),
PubKey: pubKey,
2015-01-13 21:03:01 -08:00
PrivKey: privKey,
}
}
2014-12-17 01:37:13 -08:00
2015-08-14 14:11:11 -07:00
// Generates 32 priv key bytes from secret
func GenPrivKeyBytesFromSecret(secret string) []byte {
return wire.BinarySha256(secret) // Not Ripemd160 because we want 32 bytes.
}
// Generates a new account with private key from SHA256 hash of a secret
2015-08-14 14:11:11 -07:00
func GenPrivAccountFromSecret(secret string) *PrivAccount {
privKey32 := GenPrivKeyBytesFromSecret(secret)
privKeyBytes := new([64]byte)
copy(privKeyBytes[:32], privKey32)
pubKeyBytes := ed25519.MakePublicKey(privKeyBytes)
2015-07-17 14:19:16 -07:00
pubKey := PubKeyEd25519(*pubKeyBytes)
privKey := PrivKeyEd25519(*privKeyBytes)
return &PrivAccount{
Address: pubKey.Address(),
PubKey: pubKey,
PrivKey: privKey,
}
}
2015-08-14 14:11:11 -07:00
func GenPrivAccountFromPrivKeyBytes(privKeyBytes []byte) *PrivAccount {
2015-07-11 18:01:21 -07:00
if len(privKeyBytes) != 64 {
2015-07-19 16:42:52 -07:00
PanicSanity(Fmt("Expected 64 bytes but got %v", len(privKeyBytes)))
2015-07-11 18:01:21 -07:00
}
2015-08-14 14:11:11 -07:00
var privKeyArray [64]byte
copy(privKeyArray[:], privKeyBytes)
pubKeyBytes := ed25519.MakePublicKey(&privKeyArray)
2015-07-17 14:19:16 -07:00
pubKey := PubKeyEd25519(*pubKeyBytes)
2015-08-14 14:11:11 -07:00
privKey := PrivKeyEd25519(privKeyArray)
return &PrivAccount{
Address: pubKey.Address(),
PubKey: pubKey,
PrivKey: privKey,
}
}