cic-custodial/internal/keystore/postgres.go

62 lines
1.4 KiB
Go
Raw Normal View History

2022-11-30 10:51:24 +01:00
package keystore
import (
"context"
"crypto/ecdsa"
eth_crypto "github.com/celo-org/celo-blockchain/crypto"
"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"
)
type (
Opts struct {
PostgresPool *pgxpool.Pool
Queries *queries.Queries
}
2022-11-30 10:51:24 +01:00
PostgresKeystore struct {
db *pgxpool.Pool
queries *queries.Queries
2022-11-30 10:51:24 +01:00
}
)
2022-11-30 10:51:24 +01:00
func NewPostgresKeytore(o Opts) Keystore {
2022-11-30 10:51:24 +01:00
return &PostgresKeystore{
db: o.PostgresPool,
queries: o.Queries,
}
2022-11-30 10:51:24 +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) {
2023-02-09 08:42:15 +01:00
var (
id uint
)
if err := ks.db.QueryRow(ctx, ks.queries.WriteKeyPair, keypair.Public, keypair.Private).Scan(&id); err != nil {
2023-02-09 08:42:15 +01:00
return id, err
2022-11-30 10:51:24 +01:00
}
return id, nil
2022-11-30 10:51:24 +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-09 08:42:15 +01:00
var (
privateKeyString string
)
2022-11-30 10:51:24 +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
}