Skip to content

Commit

Permalink
Warnings solved
Browse files Browse the repository at this point in the history
  • Loading branch information
dr-orlovsky committed Jun 14, 2020
1 parent 5773814 commit d1297a5
Show file tree
Hide file tree
Showing 17 changed files with 119 additions and 262 deletions.
7 changes: 6 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ readme = "README.md"
name = "rgb"

[dependencies]
amplify = "~0.1.2"
amplify = "~0.1.3"
amplify_derive = "~0.1.0"
dotenv = "~0.15.0"
clap = "=3.0.0-beta.1"
chrono = { version = "~0.4.11", features = [ "serde" ] }
Expand Down Expand Up @@ -40,6 +41,10 @@ git = "https://github.com/lnp-bp/rust-lnpbp"
branch = "master"
features = ["all"]

[dependencies.lnpbp_derive]
git = "https://github.com/lnp-bp/rust-lnpbp"
branch = "master"

[target.'cfg(target_os="android")'.dependencies.zmq]
version = "~0.9"
features = ["vendored"]
Expand Down
143 changes: 69 additions & 74 deletions src/api/fungible.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,87 @@
// along with this software.
// If not, see <https://opensource.org/licenses/MIT>.

use amplify::Wrapper;
use clap::Clap;
use core::any::Any;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io;
use std::path::PathBuf;
use std::sync::Arc;

use bitcoin::consensus::encode::{Decodable, Encodable};
use bitcoin::hashes::hex::FromHex;
use bitcoin::util::psbt::PartiallySignedTransaction;
use bitcoin::{OutPoint, TxIn};
use bitcoin::OutPoint;

use lnpbp::bitcoin;
use lnpbp::bp;
use lnpbp::lnp::presentation::{Error, UnknownTypeError};
use lnpbp::lnp::{Type, TypedEnum, UnmarshallFn, Unmarshaller};
use lnpbp::rgb::prelude::*;
use lnpbp::strict_encoding::{Error, StrictDecode, StrictEncode};
use lnpbp::strict_encoding::{strict_encode, StrictDecode};

use crate::fungible::{Outcoincealed, Outcoins};
use crate::util::SealSpec;

#[derive(Clap, Clone, PartialEq, Serialize, Deserialize, Debug, Display)]
const TYPE_ISSUE: u16 = 1000;
const TYPE_TRANSFER: u16 = 1001;

#[derive(Clone, PartialEq, Debug, Display)]
#[display_from(Debug)]
#[non_exhaustive]
pub enum Request {
Issue(Issue),
Transfer(TransferApi),
//Receive(Receive),
}

impl TypedEnum for Request {
fn try_from_type(type_id: Type, data: &dyn Any) -> Result<Self, UnknownTypeError> {
Ok(match type_id.into_inner() {
TYPE_ISSUE => Self::Issue(
data.downcast_ref::<Issue>()
.expect("Internal API parser inconsistency")
.clone(),
),
_ => Err(UnknownTypeError)?,
})
}

fn get_type(&self) -> Type {
Type::from_inner(match self {
Request::Issue(_) => TYPE_ISSUE,
_ => unimplemented!(),
})
}

fn get_payload(&self) -> Vec<u8> {
match self {
Request::Issue(issue) => {
strict_encode(issue).expect("Strict encoding for issue structure has failed")
}
_ => unimplemented!(),
}
}
}

impl Request {
pub fn create_unmarshaller() -> Unmarshaller<Self> {
Unmarshaller::new(bmap! {
TYPE_ISSUE => Self::parse_issue as UnmarshallFn<_>,
TYPE_TRANSFER => Self::parse_transfer as UnmarshallFn<_>
})
}

fn parse_issue(mut reader: &mut dyn io::Read) -> Result<Arc<dyn Any>, Error> {
Ok(Arc::new(Issue::strict_decode(&mut reader)?))
}

fn parse_transfer(mut reader: &mut dyn io::Read) -> Result<Arc<dyn Any>, Error> {
Ok(Arc::new(TransferApi::strict_decode(&mut reader)?))
}
}

#[derive(
Clap, Clone, PartialEq, Serialize, Deserialize, StrictEncode, StrictDecode, Debug, Display,
)]
#[display_from(Debug)]
pub struct Issue {
/// Asset ticker
Expand Down Expand Up @@ -67,41 +127,7 @@ pub struct Issue {
pub allocate: Vec<Outcoins>,
}

impl StrictEncode for Issue {
type Error = Error;

fn strict_encode<E: io::Write>(&self, mut e: E) -> Result<usize, Self::Error> {
Ok(strict_encode_list!(e;
self.ticker,
self.title,
self.description,
self.supply,
self.inflatable,
self.precision,
self.dust_limit,
self.allocate
))
}
}

impl StrictDecode for Issue {
type Error = Error;

fn strict_decode<D: io::Read>(mut d: D) -> Result<Self, Self::Error> {
Ok(Self {
ticker: String::strict_decode(&mut d)?,
title: String::strict_decode(&mut d)?,
description: Option::<String>::strict_decode(&mut d)?,
supply: Option::<f32>::strict_decode(&mut d)?,
inflatable: Option::<SealSpec>::strict_decode(&mut d)?,
precision: u8::strict_decode(&mut d)?,
dust_limit: Option::<Amount>::strict_decode(&mut d)?,
allocate: Vec::<Outcoins>::strict_decode(&mut d)?,
})
}
}

#[derive(Clone, PartialEq, Debug, Display)]
#[derive(Clone, PartialEq, StrictEncode, StrictDecode, Debug, Display)]
#[display_from(Debug)]
pub struct TransferApi {
/// Asset contract id
Expand Down Expand Up @@ -129,37 +155,6 @@ pub struct TransferApi {
pub change: Option<OutPoint>,
}

impl StrictEncode for TransferApi {
type Error = Error;

fn strict_encode<E: io::Write>(&self, mut e: E) -> Result<usize, Self::Error> {
let mut len = self.psbt.consensus_encode(&mut e)?;
Ok(strict_encode_list!(e; len;
self.contract_id,
self.inputs,
self.ours,
self.theirs,
self.change
))
}
}

impl StrictDecode for TransferApi {
type Error = Error;

fn strict_decode<D: io::Read>(mut d: D) -> Result<Self, Self::Error> {
let psbt = PartiallySignedTransaction::consensus_decode(&mut d)?;
Ok(Self {
psbt,
contract_id: ContractId::strict_decode(&mut d)?,
inputs: Vec::<OutPoint>::strict_decode(&mut d)?,
ours: Vec::<Outcoins>::strict_decode(&mut d)?,
theirs: Vec::<Outcoincealed>::strict_decode(&mut d)?,
change: Option::<OutPoint>::strict_decode(&mut d)?,
})
}
}

fn ticker_validator(name: &str) -> Result<(), String> {
let re = Regex::new(r"^[A-Z]{3,8}$").expect("Regex parse failure");
if !re.is_match(&name) {
Expand Down
1 change: 0 additions & 1 deletion src/cli/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ use lnpbp::lnp::transport::zmq::SocketLocator;

use super::{fungible, Error, Runtime};
use crate::constants::*;
use crate::error::ServiceErrorDomain;

#[derive(Clap, Clone, Debug, Display)]
#[display_from(Debug)]
Expand Down
15 changes: 6 additions & 9 deletions src/cli/fungible.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,22 @@
// along with this software.
// If not, see <https://opensource.org/licenses/MIT>.

use bech32::{self, ToBase32};
use clap::Clap;
use std::fs;
use std::path::PathBuf;
use std::{fs, io};

use bitcoin::consensus::Decodable;
use bitcoin::hashes::hex::FromHex;
use bitcoin::util::psbt::{self, PartiallySignedTransaction};
use bitcoin::{OutPoint, Transaction, TxIn, TxOut};
use bitcoin::{OutPoint, Transaction, TxIn};

use lnpbp::bitcoin;
use lnpbp::bp;
use lnpbp::rgb::prelude::*;
use lnpbp::strict_encoding::strict_encode;

use super::{Error, Runtime};
use crate::api::fungible::{Issue, TransferApi};
use crate::error::ServiceErrorDomain;
use crate::fungible::{IssueStructure, Outcoincealed, Outcoins};
use crate::fungible::{Outcoincealed, Outcoins};

#[derive(Clap, Clone, Debug, Display)]
#[display_from(Debug)]
Expand Down Expand Up @@ -103,7 +100,7 @@ impl Command {
Command::List => {
println!("\nKnown assets:\n\n");
unimplemented!();
Ok(())
//Ok(())
}
Command::Issue(issue) => issue.exec(runtime),
Command::Transfer(transfer) => transfer.exec(runtime),
Expand Down Expand Up @@ -143,14 +140,14 @@ impl TransferCli {
info!("Transferring asset ...");
debug!("{}", self.clone());

let mut psbt = match self.psbt {
let psbt = match self.psbt {
Some(filename) => {
debug!(
"Reading partially-signed transaction from file {:?}",
filename
);
let filepath = format!("{:?}", filename.clone());
let mut file = fs::File::open(filename)
let file = fs::File::open(filename)
.map_err(|_| Error::InputFileIoError(format!("{:?}", filepath)))?;
let psbt = PartiallySignedTransaction::consensus_decode(file).map_err(|err| {
Error::InputFileFormatError(format!("{:?}", filepath), format!("{}", err))
Expand Down
13 changes: 4 additions & 9 deletions src/cli/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,19 @@
// along with this software.
// If not, see <https://opensource.org/licenses/MIT>.

use std::io;
use std::sync::Arc;

use lnpbp::lnp::presentation::Encode;
use lnpbp::lnp::transport::zmq::ApiType;
use lnpbp::lnp::{transport, NoEncryption, Session, Unmarshall, Unmarshaller};
use lnpbp::rgb::Genesis;

use super::{Config, Error};
use crate::api::fungible::{Issue, TransferApi};
use crate::api::fungible::{Issue, Request, TransferApi};
use crate::api::Reply;
use crate::error::{BootstrapError, ServiceErrorDomain};
use crate::fungible::{Asset, Command};

pub struct Runtime {
config: Config,
context: zmq::Context,
session_rpc: Session<NoEncryption, transport::zmq::Connection>,
unmarshaller: Unmarshaller<Reply>,
}
Expand All @@ -43,13 +39,12 @@ impl Runtime {
)?;
Ok(Self {
config,
context,
session_rpc,
unmarshaller: Reply::create_unmarshaller(),
})
}

fn command(&mut self, command: Command) -> Result<Arc<Reply>, ServiceErrorDomain> {
fn command(&mut self, command: Request) -> Result<Arc<Reply>, ServiceErrorDomain> {
let data = command.encode()?;
self.session_rpc.send_raw_message(data)?;
let raw = self.session_rpc.recv_raw_message()?;
Expand All @@ -59,11 +54,11 @@ impl Runtime {

#[inline]
pub fn issue(&mut self, issue: Issue) -> Result<Arc<Reply>, Error> {
Ok(self.command(Command::Issue(issue))?)
Ok(self.command(Request::Issue(issue))?)
}

#[inline]
pub fn transfer(&mut self, transfer: TransferApi) -> Result<Arc<Reply>, Error> {
Ok(self.command(Command::Transfer(transfer))?)
Ok(self.command(Request::Transfer(transfer))?)
}
}
8 changes: 5 additions & 3 deletions src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@
//! Shared constants, including configuration parameters etc
pub const RGB_BECH32_HRP_ID: &'static str = "rgb";
pub const RGB_BECH32_HRP_GENESIS: &'static str = "rgb:gen";
pub const RGB_BECH32_HRP_TRANSITION: &'static str = "rgb:ts";
pub const RGB_BECH32_HRP_CONSIGNMENT: &'static str = "rgb:cs";
pub const RGB_BECH32_HRP_GENESIS: &'static str = "rgb:g";
pub const RGB_BECH32_HRP_TRANSITION: &'static str = "rgb:t";
pub const RGB_BECH32_HRP_CONSIGNMENT: &'static str = "rgb:c";
pub const RGB_BECH32_HRP_RGB20ASSET: &'static str = "rgb20a";
pub const RGB_BECH32_HRP_RGB20INVOICE: &'static str = "rgb20i";

pub const RGB_DATA_DIR: &'static str = "/var/lib/rgb";
pub const RGB_BIN_DIR: &'static str = "/usr/local/bin";
Expand Down
2 changes: 1 addition & 1 deletion src/contracts/fungible/cache/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ impl Cache for FileCache {
}

fn add_asset(&mut self, asset: Asset) -> Result<bool, CacheError> {
let exists = self.assets.insert(asset.id(), asset).is_some();
let exists = self.assets.insert(*asset.id(), asset).is_some();
self.save()?;
Ok(exists)
}
Expand Down
Loading

0 comments on commit d1297a5

Please sign in to comment.