Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial WIP #31

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions migrations/2019-04-16-150207_initialize/up.sql
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
CREATE TABLE accounts
(
accountid VARCHAR(56) PRIMARY KEY,
accountid VARCHAR(56) PRIMARY KEY NOT NULL,
balance BIGINT NOT NULL CHECK (balance >= 0),
seqnum BIGINT NOT NULL,
numsubentries INT NOT NULL CHECK (numsubentries >= 0),
Expand All @@ -9,8 +9,8 @@ CREATE TABLE accounts
thresholds TEXT NOT NULL,
flags INT NOT NULL,
lastmodified INT NOT NULL,
buyingliabilities BIGINT CHECK (buyingliabilities >= 0),
sellingliabilities BIGINT CHECK (sellingliabilities >= 0),
buyingliabilities BIGINT NOT NULL CHECK (buyingliabilities >= 0),
sellingliabilities BIGINT NOT NULL CHECK (sellingliabilities >= 0),
signers TEXT
);

Expand Down
6 changes: 0 additions & 6 deletions src/crypto/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,6 @@ use std::str;
/// The Errors that can occur.
#[derive(Debug)]
pub enum Error {
/// Error that can occur when parsing a key.
InvalidStrKey,
/// Invalid version byte in key.
InvalidStrKeyVersionByte,
/// Invalid checksum in key.
InvalidStrKeyChecksum,
/// Invalid keypair seed.
InvalidSeed,
/// Invalid Asset code.
Expand Down
6 changes: 3 additions & 3 deletions src/crypto/keypair.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use super::error::{Error, Result};
use super::strkey;
use crate::stellar_base::strkey;
use super::error::{Result, Error};
use ed25519_dalek::{Keypair, PublicKey, SecretKey};

pub fn from_secret_seed(data: &str) -> Result<Keypair> {
let bytes = strkey::decode_secret_seed(&data)?;
let bytes = strkey::decode_secret_seed(&data).or(Err(Error::InvalidSeed))?;
let secret = SecretKey::from_bytes(&bytes).or(Err(Error::InvalidSeed))?;
let public = PublicKey::from(&secret);
Ok(Keypair {
Expand Down
3 changes: 1 addition & 2 deletions src/crypto/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#![allow(dead_code)]

mod error;
mod keypair;
mod strkey;
mod error;

pub use self::keypair::from_secret_seed;
1 change: 1 addition & 0 deletions src/database/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#![allow(dead_code)]

pub use self::models::peer::Peer;
pub use self::models::account::{Account, BASE_RESERVE};

mod models;
mod repository;
Expand Down
114 changes: 114 additions & 0 deletions src/database/models/account.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
use super::{db_conn, schema::accounts};
use diesel::prelude::*;

// https://www.stellar.org/developers/guides/concepts/accounts.html

// TODO: We should take base reserve from ledger header
pub const BASE_RESERVE: i64 = 5000000;

#[derive(Identifiable, Queryable, Debug)]
#[primary_key(accountid)]
pub struct Account {
/// The public key that was first used to create the account. You can replace the key used for signing the account’s transactions with a different public key, but the original account ID will always be used to identify the account.
pub accountid: String,
/// The number of lumens held by the account. The balance is denominated in 1/10,000,000th of a lumen, the smallest divisible unit of a lumen.
pub balance: i64,
/// The current transaction sequence number of the account. This number starts equal to the ledger number at which the account was created.
pub seqnum: i64,
/// Number of other entries the account owns. This number is used to calculate the account’s minimum balance.
pub numsubentries: i32,
/// (optional) Account designated to receive inflation. Every account with a balance of at least 100 XLM can vote to send inflation to a destination account.
pub inflationdest: Option<String>,
/// A domain name that can optionally be added to the account. Clients can look up a stellar.toml from this domain. This should be in the format of a fully qualified domain name such as example.com.
/// The federation protocol can use the home domain to look up more details about a transaction’s memo or address details about an account. For more on federation, see the federation guide.
pub homedomain: String,
/// Operations have varying levels of access. This field specifies thresholds for low-, medium-, and high-access levels, as well as the weight of the master key. For more info, see multi-sig.
pub thresholds: String,
/// Currently there are three flags, used by issuers of assets.
/// - Authorization required (0x1): Requires the issuing account to give other accounts permission before they can hold the issuing account’s credit.
/// - Authorization revocable (0x2): Allows the issuing account to revoke its credit held by other accounts.
/// - Authorization immutable (0x4): If this is set then none of the authorization flags can be set and the account can never be deleted.
pub flags: i32,
/// updated_at field
pub lastmodified: i32,
/// Starting in protocol version 10, each account also tracks its lumen liabilities. Buying liabilities equal the total amount of lumens offered to buy aggregated over all offers owned by this account, and selling liabilities equal the total amount of lumens offered to sell aggregated over all offers owned by this account. An account must always have balance sufficiently above the minimum reserve to satisfy its lumen selling liabilities, and a balance sufficiently below the maximum to accomodate its lumen buying liabilities
pub buyingliabilities: i64,
pub sellingliabilities: i64,
/// Used for multi-sig. This field lists other public keys and their weights, which can be used to authorize transactions for this account.
pub signers: Option<String>,
}

type Result<T> = std::result::Result<T, diesel::result::Error>;

impl Account {
pub fn all() -> Result<Vec<Account>> {
use self::accounts::dsl::*;

accounts.load::<Account>(&*db_conn())
}

pub fn create(accountid: String) -> Result<usize> {
let new_account = NewAccount::new(accountid);
diesel::insert_into(accounts::table)
.values(&new_account)
.execute(&*db_conn())
}

pub fn get(g_accountid: &str) -> Result<Account> {
use self::accounts::dsl::*;

accounts
.filter(accountid.eq(g_accountid))
.first::<Account>(&*db_conn())
}

pub fn delete(g_accountid: &str) -> Result<usize> {
use self::accounts::dsl::*;

diesel::delete(accounts.filter(accountid.eq(g_accountid))).execute(&*db_conn())
}

// TODO: this should take base reserve from particular
// ledger header into account
// TODO: consider ledger version lower than 8, formulae was
// different back then
pub fn spendable_balance(&self) -> i64 {
self.balance - ((2 + i64::from(self.numsubentries)) * BASE_RESERVE)
}
}

#[derive(Insertable)]
#[table_name = "accounts"]
pub struct NewAccount {
pub accountid: String,
pub balance: i64,
pub seqnum: i64,
pub numsubentries: i32,
pub inflationdest: Option<String>,
pub homedomain: String,
pub thresholds: String,
pub flags: i32,
pub lastmodified: i32,
pub buyingliabilities: i64,
pub sellingliabilities: i64,
pub signers: Option<String>,
}

impl NewAccount {
pub fn new(accountid: String) -> Self {
NewAccount {
accountid,
balance: 0,
seqnum: 0, // TODO: This number starts equal to the ledger number at which the account was created
numsubentries: 0,
inflationdest: None,
homedomain: String::from("example.com"),
thresholds: String::from(""),
flags: 1,
lastmodified: 0,
buyingliabilities: 0,
sellingliabilities: 0,
signers: None,
}
}
}
1 change: 1 addition & 0 deletions src/database/models/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#![allow(dead_code, unused_must_use)]

pub(crate) mod peer;
pub(crate) mod account;
pub(crate) use super::{db_conn, schema, CONFIG};
9 changes: 9 additions & 0 deletions src/factories/internal_xdr.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use crate::xdr;
use rand::rngs::OsRng;
use ed25519_dalek::Keypair;
use serde::ser::Serialize;
use serde_xdr::to_bytes;

Expand Down Expand Up @@ -57,6 +59,13 @@ pub fn build_public_key() -> xdr::PublicKey {
]))
}

pub fn random_public_key() -> xdr::PublicKey {
let mut rng = OsRng::new().unwrap();
let random_keypair = Keypair::generate(&mut rng);

xdr::PublicKey::Ed25519(xdr::Uint256(*random_keypair.public.as_bytes()))
}

pub fn build_operation_result_code() -> xdr::OperationResultCode {
xdr::OperationResultCode::OpNoAccount
}
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ pub(crate) mod network;
pub(crate) mod overlay;
pub(crate) mod schema;
pub(crate) mod scp;
pub(crate) mod stellar_base;
pub(crate) mod transactions;
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ mod network;
mod overlay;
mod schema;
mod scp;
mod stellar_base;
mod xdr;

fn main() {
Expand Down
6 changes: 3 additions & 3 deletions src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ table! {

table! {
accounts (accountid) {
accountid -> Nullable<Text>,
accountid -> Text,
balance -> BigInt,
seqnum -> BigInt,
numsubentries -> Integer,
Expand All @@ -18,8 +18,8 @@ table! {
thresholds -> Text,
flags -> Integer,
lastmodified -> Integer,
buyingliabilities -> Nullable<BigInt>,
sellingliabilities -> Nullable<BigInt>,
buyingliabilities -> BigInt,
sellingliabilities -> BigInt,
signers -> Nullable<Text>,
}
}
Expand Down
1 change: 1 addition & 0 deletions src/stellar_base/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod strkey;
20 changes: 19 additions & 1 deletion src/crypto/strkey.rs → src/stellar_base/strkey.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::error::{Error, Result};
use crate::xdr::{AccountId};
use base32;
use byteorder::{ByteOrder, LittleEndian};
use crc16::{State, XMODEM};
Expand All @@ -10,6 +10,24 @@ const SHA256_HASH_VERSION_BYTE: u8 = 23 << 3; // X

static ALPHABET: base32::Alphabet = base32::Alphabet::RFC4648 { padding: false };

#[derive(Debug)]
pub enum Error {
/// Error that can occur when parsing a key.
InvalidStrKey,
/// Invalid version byte in key.
InvalidStrKeyVersionByte,
/// Invalid checksum in key.
InvalidStrKeyChecksum
}

pub type Result<T> = std::result::Result<T, Error>;

pub fn encode_ed25519_public_key(key: AccountId) -> Result<String> {
match key {
AccountId::Ed25519(opaque) => encode_account_id(&opaque.0)
}
}

pub fn encode_account_id(data: &[u8]) -> Result<String> {
encode_check(ACCOUNT_ID_VERSION_BYTE, data)
}
Expand Down
77 changes: 77 additions & 0 deletions src/transactions/create_account_operation.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
use crate::xdr;
use crate::database::{db_conn, Account, BASE_RESERVE};
use crate::stellar_base::strkey;
use super::utils;
// TODO: I believe, everything should work without using `prelude`. But it doesn't
use diesel::prelude::*;
use diesel::result::Error::NotFound;

pub(crate) fn create_account_operation(source_account: Option<xdr::AccountId>, account_operation: xdr::CreateAccountOp) -> xdr::CreateAccountResultCode {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Arkweid why do we have source_account as an Option here?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, who is the Source Account when I will try to create fresh account for myself?

let dest_account_id = strkey::encode_ed25519_public_key(account_operation.destination).unwrap();

if account_operation.starting_balance < BASE_RESERVE {
xdr::CreateAccountResultCode::CreateAccountLowReserve
} else if Account::get(&dest_account_id).is_ok() {
xdr::CreateAccountResultCode::CreateAccountAlreadyExist
} else {
match source_account {
Some(public_key) => {
let source_account_id = strkey::encode_ed25519_public_key(public_key).unwrap();

match Account::get(&source_account_id) {
Ok(account) => {
if account.spendable_balance() < account_operation.starting_balance {
xdr::CreateAccountResultCode::CreateAccountUnderfunded
} else {
// Actually apply operation
use crate::schema::accounts::dsl::balance;

let new_balance = utils::add_balance(&account, account_operation.starting_balance).unwrap();
diesel::update(&account)
.set(balance.eq(new_balance))
.execute(&*db_conn())
.unwrap();

xdr::CreateAccountResultCode::CreateAccountSuccess
}
},
Err(e) => {
match e {
NotFound => {
xdr::CreateAccountResultCode::CreateAccountMalformed
},
_ => {
// TODO: What do we do in this case?
xdr::CreateAccountResultCode::CreateAccountMalformed
}
}
}
}
}
None => {
xdr::CreateAccountResultCode::CreateAccountUnderfunded
}
}
}
}


#[cfg(test)]
mod tests {
use super::{xdr};
use crate::factories::internal_xdr;

#[test]
fn test_account_operation_with_zero_balance() {
let source_account = internal_xdr::random_public_key();

let operation = xdr::CreateAccountOp {
destination: internal_xdr::random_public_key(),
starting_balance: 0,
};

let result = super::create_account_operation(Some(source_account), operation);

assert_eq!(result, xdr::CreateAccountResultCode::CreateAccountLowReserve);
}
}
21 changes: 21 additions & 0 deletions src/transactions/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// pub(crate) use crate::config::CONFIG;
// pub(crate) use crate::crypto;
// pub(crate) use crate::network::Network;
use crate::xdr;

mod create_account_operation;
mod utils;

use create_account_operation::create_account_operation;
// pub(crate) use lazy_static::lazy_static;

// pub(crate) use crate::database::models::account;

pub fn do_apply(operation: xdr::Operation) {
match operation.body {
xdr::OperationBody::CreateAccountOp(acccount_operation) => {
create_account_operation(operation.source_account, acccount_operation);
},
_ => {}
}
}
Loading