I am trying to build a blockchain project when I'm catching an issue about gob Serialize. I have a struct Wallet which uses elliptic.P256() Curve struct, and when I'm trying to serialize Wallet, a bug of no exported fields occured.
Really hope for some help.
There is my code.
const walletFile = "Wallets.dat"
type Wallets struct {
WalletsMap map[string]*Wallet
}
type Wallet struct {
PrivateKey ecdsa.PrivateKey
PublicKey []byte
}
func (w *Wallets) SaveWallets() {
var content bytes.Buffer
gob.Register(elliptic.P256())
encoder := gob.NewEncoder(&content)
err := encoder.Encode(&w)
if err != nil {
log.Panic(err)
}
err = ioutil.WriteFile(walletFile, content.Bytes(), 0644)
if err != nil {
log.Panic(err)
}
}
func NewWallets() (*Wallets, error) {
if _, err := os.Stat(walletFile); os.IsNotExist(err) {
wallets := &Wallets{}
wallets.WalletsMap = make(map[string]*Wallet)
return wallets, err
}
fileContent, err := ioutil.ReadFile(walletFile)
if err != nil {
log.Panic(err)
}
var wallets Wallets
gob.Register(elliptic.P256())
decoder := gob.NewDecoder(bytes.NewReader(fileContent))
err = decoder.Decode(&wallets)
if err != nil {
log.Panic(err)
}
return &wallets, nil
}
The issue
2022/09/18 19:42:33 gob: type elliptic.p256Curve has no exported fields
panic: gob: type elliptic.p256Curve has no exported fields
What you seem to be trying to do here is serialize a P256 curve from the
crypto/ellipticpackage. The issue is that theP256()function returns an interface calledelliptic.Curve.What this error is telling you is that the underlying type of the
elliptic.Curve, in this caseelliptic.p256Curve, doesn't have any fields that are exported (named with the first letter capitalized). Go'sreflectpackage, whichencoding/gobuses, only works on exported fields.You might want to try using
crypto/elliptic'sMarshal()orGenerateKey()functions.