Skip to content

Commit

Permalink
feat: enable multiple db connections with sqlcipher
Browse files Browse the repository at this point in the history
  • Loading branch information
osmaczko committed May 18, 2023
1 parent 6fa8c11 commit 7df293e
Showing 1 changed file with 29 additions and 18 deletions.
47 changes: 29 additions & 18 deletions sqlite/sqlite.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ package sqlite

import (
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"os"

_ "github.com/mutecomm/go-sqlcipher" // We require go sqlcipher that overrides default implementation
sqlcipher "github.com/mutecomm/go-sqlcipher" // We require go sqlcipher that overrides default implementation

"github.com/status-im/status-go/protocol/sqlite"
)
Expand Down Expand Up @@ -81,23 +82,33 @@ func openDB(path string, key string, kdfIterationsNumber int) (*sql.DB, error) {
return nil, err
}

// Disable concurrent access as not supported by the driver
db.SetMaxOpenConns(1)

if _, err = db.Exec("PRAGMA foreign_keys=ON"); err != nil {
return nil, err
}
keyString := fmt.Sprintf("PRAGMA key = '%s'", key)
if _, err = db.Exec(keyString); err != nil {
return nil, errors.New("failed to set key pragma")
}

if kdfIterationsNumber <= 0 {
kdfIterationsNumber = sqlite.ReducedKDFIterationsNumber
}

if _, err = db.Exec(fmt.Sprintf("PRAGMA kdf_iter = '%d'", kdfIterationsNumber)); err != nil {
return nil, err
// Workaround: casting the driver type breaks the database/sql abstraction
// and may lead to compatibility issues in the future.
// This method is used because the 'database/sql' package does not expose 'ConnectHook',
// thereby making it impossible to individually configure each connection.
// Consequently, the connections from the pool can't be properly decrypted, making them unusable.
sqlcipherDriver, ok := db.Driver().(*sqlcipher.SQLiteDriver)
if !ok {
return nil, fmt.Errorf("unable to get sqlcipher driver")
}
sqlcipherDriver.ConnectHook = func(conn *sqlcipher.SQLiteConn) error {
if _, err = conn.Exec("PRAGMA foreign_keys=ON", []driver.Value{}); err != nil {
return err
}
keyString := fmt.Sprintf("PRAGMA key = '%s'", key)
if _, err = conn.Exec(keyString, []driver.Value{}); err != nil {
return errors.New("failed to set key pragma")
}

if kdfIterationsNumber <= 0 {
kdfIterationsNumber = sqlite.ReducedKDFIterationsNumber
}

if _, err = conn.Exec(fmt.Sprintf("PRAGMA kdf_iter = '%d'", kdfIterationsNumber), []driver.Value{}); err != nil {
return err
}

return nil
}

// readers do not block writers and faster i/o operations
Expand Down

0 comments on commit 7df293e

Please sign in to comment.