Skip to content

Commit

Permalink
Relax trait restrictions for schemadb
Browse files Browse the repository at this point in the history
1. remove Default trait restriction for account storage
  • Loading branch information
simonjiao committed Sep 11, 2023
1 parent bbd87b7 commit 766b03d
Show file tree
Hide file tree
Showing 9 changed files with 58 additions and 122 deletions.
10 changes: 5 additions & 5 deletions account/src/account_schemadb/accepted_token.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use super::AccountAddressWrapper;
use anyhow::Result;
use bcs_ext::BCSCodec;
use serde::{Deserialize, Serialize};
Expand All @@ -7,24 +6,25 @@ use starcoin_schemadb::{
schema::{KeyCodec, ValueCodec},
ColumnFamilyName,
};
use starcoin_types::account_address::AccountAddress;
use starcoin_types::account_config::token_code::TokenCode;

pub const ACCEPTED_TOKEN_PREFIX_NAME: ColumnFamilyName = "accepted_token";

define_schema!(
AcceptedToken,
AccountAddressWrapper,
AccountAddress,
AcceptedTokens,
ACCEPTED_TOKEN_PREFIX_NAME
);

impl KeyCodec<AcceptedToken> for AccountAddressWrapper {
impl KeyCodec<AcceptedToken> for AccountAddress {
fn encode_key(&self) -> Result<Vec<u8>> {
Ok(self.0.to_vec())
Ok(self.to_vec())
}

fn decode_key(data: &[u8]) -> Result<Self> {
AccountAddressWrapper::try_from(data)
AccountAddress::try_from(data).map_err(Into::into)
}
}

Expand Down
3 changes: 1 addition & 2 deletions account/src/account_schemadb/global_setting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@ define_schema!(
GLOBAL_PREFIX_NAME
);

#[derive(Default, Hash, Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub enum GlobalSettingKey {
#[default]
DefaultAddress,
/// FIXME: once db support iter, remove this.
AllAddresses,
Expand Down
24 changes: 0 additions & 24 deletions account/src/account_schemadb/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use anyhow::Result;
use starcoin_schemadb::schema::Schema;
use starcoin_storage::cache_storage::GCacheStorage;
use starcoin_types::account_address::AccountAddress;
use std::sync::Arc;

mod accepted_token;
Expand All @@ -17,29 +16,6 @@ pub(crate) use public_key::*;
pub(crate) use setting::*;
use starcoin_schemadb::{db::DBStorage as DB, SchemaBatch};

#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Hash, Clone, Copy)]
pub(crate) struct AccountAddressWrapper(AccountAddress);

impl Default for AccountAddressWrapper {
fn default() -> Self {
Self(AccountAddress::ZERO)
}
}
impl From<AccountAddress> for AccountAddressWrapper {
fn from(value: AccountAddress) -> Self {
Self(value)
}
}
impl TryFrom<&[u8]> for AccountAddressWrapper {
type Error = anyhow::Error;

fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
AccountAddress::try_from(value)
.map(Self)
.map_err(Into::into)
}
}

#[derive(Clone)]
pub(super) struct AccountStore<S: Schema> {
cache: Arc<GCacheStorage<S::Key, S::Value>>,
Expand Down
10 changes: 5 additions & 5 deletions account/src/account_schemadb/private_key.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
use super::AccountAddressWrapper;
use anyhow::Result;
use starcoin_schemadb::{
define_schema,
schema::{KeyCodec, ValueCodec},
ColumnFamilyName,
};
use starcoin_types::account_address::AccountAddress;

pub const ENCRYPTED_PRIVATE_KEY_PREFIX_NAME: ColumnFamilyName = "encrypted_private_key";

define_schema!(
PrivateKey,
AccountAddressWrapper,
AccountAddress,
EncryptedPrivateKey,
ENCRYPTED_PRIVATE_KEY_PREFIX_NAME
);

impl KeyCodec<PrivateKey> for AccountAddressWrapper {
impl KeyCodec<PrivateKey> for AccountAddress {
fn encode_key(&self) -> Result<Vec<u8>> {
Ok(self.0.to_vec())
Ok(self.to_vec())
}

fn decode_key(data: &[u8]) -> Result<Self> {
AccountAddressWrapper::try_from(data)
AccountAddress::try_from(data).map_err(Into::into)
}
}

Expand Down
38 changes: 11 additions & 27 deletions account/src/account_schemadb/public_key.rs
Original file line number Diff line number Diff line change
@@ -1,54 +1,38 @@
use super::AccountAddressWrapper;
use anyhow::{format_err, Result};
use anyhow::Result;
use bcs_ext::BCSCodec;
use starcoin_account_api::AccountPublicKey;
use starcoin_schemadb::{
define_schema,
schema::{KeyCodec, ValueCodec},
ColumnFamilyName,
};
use starcoin_types::account_address::AccountAddress;

pub const PUBLIC_KEY_PREFIX_NAME: ColumnFamilyName = "public_key";

define_schema!(
PublicKey,
AccountAddressWrapper,
PublicKeyWrapper,
AccountAddress,
AccountPublicKey,
PUBLIC_KEY_PREFIX_NAME
);

impl KeyCodec<PublicKey> for AccountAddressWrapper {
impl KeyCodec<PublicKey> for AccountAddress {
fn encode_key(&self) -> Result<Vec<u8>> {
Ok(self.0.to_vec())
Ok(self.to_vec())
}

fn decode_key(data: &[u8]) -> Result<Self> {
AccountAddressWrapper::try_from(data)
AccountAddress::try_from(data).map_err(Into::into)
}
}

#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct PublicKeyWrapper(pub(crate) Option<AccountPublicKey>);
impl From<AccountPublicKey> for PublicKeyWrapper {
fn from(s: AccountPublicKey) -> Self {
Self(Some(s))
}
}

impl From<PublicKeyWrapper> for AccountPublicKey {
fn from(value: PublicKeyWrapper) -> Self {
value.0.expect("NullValue")
}
}

impl ValueCodec<PublicKey> for PublicKeyWrapper {
impl ValueCodec<PublicKey> for AccountPublicKey {
fn encode_value(&self) -> Result<Vec<u8>> {
match &self.0 {
Some(p) => Ok(bcs_ext::to_bytes(&p)?),
None => Err(format_err!("NullValue")),
}
self.encode()
}

fn decode_value(data: &[u8]) -> Result<Self> {
Ok(Self::from(bcs_ext::from_bytes::<AccountPublicKey>(data)?))
bcs_ext::from_bytes::<AccountPublicKey>(data)
}
}
31 changes: 8 additions & 23 deletions account/src/account_schemadb/setting.rs
Original file line number Diff line number Diff line change
@@ -1,47 +1,32 @@
use super::AccountAddressWrapper;
use anyhow::Result;
use starcoin_account_api::Setting;
use starcoin_schemadb::{
define_schema,
schema::{KeyCodec, ValueCodec},
ColumnFamilyName,
};
use starcoin_types::account_address::AccountAddress;

pub const SETTING_PREFIX_NAME: ColumnFamilyName = "account_settings";

define_schema!(
AccountSetting,
AccountAddressWrapper,
SettingWrapper,
SETTING_PREFIX_NAME
);
define_schema!(AccountSetting, AccountAddress, Setting, SETTING_PREFIX_NAME);

#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct SettingWrapper(pub(crate) Setting);
impl From<Setting> for SettingWrapper {
fn from(setting: Setting) -> Self {
Self(setting)
}
}

impl KeyCodec<AccountSetting> for AccountAddressWrapper {
impl KeyCodec<AccountSetting> for AccountAddress {
fn encode_key(&self) -> Result<Vec<u8>> {
Ok(self.0.to_vec())
Ok(self.to_vec())
}

fn decode_key(data: &[u8]) -> Result<Self> {
AccountAddressWrapper::try_from(data)
AccountAddress::try_from(data).map_err(Into::into)
}
}
/// Setting use json encode/decode for support more setting field in the future.
impl ValueCodec<AccountSetting> for SettingWrapper {
impl ValueCodec<AccountSetting> for Setting {
fn encode_value(&self) -> Result<Vec<u8>> {
serde_json::to_vec(&self.0).map_err(Into::into)
serde_json::to_vec(&self).map_err(Into::into)
}

fn decode_value(data: &[u8]) -> Result<Self> {
serde_json::from_slice::<Setting>(data)
.map(Into::into)
.map_err(Into::into)
serde_json::from_slice::<Setting>(data).map_err(Into::into)
}
}
52 changes: 22 additions & 30 deletions account/src/account_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
// SPDX-License-Identifier: Apache-2.0

use crate::account_schemadb::{
AcceptedToken, AcceptedTokens, AccountAddressWrapper, AccountSetting, AccountStore,
EncryptedPrivateKey, GlobalSetting, GlobalSettingKey, GlobalValue, PrivateKey, PublicKey,
SettingWrapper, ACCEPTED_TOKEN_PREFIX_NAME, ENCRYPTED_PRIVATE_KEY_PREFIX_NAME,
GLOBAL_PREFIX_NAME, PUBLIC_KEY_PREFIX_NAME, SETTING_PREFIX_NAME,
AcceptedToken, AcceptedTokens, AccountSetting, AccountStore, EncryptedPrivateKey,
GlobalSetting, GlobalSettingKey, GlobalValue, PrivateKey, PublicKey,
ACCEPTED_TOKEN_PREFIX_NAME, ENCRYPTED_PRIVATE_KEY_PREFIX_NAME, GLOBAL_PREFIX_NAME,
PUBLIC_KEY_PREFIX_NAME, SETTING_PREFIX_NAME,
};
use anyhow::{Error, Result};
use starcoin_account_api::{AccountPrivateKey, AccountPublicKey, Setting};
Expand Down Expand Up @@ -89,7 +89,7 @@ impl AccountStorage {
}

pub fn contain_address(&self, address: AccountAddress) -> Result<bool> {
match self.get_public_key(&address.into())? {
match self.get_public_key(&address)? {
Some(v) => {
let _ = Into::<AccountPublicKey>::into(v);
Ok(true)
Expand Down Expand Up @@ -148,22 +148,19 @@ impl AccountStorage {
Ok(value.map(|v| v.addresses).unwrap_or_default())
}

fn get_public_key(&self, address: &AccountAddressWrapper) -> Result<Option<AccountPublicKey>> {
Ok(self.public_key_store.get(address)?.map(Into::into))
fn get_public_key(&self, address: &AccountAddress) -> Result<Option<AccountPublicKey>> {
self.public_key_store.get(address)
}

fn put_public_key(&self, key: AccountAddress, value: AccountPublicKey) -> Result<()> {
self.public_key_store.put(key.into(), value.into())
self.public_key_store.put(key, value)
}

pub fn public_key(&self, address: AccountAddress) -> Result<Option<AccountPublicKey>> {
self.get_public_key(&address.into())
self.get_public_key(&address)
}

fn get_private_key(
&self,
address: &AccountAddressWrapper,
) -> Result<Option<EncryptedPrivateKey>> {
fn get_private_key(&self, address: &AccountAddress) -> Result<Option<EncryptedPrivateKey>> {
self.private_key_store.get(address)
}

Expand All @@ -179,7 +176,7 @@ impl AccountStorage {
address: AccountAddress,
password: impl AsRef<str>,
) -> Result<Option<AccountPrivateKey>> {
match self.get_private_key(&address.into())? {
match self.get_private_key(&address)? {
None => Ok(None),
Some(encrypted_key) => {
let plain_key_data = decrypt(password.as_ref().as_bytes(), &encrypted_key.0)?;
Expand Down Expand Up @@ -207,27 +204,24 @@ impl AccountStorage {
let batch = SchemaBatch::default();
let encrypted_prikey = encrypt(password.as_ref().as_bytes(), &private_key.to_bytes());
self.private_key_store
.put_batch(address.into(), encrypted_prikey.into(), &batch)?;
.put_batch(address, encrypted_prikey.into(), &batch)?;
let public_key = private_key.public_key();
self.public_key_store
.put_batch(address.into(), public_key.into(), &batch)?;
.put_batch(address, public_key, &batch)?;
self.write_schemas(batch)?;
Ok(())
}

fn put_setting(&self, address: AccountAddress, setting: Setting) -> Result<()> {
let key: AccountAddressWrapper = address.into();
let value: SettingWrapper = setting.into();
self.setting_store.put(key, value)
self.setting_store.put(address, setting)
}

pub fn update_setting(&self, address: AccountAddress, setting: Setting) -> Result<()> {
self.put_setting(address, setting)
}

pub fn load_setting(&self, address: AccountAddress) -> Result<Setting> {
let key: AccountAddressWrapper = address.into();
Ok(self.setting_store.get(&key)?.unwrap_or_default().0)
Ok(self.setting_store.get(&address)?.unwrap_or_default())
}

pub fn destroy_account(&self, address: AccountAddress) -> Result<()> {
Expand Down Expand Up @@ -255,11 +249,10 @@ impl AccountStorage {
}
}

let key: AccountAddressWrapper = address.into();
self.private_key_store.remove_batch(&key, &batch)?;
self.public_key_store.remove_batch(&key, &batch)?;
self.setting_store.remove_batch(&key, &batch)?;
self.accepted_token_store.remove_batch(&key, &batch)?;
self.private_key_store.remove_batch(&address, &batch)?;
self.public_key_store.remove_batch(&address, &batch)?;
self.setting_store.remove_batch(&address, &batch)?;
self.accepted_token_store.remove_batch(&address, &batch)?;

// persist updates to underlying storage
self.db
Expand All @@ -270,12 +263,11 @@ impl AccountStorage {
}

pub fn get_accepted_tokens(&self, address: AccountAddress) -> Result<Vec<TokenCode>> {
let key: AccountAddressWrapper = address.into();
let ts = self.accepted_token_store.get(&key)?;
let ts = self.accepted_token_store.get(&address)?;
Ok(ts.map(|t| t.0).unwrap_or_default())
}

fn put_accepted_tokens(&self, key: AccountAddressWrapper, value: AcceptedTokens) -> Result<()> {
fn put_accepted_tokens(&self, key: AccountAddress, value: AcceptedTokens) -> Result<()> {
self.accepted_token_store.put(key, value)
}

Expand All @@ -287,7 +279,7 @@ impl AccountStorage {
let mut tokens = self.get_accepted_tokens(address)?;
if !tokens.contains(&token_code) {
tokens.push(token_code);
self.put_accepted_tokens(address.into(), AcceptedTokens(tokens))?;
self.put_accepted_tokens(address, AcceptedTokens(tokens))?;
}
Ok(())
}
Expand Down
4 changes: 2 additions & 2 deletions storage/schemadb/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ where
pub trait Schema: Debug + Send + Sync + 'static {
const COLUMN_FAMILY: &'static str;

type Key: KeyCodec<Self> + Hash + Eq + Default;
type Value: ValueCodec<Self> + Default + Clone;
type Key: KeyCodec<Self> + Hash + Eq;
type Value: ValueCodec<Self>;
}

#[macro_export]
Expand Down
Loading

0 comments on commit 766b03d

Please sign in to comment.