2022-11-30 10:51:24 +01:00
|
|
|
package keystore
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"crypto/ecdsa"
|
|
|
|
|
|
|
|
eth_crypto "github.com/celo-org/celo-blockchain/crypto"
|
2023-02-03 10:29:27 +01:00
|
|
|
"github.com/grassrootseconomics/cic-custodial/internal/queries"
|
2022-11-30 10:51:24 +01:00
|
|
|
"github.com/grassrootseconomics/cic-custodial/pkg/keypair"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
)
|
|
|
|
|
2023-02-03 10:29:27 +01:00
|
|
|
type (
|
|
|
|
Opts struct {
|
|
|
|
PostgresPool *pgxpool.Pool
|
|
|
|
Queries *queries.Queries
|
|
|
|
}
|
2022-11-30 10:51:24 +01:00
|
|
|
|
2023-02-03 10:29:27 +01:00
|
|
|
PostgresKeystore struct {
|
|
|
|
db *pgxpool.Pool
|
|
|
|
queries *queries.Queries
|
2022-11-30 10:51:24 +01:00
|
|
|
}
|
2023-02-03 10:29:27 +01:00
|
|
|
)
|
2022-11-30 10:51:24 +01:00
|
|
|
|
2023-02-03 10:29:27 +01:00
|
|
|
func NewPostgresKeytore(o Opts) Keystore {
|
2022-11-30 10:51:24 +01:00
|
|
|
return &PostgresKeystore{
|
2023-02-03 10:29:27 +01:00
|
|
|
db: o.PostgresPool,
|
|
|
|
queries: o.Queries,
|
|
|
|
}
|
2022-11-30 10:51:24 +01:00
|
|
|
}
|
|
|
|
|
2023-02-03 10:29:27 +01:00
|
|
|
// WriteKeyPair inserts a keypair into the db and returns the linked id.
|
|
|
|
func (ks *PostgresKeystore) WriteKeyPair(ctx context.Context, keypair keypair.Key) (uint, error) {
|
|
|
|
var id uint
|
|
|
|
|
|
|
|
if err := ks.db.QueryRow(ctx, ks.queries.WriteKeyPair, keypair.Public, keypair.Private).Scan(&id); err != nil {
|
|
|
|
return 0, err
|
2022-11-30 10:51:24 +01:00
|
|
|
}
|
|
|
|
|
2023-02-03 10:29:27 +01:00
|
|
|
return id, nil
|
2022-11-30 10:51:24 +01:00
|
|
|
}
|
|
|
|
|
2023-02-03 10:29:27 +01:00
|
|
|
// LoadPrivateKey loads a private key as a crypto primitive for direct use. An id is used to search for the private key.
|
2022-11-30 10:51:24 +01:00
|
|
|
func (ks *PostgresKeystore) LoadPrivateKey(ctx context.Context, publicKey string) (*ecdsa.PrivateKey, error) {
|
2023-02-03 10:29:27 +01:00
|
|
|
var privateKeyString string
|
2022-11-30 10:51:24 +01:00
|
|
|
|
2023-02-03 10:29:27 +01:00
|
|
|
if err := ks.db.QueryRow(ctx, ks.queries.LoadKeyPair, publicKey).Scan(&privateKeyString); err != nil {
|
2022-11-30 10:51:24 +01:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
privateKey, err := eth_crypto.HexToECDSA(privateKeyString)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return privateKey, nil
|
|
|
|
}
|