2019-02-07 19:22:49 +00:00
|
|
|
// Copyright (C) 2018 Storj Labs, Inc.
|
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
package satellitedb
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"crypto"
|
2019-04-23 20:48:57 +01:00
|
|
|
"database/sql"
|
2019-02-07 19:22:49 +00:00
|
|
|
|
2019-04-23 20:48:57 +01:00
|
|
|
"storj.io/storj/internal/dbutil/pgutil"
|
|
|
|
"storj.io/storj/internal/dbutil/sqliteutil"
|
2019-02-07 20:39:20 +00:00
|
|
|
"storj.io/storj/pkg/pkcrypto"
|
2019-02-07 19:22:49 +00:00
|
|
|
"storj.io/storj/pkg/storj"
|
|
|
|
dbx "storj.io/storj/satellite/satellitedb/dbx"
|
|
|
|
)
|
|
|
|
|
|
|
|
type certDB struct {
|
|
|
|
db *dbx.DB
|
|
|
|
}
|
|
|
|
|
2019-04-23 20:48:57 +01:00
|
|
|
func (certs *certDB) SavePublicKey(ctx context.Context, nodeID storj.NodeID, publicKey crypto.PublicKey) error {
|
|
|
|
_, err := certs.db.Get_CertRecord_By_Id(ctx, dbx.CertRecord_Id(nodeID.Bytes()))
|
|
|
|
if err == sql.ErrNoRows {
|
|
|
|
return certs.tryAddPublicKey(ctx, nodeID, publicKey)
|
|
|
|
}
|
2019-02-07 19:22:49 +00:00
|
|
|
if err != nil {
|
|
|
|
return Error.Wrap(err)
|
|
|
|
}
|
|
|
|
|
2019-04-23 20:48:57 +01:00
|
|
|
// nodeID entry already exists, just return
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (certs *certDB) tryAddPublicKey(ctx context.Context, nodeID storj.NodeID, publicKey crypto.PublicKey) error {
|
|
|
|
// no rows err, so create/insert an entry
|
|
|
|
pubbytes, err := pkcrypto.PublicKeyToPKIX(publicKey)
|
2019-02-07 19:22:49 +00:00
|
|
|
if err != nil {
|
2019-04-23 20:48:57 +01:00
|
|
|
return Error.Wrap(err)
|
2019-02-07 19:22:49 +00:00
|
|
|
}
|
|
|
|
|
2019-04-23 20:48:57 +01:00
|
|
|
// TODO: use upsert here instead of create
|
|
|
|
_, err = certs.db.Create_CertRecord(ctx,
|
|
|
|
dbx.CertRecord_Publickey(pubbytes),
|
|
|
|
dbx.CertRecord_Id(nodeID.Bytes()),
|
|
|
|
)
|
|
|
|
// another goroutine might race to create the cert record, let's ignore that error
|
|
|
|
if pgutil.IsConstraintError(err) || sqliteutil.IsConstraintError(err) {
|
|
|
|
return nil
|
|
|
|
} else if err != nil {
|
|
|
|
return Error.Wrap(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
2019-02-07 19:22:49 +00:00
|
|
|
}
|
|
|
|
|
2019-04-23 20:48:57 +01:00
|
|
|
func (certs *certDB) GetPublicKey(ctx context.Context, nodeID storj.NodeID) (crypto.PublicKey, error) {
|
|
|
|
dbxInfo, err := certs.db.Get_CertRecord_By_Id(ctx, dbx.CertRecord_Id(nodeID.Bytes()))
|
2019-02-07 19:22:49 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-04-23 20:48:57 +01:00
|
|
|
|
2019-02-07 20:39:20 +00:00
|
|
|
pubkey, err := pkcrypto.PublicKeyFromPKIX(dbxInfo.Publickey)
|
2019-02-07 19:22:49 +00:00
|
|
|
if err != nil {
|
2019-02-22 21:17:35 +00:00
|
|
|
return nil, Error.New("Failed to extract Public Key from Order: %+v", err)
|
2019-02-07 19:22:49 +00:00
|
|
|
}
|
2019-02-07 20:39:20 +00:00
|
|
|
return pubkey, nil
|
2019-02-07 19:22:49 +00:00
|
|
|
}
|