From 4a06b14b9724e69b8543f3173e562e6797211111 Mon Sep 17 00:00:00 2001 From: Torben Poguntke Date: Tue, 9 Jan 2024 14:10:33 +0100 Subject: [PATCH] cleanup --- README.md | 2 +- drasil-dvltath/Cargo.toml | 4 +- drasil-gungnir/Cargo.toml | 15 +- .../up.sql | 18 - .../migrations/00000001_init/up.sql | 507 +++++++++--------- .../src/bin/create_token_whitelisting.rs | 94 ---- drasil-hugin/Cargo.toml | 4 +- drasil-hugin/migrations/000001_init/up.sql | 230 ++++---- drasil-hugin/src/datamodel/models.rs | 10 +- .../src/protocol/cmd/buildmultisig.rs | 18 +- .../src/protocol/cmd/finalizemultisig.rs | 1 - .../src/protocol/multisig/moneshot_handler.rs | 22 +- .../src/protocol/multisig/reward_handler.rs | 102 ++-- .../src/protocol/multisig/testrwd_handler.rs | 4 +- .../src/protocol/stdtx/delegation_handler.rs | 42 +- .../protocol/stdtx/deregistration_handler.rs | 14 +- .../src/protocol/stdtx/standard_tx.rs | 9 - .../src/protocol/stdtx/withdrawal_handler.rs | 71 ++- drasil-mimir/Cargo.toml | 4 +- drasil-mimir/src/api.rs | 86 ++- drasil-mimir/src/lib.rs | 20 - drasil-murin/Cargo.toml | 4 +- drasil-murin/src/cardano/cip30/wallet.rs | 39 +- drasil-murin/src/cardano/mod.rs | 87 --- drasil-murin/src/cardano/models.rs | 7 +- .../src/cardano/supporting_functions.rs | 54 +- drasil-murin/src/txbuilder/marketplace/mod.rs | 99 ---- .../src/txbuilder/minter/build_minttx.rs | 29 +- .../txbuilder/minter/build_oneshot_mint.rs | 37 +- drasil-murin/src/txbuilder/minter/mod.rs | 38 +- .../src/txbuilder/modules/transfer/models.rs | 29 +- .../src/txbuilder/modules/txtools/lib.rs | 1 - .../src/txbuilder/modules/txtools/mod.rs | 1 - .../src/txbuilder/modules/txtools/models.rs | 11 - .../modules/txtools/utxo_handling.rs | 33 +- .../src/txbuilder/rwdist/build_rwd.rs | 3 - drasil-murin/src/txbuilder/rwdist/mod.rs | 23 +- drasil-murin/src/txbuilder/stdtx/build_cpo.rs | 1 - drasil-sleipnir/Cargo.toml | 10 +- drasil-sleipnir/src/apiauth/mod.rs | 4 +- drasil-sleipnir/src/bin/create_mintpolicy.rs | 76 --- drasil-sleipnir/src/minting/api.rs | 51 +- drasil-sleipnir/src/minting/mod.rs | 1 - jobs/freki/Cargo.toml | 4 +- jobs/utxopti/Cargo.toml | 4 +- jobs/utxopti/src/lib.rs | 35 +- jobs/utxopti/src/models.rs | 0 services/frigg/Cargo.toml | 4 +- services/frigg/src/handler/mint.rs | 46 -- services/heimdallr/Cargo.toml | 4 +- services/heimdallr/src/clientapi/handlers.rs | 4 +- services/loki/Cargo.toml | 4 +- services/loki/src/auth.rs | 25 +- services/loki/src/error.rs | 2 - services/loki/src/handlers.rs | 3 +- services/odin/Cargo.toml | 4 +- services/vidar/Cargo.toml | 4 +- worker/geri/Cargo.toml | 4 +- worker/geri/src/main.rs | 2 - worker/jobs/Cargo.toml | 4 +- worker/work_loki/Cargo.toml | 4 +- worker/work_loki/src/handlers.rs | 0 worker/work_loki/src/main.rs | 1 - 63 files changed, 618 insertions(+), 1455 deletions(-) delete mode 100644 drasil-gungnir/src/bin/create_token_whitelisting.rs delete mode 100644 drasil-murin/src/txbuilder/modules/txtools/lib.rs delete mode 100644 drasil-sleipnir/src/bin/create_mintpolicy.rs delete mode 100644 jobs/utxopti/src/models.rs delete mode 100644 worker/work_loki/src/handlers.rs diff --git a/README.md b/README.md index 2ddd1aab..be96c066 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Drasil is an opinionated implementation of a software suite to run applications on Cardano, it is a collection of microservices which, when used together, form an effective and scalable framework for running applications on the Cardano blockchain. Its architecture, services and libraries are written in Rust. -# The codebase is still under development and not considered production ready, use on own risk. +## ! The codebase is under development ! Drasil system and concept was created by Torben and Zak, but it also utilises several tools developed by the Cardano community, to whom we are grateful and hope to continue to repay with our own small contributions. Because of the way in which the various tools interact, more is required to actually run a fully integrated and working "Drasil System" than just the applications and libraries found in this repository! (Redis, RabbitMQ, Cardano-Node, Dbsync, Oura, Postgres) diff --git a/drasil-dvltath/Cargo.toml b/drasil-dvltath/Cargo.toml index fd6f5e99..34c679ae 100644 --- a/drasil-dvltath/Cargo.toml +++ b/drasil-dvltath/Cargo.toml @@ -5,8 +5,8 @@ edition = "2021" description = "Hashicorp Vault Authorizer Sidecar for Drasil" repository = "https://github.com/Sbcdn/drasil.git" documentation = "https://docs.drasil.io" -license = "LICENSE_GPL.md" -readme = "README.md" +license = "https://github.com/Sbcdn/drasil/blob/main/LICENSE.md" +readme = "https://github.com/Sbcdn/drasil/blob/main/README.md" authors = ["Torben Poguntke "] [dependencies] diff --git a/drasil-gungnir/Cargo.toml b/drasil-gungnir/Cargo.toml index 62e28b43..3299a6d7 100644 --- a/drasil-gungnir/Cargo.toml +++ b/drasil-gungnir/Cargo.toml @@ -5,8 +5,8 @@ edition = "2021" description = "Drasil Blockchain Application Framework - Reward Library" repository = "https://github.com/Sbcdn/drasil.git" documentation = "https://docs.drasil.io" -license = "LICENSE_GPL.md" -readme = "README.md" +license = "https://github.com/Sbcdn/drasil/blob/main/LICENSE.md" +readme = "https://github.com/Sbcdn/drasil/blob/main/README.md" authors = ["Torben Poguntke "] [dependencies] @@ -37,13 +37,4 @@ features = [ "64-column-tables", "r2d2", "serde_json", -] - - -[features] -mimir_bin = ["drasil-mimir", "structopt"] - - -[[bin]] -name = "create_token_whitelisting" -required-features = ["mimir_bin"] +] diff --git a/drasil-gungnir/migrations/00000000000000_diesel_initial_setup/up.sql b/drasil-gungnir/migrations/00000000000000_diesel_initial_setup/up.sql index d68895b1..08d6f2ac 100644 --- a/drasil-gungnir/migrations/00000000000000_diesel_initial_setup/up.sql +++ b/drasil-gungnir/migrations/00000000000000_diesel_initial_setup/up.sql @@ -1,21 +1,3 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ BEGIN EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s diff --git a/drasil-gungnir/migrations/00000001_init/up.sql b/drasil-gungnir/migrations/00000001_init/up.sql index 5a6b1998..4fbcac3a 100644 --- a/drasil-gungnir/migrations/00000001_init/up.sql +++ b/drasil-gungnir/migrations/00000001_init/up.sql @@ -1,253 +1,254 @@ - -CREATE OR REPLACE FUNCTION trigger_set_timestamp() -RETURNS TRIGGER AS $$ -BEGIN - NEW.updated_at = NOW(); - RETURN NEW; -END; -$$ LANGUAGE plpgsql; - -CREATE TYPE public.calculationmode AS ENUM ( - 'custom', - 'modifactorandequation', - 'simpleequation', - 'fixedendepoch', - 'relationaltoadastake', - 'airdrop' -); - -CREATE DOMAIN public.amount AS numeric(20,0) - CONSTRAINT amount_check CHECK (((VALUE >= (0)::numeric) AND (VALUE <= '18446744073709551615'::numeric))); - - -CREATE TABLE rewards ( - id BIGSERIAL PRIMARY KEY, - stake_addr VARCHAR(100) NOT NULL, - payment_addr VARCHAR(200) NOT NULL, - fingerprint VARCHAR(100) NOT NULL, - contract_id BIGINT NOT NULL, - user_id BIGINT NOT NULL, - tot_earned amount NOT NULL, - tot_claimed amount NOT NULL, - oneshot BOOLEAN NOT NULL, - last_calc_epoch BIGINT NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE TABLE claimed ( - id BIGSERIAL PRIMARY KEY, - stake_addr VARCHAR(100) NOT NULL, - payment_addr VARCHAR(140) NOT NULL, - fingerprint VARCHAR(100) NOT NULL, - amount amount NOT NULL, - contract_id BIGINT NOT NULL, - user_id BIGINT NOT NULL, - txhash VARCHAR(120) NOT NULL, - invalid BOOLEAN, - invalid_descr TEXT, - timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - - -CREATE TABLE token_whitelist ( - id BIGSERIAL PRIMARY KEY, - fingerprint VARCHAR(100), - policy_id VARCHAR(100) NOT NULL, - tokenname VARCHAR(140), - contract_id BIGINT NOT NULL, - user_id BIGINT NOT NULL, - vesting_period TIMESTAMPTZ NOT NULL DEFAULT NOW(), -- All new entries are valid on creation, vesting has to be set explicitly - pools TEXT[] NOT NULL, - mode calculationmode NOT NULL, - equation TEXT NOT NULL, - start_epoch BIGINT NOT NULL, - end_epoch BIGINT, - modificator_equ TEXT, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -ALTER TYPE public.calculationmode ADD VALUE IF NOT EXISTS 'custom' BEFORE 'fixedamountperepoch'; - -CREATE TABLE airdrop_whitelist ( - id BIGSERIAL PRIMARY KEY, - contract_id BIGINT NOT NULL, - user_id BIGINT NOT NULL, - reward_created BOOLEAN NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - - -CREATE TABLE airdrop_parameter ( - id BIGSERIAL PRIMARY KEY, - contract_id BIGINT NOT NULL, - user_id BIGINT NOT NULL, - airdrop_type_type VARCHAR(3) NOT NULL, - distribution_type VARCHAR(100) NOT NULL, - selection_type TEXT NOT NULL, - args_1 TEXT[] NOT NULL, - args_2 TEXT[] NOT NULL, - args_3 TEXT[] NOT NULL, - whitelist_ids BIGINT[], - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE TRIGGER set_timestamp -BEFORE UPDATE ON airdrop_whitelist -FOR EACH ROW -EXECUTE PROCEDURE trigger_set_timestamp(); - -CREATE TRIGGER set_timestamp -BEFORE UPDATE ON airdrop_parameter -FOR EACH ROW -EXECUTE PROCEDURE trigger_set_timestamp(); - -CREATE TYPE public.whitelisttype AS ENUM ( - 'RandomContained', - 'SpecificAsset', - 'RandomPreallocated' -); - -CREATE TABLE wladdresses ( - id BIGSERIAL PRIMARY KEY, - payment_address VARCHAR NOT NULL UNIQUE, - stake_address VARCHAR -); - -CREATE TABLE wlalloc ( - wl BIGINT NOT NULL, - addr BIGINT NOT NULL, - specific_asset Jsonb, - PRIMARY KEY(wl,addr,specific_asset) -); -ALTER TABLE wlalloc ADD CONSTRAINT unique_token_per_whitelist UNIQUE(wl, specific_asset); - -CREATE TABLE whitelist ( - id BIGSERIAL PRIMARY KEY, - user_id BIGINT NOT NULL, - max_addr_repeat INTEGER NOT NULL, - wl_type whitelisttype NOT NULL, - description VARCHAR NOT NULL, - notes VARCHAR NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE TRIGGER set_timestamp -BEFORE UPDATE ON whitelist -FOR EACH ROW -EXECUTE PROCEDURE trigger_set_timestamp(); - -CREATE TABLE mint_projects ( - id BIGSERIAL PRIMARY KEY, - project_name VARCHAR NOT NULL, - user_id BIGINT NOT NULL, - mint_contract_id BIGINT NOT NULL, - whitelists BIGINT[], - mint_start_date TIMESTAMPTZ NOT NULL, - mint_end_date TIMESTAMPTZ, - storage_type Varchar NOT NULL, - storage_url Varchar, - storage_access_token Varchar, - collection_name VARCHAR NOT NULL, - author VARCHAR(64) NOT NULL, - meta_description VARCHAR(64) NOT NULL, - meta_common_nft_name VARCHAR(64), - max_mint_p_addr INTEGER, - nft_table_name VARCHAR(64) NOT NULL UNIQUE, - active BOOLEAN NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - UNIQUE (user_id,mint_contract_id), - UNIQUE (user_id,collection_name) -); - -CREATE TRIGGER set_timestamp -BEFORE UPDATE ON mint_projects -FOR EACH ROW -EXECUTE PROCEDURE trigger_set_timestamp(); - -CREATE TABLE nft_table ( - project_id BIGINT NOT NULL, - asset_name_b BYTEA NOT NULL, - asset_name VARCHAR NOT NULL, - fingerprint VARCHAR NOT NULL, - nft_id VARCHAR NOT NULL, - file_name VARCHAR NOT NULL, - ipfs_hash VARCHAR, - metadata TEXT NOT NULL, - claim_addr VARCHAR, - minted BOOLEAN NOT NULL, - tx_hash VARCHAR, - confirmed BOOLEAN, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - PRIMARY KEY(project_id,asset_name_b) -); - -CREATE TRIGGER set_timestamp -BEFORE UPDATE ON nft_table -FOR EACH ROW -EXECUTE PROCEDURE trigger_set_timestamp(); - -CREATE INDEX nft_project ON nft_table (project_id); -CREATE EXTENSION tsm_system_rows; - -CREATE TABLE discount ( - id BIGSERIAL PRIMARY KEY, - contract_id BIGINT NOT NULL, - user_id BIGINT NOT NULL, - policy_id VARCHAR NOT NULL, - fingerprint VARCHAR, - metadata_path VARCHAR[] NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - UNIQUE (user_id,contract_id,policy_id) -); - -CREATE TRIGGER set_timestamp -BEFORE UPDATE ON discount -FOR EACH ROW -EXECUTE PROCEDURE trigger_set_timestamp(); - -CREATE TABLE mint_rewards ( - id BIGSERIAL PRIMARY KEY, - project_id BIGINT NOT NULL, - pay_addr VARCHAR NOT NULL, - nft_ids Bytea[] NOT NULL, - v_nfts_b Bytea[] NOT NULL, - processed BOOLEAN NOT NULL, - minted BOOLEAN NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - UNIQUE (project_id,nft_ids) -); - -CREATE TRIGGER set_timestamp -BEFORE UPDATE ON mint_rewards -FOR EACH ROW -EXECUTE PROCEDURE trigger_set_timestamp(); - - -CREATE TRIGGER set_timestamp -BEFORE UPDATE ON rewards -FOR EACH ROW -EXECUTE PROCEDURE trigger_set_timestamp(); - -CREATE TRIGGER set_timestamp -BEFORE UPDATE ON claimed -FOR EACH ROW -EXECUTE PROCEDURE trigger_set_timestamp(); - -CREATE TRIGGER set_timestamp -BEFORE UPDATE ON token_whitelist -FOR EACH ROW -EXECUTE PROCEDURE trigger_set_timestamp(); - -ALTER TABLE rewards ADD CONSTRAINT unique_stake_per_contract UNIQUE(stake_addr, fingerprint, contract_id,user_id); -ALTER TABLE claimed ADD CONSTRAINT unique_txhash UNIQUE(txhash,fingerprint); -ALTER TABLE token_whitelist ADD CONSTRAINT unique_token_per_contract_and_user UNIQUE(user_id,contract_id,policy_id,fingerprint); + CREATE OR REPLACE FUNCTION trigger_set_timestamp() + RETURNS TRIGGER AS $$ + BEGIN + NEW.updated_at = NOW(); + RETURN NEW; + END; + $$ LANGUAGE plpgsql; + + CREATE TYPE public.Calculationmode AS ENUM ( + 'custom', + 'modifactorandequation', + 'simpleequation', + 'fixedendepoch', + 'relationaltoadastake', + 'airdrop' + ); + + CREATE DOMAIN public.amount AS numeric(20,0) + CONSTRAINT amount_check CHECK (((VALUE >= (0)::numeric) AND (VALUE <= '18446744073709551615'::numeric))); + + + CREATE TABLE rewards ( + id BIGSERIAL PRIMARY KEY, + stake_addr VARCHAR(100) NOT NULL, + payment_addr VARCHAR(200) NOT NULL, + fingerprint VARCHAR(100) NOT NULL, + contract_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + tot_earned amount NOT NULL, + tot_claimed amount NOT NULL, + oneshot BOOLEAN NOT NULL, + last_calc_epoch BIGINT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); + + CREATE TABLE claimed ( + id BIGSERIAL PRIMARY KEY, + stake_addr VARCHAR(100) NOT NULL, + payment_addr VARCHAR(140) NOT NULL, + fingerprint VARCHAR(100) NOT NULL, + amount amount NOT NULL, + contract_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + txhash VARCHAR(120) NOT NULL, + invalid BOOLEAN, + invalid_descr TEXT, + timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); + + + CREATE TABLE token_whitelist ( + id BIGSERIAL PRIMARY KEY, + fingerprint VARCHAR(100), + policy_id VARCHAR(100) NOT NULL, + tokenname VARCHAR(140), + contract_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + vesting_period TIMESTAMPTZ NOT NULL DEFAULT NOW(), -- All new entries are valid on creation, vesting has to be set explicitly + pools TEXT[] NOT NULL, + mode Calculationmode NOT NULL, + equation TEXT NOT NULL, + start_epoch BIGINT NOT NULL, + end_epoch BIGINT, + modificator_equ TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); + + ALTER TYPE public.Calculationmode ADD VALUE IF NOT EXISTS 'custom' BEFORE 'fixedamountperepoch'; + + CREATE TABLE airdrop_whitelist ( + id BIGSERIAL PRIMARY KEY, + contract_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + reward_created BOOLEAN NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); + + + CREATE TABLE airdrop_parameter ( + id BIGSERIAL PRIMARY KEY, + contract_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + airdrop_type_type VARCHAR(3) NOT NULL, + distribution_type VARCHAR(100) NOT NULL, + selection_type TEXT NOT NULL, + args_1 TEXT[] NOT NULL, + args_2 TEXT[] NOT NULL, + args_3 TEXT[] NOT NULL, + whitelist_ids BIGINT[], + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); + + CREATE TRIGGER set_timestamp + BEFORE UPDATE ON airdrop_whitelist + FOR EACH ROW + EXECUTE PROCEDURE trigger_set_timestamp(); + + CREATE TRIGGER set_timestamp + BEFORE UPDATE ON airdrop_parameter + FOR EACH ROW + EXECUTE PROCEDURE trigger_set_timestamp(); + + CREATE TYPE public.whitelisttype AS ENUM ( + 'RandomContained', + 'SpecificAsset', + 'RandomPreallocated' + ); + + CREATE TABLE wladdresses ( + id BIGSERIAL PRIMARY KEY, + payment_address VARCHAR NOT NULL UNIQUE, + stake_address VARCHAR + ); + + CREATE TABLE wlalloc ( + wl BIGINT NOT NULL, + addr BIGINT NOT NULL, + specific_asset Jsonb, + PRIMARY KEY(wl,addr,specific_asset) + ); + ALTER TABLE wlalloc ADD CONSTRAINT unique_token_per_whitelist UNIQUE(wl, specific_asset); + + CREATE TABLE whitelist ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT NOT NULL, + max_addr_repeat INTEGER NOT NULL, + wl_type whitelisttype NOT NULL, + description VARCHAR NOT NULL, + notes VARCHAR NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); + + CREATE TRIGGER set_timestamp + BEFORE UPDATE ON whitelist + FOR EACH ROW + EXECUTE PROCEDURE trigger_set_timestamp(); + + CREATE TABLE mint_projects ( + id BIGSERIAL PRIMARY KEY, + project_name VARCHAR NOT NULL, + user_id BIGINT NOT NULL, + mint_contract_id BIGINT NOT NULL, + whitelists BIGINT[], + mint_start_date TIMESTAMPTZ NOT NULL, + mint_end_date TIMESTAMPTZ, + storage_type Varchar NOT NULL, + storage_url Varchar, + storage_access_token Varchar, + collection_name VARCHAR NOT NULL, + author VARCHAR(64) NOT NULL, + meta_description VARCHAR(64) NOT NULL, + meta_common_nft_name VARCHAR(64), + max_mint_p_addr INTEGER, + nft_table_name VARCHAR(64) NOT NULL UNIQUE, + active BOOLEAN NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (user_id,mint_contract_id), + UNIQUE (user_id,collection_name) + ); + + CREATE TRIGGER set_timestamp + BEFORE UPDATE ON mint_projects + FOR EACH ROW + EXECUTE PROCEDURE trigger_set_timestamp(); + + CREATE TABLE nft_table ( + project_id BIGINT NOT NULL, + asset_name_b BYTEA NOT NULL, + asset_name VARCHAR NOT NULL, + fingerprint VARCHAR NOT NULL, + nft_id VARCHAR NOT NULL, + file_name VARCHAR NOT NULL, + ipfs_hash VARCHAR, + metadata TEXT NOT NULL, + claim_addr VARCHAR, + minted BOOLEAN NOT NULL, + tx_hash VARCHAR, + confirmed BOOLEAN, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY(project_id,asset_name_b) + ); + + CREATE TRIGGER set_timestamp + BEFORE UPDATE ON nft_table + FOR EACH ROW + EXECUTE PROCEDURE trigger_set_timestamp(); + + CREATE INDEX nft_project ON nft_table (project_id); + CREATE EXTENSION tsm_system_rows; + + CREATE TABLE discount ( + id BIGSERIAL PRIMARY KEY, + contract_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + policy_id VARCHAR NOT NULL, + fingerprint VARCHAR, + metadata_path VARCHAR[] NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (user_id,contract_id,policy_id) + ); + + CREATE TRIGGER set_timestamp + BEFORE UPDATE ON discount + FOR EACH ROW + EXECUTE PROCEDURE trigger_set_timestamp(); + + CREATE TABLE mint_rewards ( + id BIGSERIAL PRIMARY KEY, + project_id BIGINT NOT NULL, + pay_addr VARCHAR NOT NULL, + nft_ids Bytea[] NOT NULL, + v_nfts_b Bytea[] NOT NULL, + processed BOOLEAN NOT NULL, + minted BOOLEAN NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (project_id,nft_ids) + ); + + CREATE TRIGGER set_timestamp + BEFORE UPDATE ON mint_rewards + FOR EACH ROW + EXECUTE PROCEDURE trigger_set_timestamp(); + + + CREATE TRIGGER set_timestamp + BEFORE UPDATE ON rewards + FOR EACH ROW + EXECUTE PROCEDURE trigger_set_timestamp(); + + CREATE TRIGGER set_timestamp + BEFORE UPDATE ON claimed + FOR EACH ROW + EXECUTE PROCEDURE trigger_set_timestamp(); + + CREATE TRIGGER set_timestamp + BEFORE UPDATE ON token_whitelist + FOR EACH ROW + EXECUTE PROCEDURE trigger_set_timestamp(); + + ALTER TABLE rewards ADD CONSTRAINT unique_stake_per_contract UNIQUE(stake_addr, fingerprint, contract_id,user_id); + ALTER TABLE claimed ADD CONSTRAINT unique_txhash UNIQUE(txhash,fingerprint); + ALTER TABLE token_whitelist ADD CONSTRAINT unique_token_per_contract_and_user UNIQUE(user_id,contract_id,policy_id,fingerprint); + + ALTER TYPE public."calculationmode" RENAME TO "Calculationmode"; diff --git a/drasil-gungnir/src/bin/create_token_whitelisting.rs b/drasil-gungnir/src/bin/create_token_whitelisting.rs deleted file mode 100644 index aa72cd6d..00000000 --- a/drasil-gungnir/src/bin/create_token_whitelisting.rs +++ /dev/null @@ -1,94 +0,0 @@ -use chrono::{NaiveDateTime, Utc}; -#[cfg(feature = "mimir_bin")] -use drasil_mimir::*; -use gungnir::*; -use std::str::FromStr; -#[cfg(feature = "mimir_bin")] -use structopt::StructOpt; - -#[derive(Debug, StructOpt)] -#[structopt( - name = "rwd create token whitelisting", - about = "Creates a Whitelisting for a token in a contract" -)] -struct Opt { - #[structopt(short, long, about = "user id as integer")] - user: i32, - - #[structopt(short, long, about = "contract id as integer")] - contract_id: i32, - - #[structopt(short, long, about = "policy id as String")] - policy_id: String, - - #[structopt(short, long, about = "tokenname as String")] - tokenname: String, - - #[structopt(short, long, about = "fingerprint as String")] - fingerprint: Option, - - #[structopt(short, long, about = "Date until rewards are blocked")] - vesting_period: Option, - - #[structopt(short = "l", long, about = "pools array of Strings")] - pools: Vec, - - #[structopt( - short, - long, - about = "[custom, modifactorandequation, simpleequation, fixedendepoch, relationaltoadastake]" - )] - mode: String, - - #[structopt(short = "q", long, about = "Variable or equation, depends on mode")] - equation: String, - - #[structopt(short, long, about = "start epoch as integer")] - start_epoch: i64, - - #[structopt(short, long, about = "end epoch as integer")] - end_epoch: Option, - - #[structopt(short = "i", long, about = "modificator depends on mode")] - modificator: Option, -} - -fn main() -> Result<(), RWDError> { - let opt = Opt::from_args(); - - let mconn = mimir::establish_connection()?; - let fingerprint = mimir::get_fingerprint(&mconn, &opt.policy_id, &opt.tokenname)?; - let tn = hex::encode(opt.tokenname.as_bytes()); - - println!("PolicyId: {:?}", opt.policy_id); - println!("TokenName: {:?}", tn); - println!("Fingerprint: {:?}", fingerprint); - - println!("Pools: {:?}", opt.pools); - - let mut vd = chrono::Utc::now(); - if let Some(date) = opt.vesting_period { - vd = chrono::DateTime::::from_utc( - NaiveDateTime::parse_from_str(&date, "%Y-%m-%d %H:%M:%S")?, - Utc, - ); - } - - gungnir::TokenWhitelist::create_twl_entry( - &mut gungnir::establish_connection()?, - &fingerprint, - &opt.policy_id, - &tn, - &(opt.contract_id as i64), - &(opt.user as i64), - &vd, - &opt.pools, - &gungnir::Calculationmode::from_str(&opt.mode)?, - &opt.equation, - &opt.start_epoch, - opt.end_epoch.as_ref(), - opt.modificator.as_ref(), - )?; - - Ok(()) -} diff --git a/drasil-hugin/Cargo.toml b/drasil-hugin/Cargo.toml index 8ce19a1b..b58aa983 100644 --- a/drasil-hugin/Cargo.toml +++ b/drasil-hugin/Cargo.toml @@ -5,8 +5,8 @@ edition = "2021" description = "Drasil Blockchain Application Framework - Drasil System Library" repository = "https://github.com/Sbcdn/drasil.git" documentation = "https://docs.drasil.io" -license = "LICENSE_GPL.md" -readme = "README.md" +license = "https://github.com/Sbcdn/drasil/blob/main/LICENSE.md" +readme = "https://github.com/Sbcdn/drasil/blob/main/README.md" authors = ["Torben Poguntke "] [dependencies] diff --git a/drasil-hugin/migrations/000001_init/up.sql b/drasil-hugin/migrations/000001_init/up.sql index f9f5acb3..fe98ffa0 100644 --- a/drasil-hugin/migrations/000001_init/up.sql +++ b/drasil-hugin/migrations/000001_init/up.sql @@ -1,128 +1,128 @@ -CREATE OR REPLACE FUNCTION trigger_set_timestamp() -RETURNS TRIGGER AS $$ -BEGIN - NEW.updated_at = NOW(); - RETURN NEW; -END; -$$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION trigger_set_timestamp() + RETURNS TRIGGER AS $$ + BEGIN + NEW.updated_at = NOW(); + RETURN NEW; + END; + $$ LANGUAGE plpgsql; -CREATE TABLE contracts ( - id BIGSERIAL PRIMARY KEY, - user_id BIGINT NOT NULL, - contract_id bigint NOT NULL, - contract_type VARCHAR(20) NOT NULL, - description VARCHAR(100), - version REAL NOT NULL, - plutus TEXT NOT NULL, - address VARCHAR(80) NOT NULL, - policy_id VARCHAR(120), - depricated BOOLEAN NOT NULL DEFAULT false, - drasil_lqdty BIGINT, - customer_lqdty BIGINT, - external_lqdty BIGINT, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); + CREATE TABLE contracts ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT NOT NULL, + contract_id bigint NOT NULL, + contract_type VARCHAR(20) NOT NULL, + description VARCHAR(100), + version REAL NOT NULL, + plutus TEXT NOT NULL, + address VARCHAR(80) NOT NULL, + policy_id VARCHAR(120), + depricated BOOLEAN NOT NULL DEFAULT false, + drasil_lqdty BIGINT, + customer_lqdty BIGINT, + external_lqdty BIGINT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); -CREATE TABLE drasil_user ( - id BIGSERIAL PRIMARY KEY, - user_id BIGINT NOT NULL, - api_pubkey VARCHAR(250), - uname VARCHAR(24) NOT NULL, - email VARCHAR(150) NOT NULL, - pwd TEXT NOT NULL, - role VARCHAR(20) NOT NULL, - permissions TEXT[] NOT NULL, - company_name VARCHAR(32), - address VARCHAR(128), - post_code VARCHAR(12), - city VARCHAR(100), - addional_addr VARCHAR (128), - country VARCHAR(30), - contact_p_fname VARCHAR(50), - contact_p_sname VARCHAR(50), - contact_p_tname VARCHAR(50), - identification TEXT[] NOT NULL, - email_verified BOOLEAN NOT NULL, - cardano_wallet TEXT, - drslpubkey VARCHAR(150), - cwallet_verified BOOLEAN NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); + CREATE TABLE drasil_user ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT NOT NULL, + api_pubkey VARCHAR(250), + uname VARCHAR(24) NOT NULL, + email VARCHAR(150) NOT NULL, + pwd TEXT NOT NULL, + role VARCHAR(20) NOT NULL, + permissions TEXT[] NOT NULL, + company_name VARCHAR(32), + address VARCHAR(128), + post_code VARCHAR(12), + city VARCHAR(100), + addional_addr VARCHAR (128), + country VARCHAR(30), + contact_p_fname VARCHAR(50), + contact_p_sname VARCHAR(50), + contact_p_tname VARCHAR(50), + identification TEXT[] NOT NULL, + email_verified BOOLEAN NOT NULL, + cardano_wallet TEXT, + drslpubkey VARCHAR(150), + cwallet_verified BOOLEAN NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); -CREATE TABLE multisig_keyloc ( - id BIGSERIAL PRIMARY KEY, - user_id BIGINT NOT NULL, - contract_id bigint NOT NULL, - version REAL NOT NULL, - fee_wallet_addr VARCHAR(120), - fee bigint, - pvks TEXT[] NOT NULL, - depricated BOOLEAN NOT NULL DEFAULT false, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); + CREATE TABLE multisig_keyloc ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT NOT NULL, + contract_id bigint NOT NULL, + version REAL NOT NULL, + fee_wallet_addr VARCHAR(120), + fee bigint, + pvks TEXT[] NOT NULL, + depricated BOOLEAN NOT NULL DEFAULT false, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); -CREATE TABLE ca_payment ( - id BIGSERIAL PRIMARY KEY, - user_id BIGINT NOT NULL, - contract_id bigint NOT NULL, - value VARCHAR NOT NULL, - tx_hash VARCHAR(64), - user_appr VARCHAR, - drasil_appr VARCHAR, - status_bl VARCHAR, - status_pa VARCHAR NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); + CREATE TABLE ca_payment ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT NOT NULL, + contract_id bigint NOT NULL, + value VARCHAR NOT NULL, + tx_hash VARCHAR(64), + user_appr VARCHAR, + drasil_appr VARCHAR, + status_bl VARCHAR, + status_pa VARCHAR NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); -CREATE TABLE ca_payment_hash ( - id BIGSERIAL PRIMARY KEY, - payment_id BIGINT NOT NULL, - payment_hash VARCHAR NOT NULL UNIQUE, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); + CREATE TABLE ca_payment_hash ( + id BIGSERIAL PRIMARY KEY, + payment_id BIGINT NOT NULL, + payment_hash VARCHAR NOT NULL UNIQUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); -CREATE TABLE email_verification_token ( - id BYTEA PRIMARY KEY, - email TEXT UNIQUE NOT NULL, - expires_at TIMESTAMP NOT NULL, - created_at TIMESTAMP NOT NULL DEFAULT NOW() -); + CREATE TABLE email_verification_token ( + id BYTEA PRIMARY KEY, + email TEXT UNIQUE NOT NULL, + expires_at TIMESTAMP NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT NOW() + ); -CREATE TRIGGER set_timestamp -BEFORE UPDATE ON ca_payment -FOR EACH ROW -EXECUTE PROCEDURE trigger_set_timestamp(); + CREATE TRIGGER set_timestamp + BEFORE UPDATE ON ca_payment + FOR EACH ROW + EXECUTE PROCEDURE trigger_set_timestamp(); -CREATE TRIGGER set_timestamp -BEFORE UPDATE ON ca_payment_hash -FOR EACH ROW -EXECUTE PROCEDURE trigger_set_timestamp(); + CREATE TRIGGER set_timestamp + BEFORE UPDATE ON ca_payment_hash + FOR EACH ROW + EXECUTE PROCEDURE trigger_set_timestamp(); -CREATE TRIGGER set_timestamp -BEFORE UPDATE ON contracts -FOR EACH ROW -EXECUTE PROCEDURE trigger_set_timestamp(); + CREATE TRIGGER set_timestamp + BEFORE UPDATE ON contracts + FOR EACH ROW + EXECUTE PROCEDURE trigger_set_timestamp(); -CREATE TRIGGER set_timestamp -BEFORE UPDATE ON drasil_user -FOR EACH ROW -EXECUTE PROCEDURE trigger_set_timestamp(); + CREATE TRIGGER set_timestamp + BEFORE UPDATE ON drasil_user + FOR EACH ROW + EXECUTE PROCEDURE trigger_set_timestamp(); -CREATE TRIGGER set_timestamp -BEFORE UPDATE ON email_verification_token -FOR EACH ROW -EXECUTE PROCEDURE trigger_set_timestamp(); + CREATE TRIGGER set_timestamp + BEFORE UPDATE ON email_verification_token + FOR EACH ROW + EXECUTE PROCEDURE trigger_set_timestamp(); -ALTER TABLE contracts ADD CONSTRAINT unique_contract UNIQUE(user_id, contract_id, version); -ALTER TABLE contracts ADD CONSTRAINT unique_address UNIQUE(address); -ALTER TABLE drasil_user ADD CONSTRAINT unique_email UNIQUE(email); -ALTER TABLE drasil_user ADD CONSTRAINT unique_user_id UNIQUE(user_id); -ALTER TABLE drasil_user ADD CONSTRAINT unique_api_key UNIQUE(api_pubkey); -ALTER TABLE drasil_user ADD CONSTRAINT unique_passwords UNIQUE(pwd); -ALTER TABLE multisig_keyloc ADD CONSTRAINT unique_multisig_keyloc UNIQUE(user_id,contract_id,version); \ No newline at end of file + ALTER TABLE contracts ADD CONSTRAINT unique_contract UNIQUE(user_id, contract_id, version); + ALTER TABLE contracts ADD CONSTRAINT unique_address UNIQUE(address); + ALTER TABLE drasil_user ADD CONSTRAINT unique_email UNIQUE(email); + ALTER TABLE drasil_user ADD CONSTRAINT unique_user_id UNIQUE(user_id); + ALTER TABLE drasil_user ADD CONSTRAINT unique_api_key UNIQUE(api_pubkey); + ALTER TABLE drasil_user ADD CONSTRAINT unique_passwords UNIQUE(pwd); + ALTER TABLE multisig_keyloc ADD CONSTRAINT unique_multisig_keyloc UNIQUE(user_id,contract_id,version); \ No newline at end of file diff --git a/drasil-hugin/src/datamodel/models.rs b/drasil-hugin/src/datamodel/models.rs index 06e13d1d..b64d046e 100644 --- a/drasil-hugin/src/datamodel/models.rs +++ b/drasil-hugin/src/datamodel/models.rs @@ -201,7 +201,7 @@ pub enum TXPWrapper { #[derive(Serialize, Deserialize, Debug, Clone)] pub struct WalletTransactionPattern { user: Option, - contract_id: Option, // ToDO: Expect a Vector instead of a single contract; needs to be changed on front-end + contract_id: Option, wallet_type: Option, // yoroi, ccvault, gero, flint, ... // or yoroi, cip30, typhon #[serde(alias = "sending_wal_addrs")] used_addresses: Option>, @@ -240,7 +240,7 @@ impl WalletTransactionPattern { #[derive(Serialize, Deserialize, Debug, Clone)] pub struct TransactionPattern { user: Option, - contract_id: Option, // ToDO: Expect a Vector instead of a single contract; needs to be changed on front-end + contract_id: Option, wallet_type: Option, // yoroi, ccvault, gero, flint, ... // or yoroi, cip30, typhon #[serde(alias = "sending_wal_addrs")] used_addresses: Vec, @@ -284,7 +284,6 @@ impl TransactionPattern { } pub fn contract_id(&self) -> Option { - // ToDO: Expect a Vector instead of a single contract; needs to be changed on front-end self.contract_id } @@ -394,7 +393,7 @@ impl TransactionPattern { }; debug!("addresses: {:?}", addresses); let mut txd = TxData::new( - Some(vec![contract_id]), // ToDO: Expect a Vector instead of a single contract; needs to be changed on front-end + Some(vec![contract_id]), wallet::addresses_from_string(&addresses).await?, saddr, wallet::transaction_unspent_outputs_from_string_vec( @@ -423,7 +422,6 @@ impl TransactionPattern { } #[derive(Serialize, Deserialize, Debug, Clone, EnumIs)] -//#[serde(tag = "type")] pub enum Operation { SpoRewardClaim { rewards: Vec, @@ -1153,7 +1151,7 @@ mod tests { let delegation = op.into_stake_delegation().await.unwrap(); let real_poolkeyhash = Ed25519KeyHash::from_bech32(&poolhash).unwrap(); - let real_registered = false; // Placeholder value. Unit test can't test this. Needs integration test. + let real_registered = false; assert_eq!(delegation.get_poolhash(), poolhash); assert_eq!(delegation.get_poolkeyhash(), real_poolkeyhash); assert_eq!(delegation.get_registered(), real_registered); diff --git a/drasil-hugin/src/protocol/cmd/buildmultisig.rs b/drasil-hugin/src/protocol/cmd/buildmultisig.rs index 745060f0..02b9431e 100644 --- a/drasil-hugin/src/protocol/cmd/buildmultisig.rs +++ b/drasil-hugin/src/protocol/cmd/buildmultisig.rs @@ -41,12 +41,18 @@ impl BuildMultiSig { } pub(crate) fn parse_frames(parse: &mut Parse) -> crate::Result { - let customer_id = parse.next_int().map_err(|e| MurinError::ProtocolCommandError(e.to_string()))?; - let mtype = parse.next_bytes().map_err(|e| MurinError::ProtocolCommandError(e.to_string()))?; + let customer_id = parse + .next_int() + .map_err(|e| MurinError::ProtocolCommandError(e.to_string()))?; + let mtype = parse + .next_bytes() + .map_err(|e| MurinError::ProtocolCommandError(e.to_string()))?; let mtype: MultiSigType = bc::DefaultOptions::new() .with_varint_encoding() .deserialize(&mtype)?; - let txpattern = parse.next_bytes().map_err(|e| MurinError::ProtocolCommandError(e.to_string()))?; + let txpattern = parse + .next_bytes() + .map_err(|e| MurinError::ProtocolCommandError(e.to_string()))?; let txpattern: TransactionPattern = bc::DefaultOptions::new() .with_varint_encoding() .deserialize(&txpattern)?; @@ -100,12 +106,6 @@ impl BuildMultiSig { Err(e) => e.to_string(), }; } - /* MultiSigType::TestRewards => { - ret = match multisig::handle_testrewards(&self).await { - Ok(s) => s, - Err(e) => e.to_string(), - }; - } */ MultiSigType::CustomerPayout => { ret = match multisig::handle_customer_payout(&self).await { Ok(s) => s, diff --git a/drasil-hugin/src/protocol/cmd/finalizemultisig.rs b/drasil-hugin/src/protocol/cmd/finalizemultisig.rs index 90518d29..4b75b16a 100644 --- a/drasil-hugin/src/protocol/cmd/finalizemultisig.rs +++ b/drasil-hugin/src/protocol/cmd/finalizemultisig.rs @@ -184,7 +184,6 @@ impl FinalizeMultiSig { ret = self.finalize_rwd(raw_tx.clone()).await?; - //Todo: processed must happen before finalize rwd for h in &handles { MintReward::process_mintreward(h.1.id, h.1.project_id, &h.1.pay_addr) .map_err(|e| MurinError::ProtocolCommandError(e.to_string()))?; diff --git a/drasil-hugin/src/protocol/multisig/moneshot_handler.rs b/drasil-hugin/src/protocol/multisig/moneshot_handler.rs index da57656b..410c33eb 100644 --- a/drasil-hugin/src/protocol/multisig/moneshot_handler.rs +++ b/drasil-hugin/src/protocol/multisig/moneshot_handler.rs @@ -32,7 +32,11 @@ pub(crate) async fn handle_onehshot_mint(bms: &BuildMultiSig) -> crate::Result s, Err(e) => { - return Err(format!("ERROR could not determine current slot: '{:?}'",e.to_string()).into()); + return Err(format!( + "ERROR could not determine current slot: '{:?}'", + e.to_string() + ) + .into()); } }; gtxd.set_current_slot(slot as u64); @@ -43,13 +47,15 @@ pub(crate) async fn handle_onehshot_mint(bms: &BuildMultiSig) -> crate::Result crate::Result5kB (cal_min_ada panics on utxos >5kB) - // - Find a solution for protocal parameters (maybe to database?) at the moment they are hardcoded in list / build_rwd - log::debug!("Set utxos for input..."); - gtxd.set_inputs(drasil_mimir::get_address_utxos(&contract.address).map_err(|e| MurinError::ProtocolCommandError(e.to_string()))?); + gtxd.set_inputs( + drasil_mimir::get_address_utxos(&contract.address) + .map_err(|e| MurinError::ProtocolCommandError(e.to_string()))?, + ); log::debug!("Try to build transactions..."); let txb_param: drasil_murin::txbuilder::minter::build_oneshot_mint::AtOSMParams = ( diff --git a/drasil-hugin/src/protocol/multisig/reward_handler.rs b/drasil-hugin/src/protocol/multisig/reward_handler.rs index c8bf6a5a..5e7b50fa 100644 --- a/drasil-hugin/src/protocol/multisig/reward_handler.rs +++ b/drasil-hugin/src/protocol/multisig/reward_handler.rs @@ -3,8 +3,7 @@ use crate::protocol::{create_response, determine_contracts}; use crate::{discount, CmdError}; use crate::{BuildMultiSig, TBMultiSigLoc}; use drasil_murin::modules::transfer::models::*; -use drasil_murin::{wallet, PerformTxb, MurinError}; -//use drasil_gungnir::schema::whitelist; +use drasil_murin::{wallet, MurinError, PerformTxb}; pub(crate) async fn handle_rewardclaim(bms: &BuildMultiSig) -> crate::Result { info!("verify transaction data..."); @@ -19,9 +18,10 @@ pub(crate) async fn handle_rewardclaim(bms: &BuildMultiSig) -> crate::Result { let err = Err(format!( - "ERROR wrong data provided for script specific parameters: '{:?}'", - bms.transaction_pattern().operation() - ).into()); + "ERROR wrong data provided for script specific parameters: '{:?}'", + bms.transaction_pattern().operation() + ) + .into()); if rewards.is_empty() || wallet::address_from_string(&recipient_stake_addr) .await @@ -38,7 +38,8 @@ pub(crate) async fn handle_rewardclaim(bms: &BuildMultiSig) -> crate::Result crate::Result { - return Err(format!("ERROR wrong data provided for '{:?}'", bms.multisig_type()).into()); + return Err( + format!("ERROR wrong data provided for '{:?}'", bms.multisig_type()).into(), + ); } } @@ -59,19 +62,23 @@ pub(crate) async fn handle_rewardclaim(bms: &BuildMultiSig) -> crate::Result::new(); @@ -81,9 +88,10 @@ pub(crate) async fn handle_rewardclaim(bms: &BuildMultiSig) -> crate::Result crate::Result crate::Result crate::Result::new(); for c in &contract { - keylocs.push(crate::drasildb::TBMultiSigLoc::get_multisig_keyloc( - &c.contract_id, - &c.user_id, - &c.version, - ).map_err(|e| MurinError::ProtocolCommandError(e.to_string()))?); + keylocs.push( + crate::drasildb::TBMultiSigLoc::get_multisig_keyloc( + &c.contract_id, + &c.user_id, + &c.version, + ) + .map_err(|e| MurinError::ProtocolCommandError(e.to_string()))?, + ); } let mut fees = keylocs.iter().fold( @@ -190,20 +205,27 @@ pub(crate) async fn handle_rewardclaim(bms: &BuildMultiSig) -> crate::Result crate::Result(|_| CmdError::Custom { - str: "could not convert string to native script".to_string(), - }).map_err(|e| MurinError::ProtocolCommandError(e.to_string()))?; + str: "could not convert string to native script".to_string(), + }) + .map_err(|e| MurinError::ProtocolCommandError(e.to_string()))?; let mut w = TransWallet::new(&tw_addr, &wallet_utxos); let s = CardanoNativeScript::new(&tw_addr, &tw_script, c.version, vec![pkvs[0].clone()]); w.set_native_script(s); @@ -225,23 +248,10 @@ pub(crate) async fn handle_rewardclaim(bms: &BuildMultiSig) -> crate::Result5kB (cal_min_ada panics on utxos >5kB) - // - Find a solution for protocal parameters (maybe to database?) at the moment they are hardcoded in list / build_rwd - /* - let ident = crate::encryption::mident( - &contract[0].user_id, - &contract[0].contract_id, - &contract[0].version, - &ns_addr, - ); - let pkvs = crate::encryption::decrypt_pkvs(keylocs[0].pvks.clone(), &ident).await?; - */ info!("build transaction..."); let txb_param: drasil_murin::txbuilder::rwdist::AtRWDParams = (&rwdtxd, Some(wallets)); let rwd = drasil_murin::txbuilder::rwdist::AtRWDBuilder::new(txb_param); diff --git a/drasil-hugin/src/protocol/multisig/testrwd_handler.rs b/drasil-hugin/src/protocol/multisig/testrwd_handler.rs index 3bf41766..59a13a1f 100644 --- a/drasil-hugin/src/protocol/multisig/testrwd_handler.rs +++ b/drasil-hugin/src/protocol/multisig/testrwd_handler.rs @@ -139,9 +139,7 @@ pub(crate) async fn handle_testrewards(bms: &BuildMultiSig) -> crate::Result5kB (cal_min_ada panics on utxos >5kB) - // - Find a solution for protocal parameters (maybe to database?) at the moment they are hardcoded in list / build_rwd + let policy_script_utxos = mimir::get_address_utxos(&mut dbsync, &contract.address)?; gtxd.set_inputs(policy_script_utxos); diff --git a/drasil-hugin/src/protocol/stdtx/delegation_handler.rs b/drasil-hugin/src/protocol/stdtx/delegation_handler.rs index f626853b..c1e10a4a 100644 --- a/drasil-hugin/src/protocol/stdtx/delegation_handler.rs +++ b/drasil-hugin/src/protocol/stdtx/delegation_handler.rs @@ -1,9 +1,9 @@ use crate::datamodel::Operation; use crate::protocol::create_response; use crate::BuildStdTx; -use drasil_murin::MurinError; use drasil_murin::clib; use drasil_murin::wallet; +use drasil_murin::MurinError; use drasil_murin::PerformTxb; use drasil_murin::TransactionUnspentOutputs; @@ -15,7 +15,9 @@ pub(crate) async fn handle_stake_delegation(bst: &BuildStdTx) -> crate::Result (), _ => { - return Err(format!("ERROR wrong input data provided for '{:?}'", bst.tx_type()).into()); + return Err( + format!("ERROR wrong input data provided for '{:?}'", bst.tx_type()).into(), + ); } } let op = &bst.transaction_pattern().operation().unwrap(); @@ -31,8 +33,7 @@ pub(crate) async fn handle_stake_delegation(bst: &BuildStdTx) -> crate::Result::new(), |mut acc, a| { acc.push(wallet::address_from_string_non_async(a).unwrap()); acc @@ -41,9 +42,7 @@ pub(crate) async fn handle_stake_delegation(bst: &BuildStdTx) -> crate::Result::new(), |mut acc, n| { - acc.push( - n.to_bech32(None).unwrap() - ); + acc.push(n.to_bech32(None).unwrap()); acc }); debug!("stake delegation addresses: {:?}", addresses); @@ -60,16 +59,11 @@ pub(crate) async fn handle_stake_delegation(bst: &BuildStdTx) -> crate::Result crate::Result crate::Result crate::Result Result<(), Box> { @@ -142,7 +138,10 @@ mod tests { let poolhash = "pool1pt39c4va0aljcgn4jqru0jhtws9q5wj8u0xnajtkgk9g7lxlk2t".to_string(); let addr1 = "addr_test1qp8cprhse9pnnv7f4l3n6pj0afq2hjm6f7r2205dz0583egaeu9dhacmtx94652q4ym0v9v2mcra0n28d5lrtjqzsgxqgk5t8s".to_string(); let addresses = Some(vec![addr1]); - let script_spec = Operation::StakeDelegation { poolhash, addresses }; + let script_spec = Operation::StakeDelegation { + poolhash, + addresses, + }; let network = 0; let txpattern = TransactionPattern::new_empty(customer_id, &script_spec, network); let bst = BuildStdTx::new(customer_id, txtype, txpattern); @@ -150,10 +149,13 @@ mod tests { let real_value = "310737567dbedda0d4e9780861bad5ade7bd00fb14032302b1b7bd9c|84a50081825820395eab6c60ec00faeff30391c683551119669b0aeb8c778948afbe83299b29b1010181825839004f808ef0c94339b3c9afe33d064fea40abcb7a4f86a53e8d13e878e51dcf0adbf71b598b5d5140a936f6158ade07d7cd476d3e35c802820c1b000000e8d4a26cfb021a0002a305031a01905d4b048183028200581c1dcf0adbf71b598b5d5140a936f6158ade07d7cd476d3e35c802820c581c0ae25c559d7f7f2c22759007c7caeb740a0a3a47e3cd3ec976458a8fa0f5f6".to_string(); log::info!("handle_stake_delegation real value example: {}", "310737567dbedda0d4e9780861bad5ade7bd00fb14032302b1b7bd9c|84a50081825820395eab6c60ec00faeff30391c683551119669b0aeb8c778948afbe83299b29b1010181825839004f808ef0c94339b3c9afe33d064fea40abcb7a4f86a53e8d13e878e51dcf0adbf71b598b5d5140a936f6158ade07d7cd476d3e35c802820c1b000000e8d4a26cfb021a0002a305031a01905d4b048183028200581c1dcf0adbf71b598b5d5140a936f6158ade07d7cd476d3e35c802820c581c0ae25c559d7f7f2c22759007c7caeb740a0a3a47e3cd3ec976458a8fa0f5f6"); - log::info!("handle_stake_delegation func value (changes with time): {}", func_value); + log::info!( + "handle_stake_delegation func value (changes with time): {}", + func_value + ); assert_eq!(func_value.len(), real_value.len()); Ok(()) } -} \ No newline at end of file +} diff --git a/drasil-hugin/src/protocol/stdtx/deregistration_handler.rs b/drasil-hugin/src/protocol/stdtx/deregistration_handler.rs index 95ce4021..4cd0516c 100644 --- a/drasil-hugin/src/protocol/stdtx/deregistration_handler.rs +++ b/drasil-hugin/src/protocol/stdtx/deregistration_handler.rs @@ -1,9 +1,9 @@ use crate::datamodel::Operation; use crate::protocol::create_response; use crate::BuildStdTx; -use drasil_murin::MurinError; use drasil_murin::clib; use drasil_murin::wallet::address_from_string_non_async; +use drasil_murin::MurinError; use drasil_murin::PerformTxb; use drasil_murin::TransactionUnspentOutputs; @@ -15,7 +15,9 @@ pub(crate) async fn handle_stake_deregistration(bst: &BuildStdTx) -> crate::Resu { Operation::StakeDeregistration { .. } => (), _ => { - return Err(format!("ERROR wrong input data provided for '{:?}'", bst.tx_type()).into()); + return Err( + format!("ERROR wrong input data provided for '{:?}'", bst.tx_type()).into(), + ); } } let op = &bst.transaction_pattern().operation().unwrap(); @@ -64,7 +66,6 @@ pub(crate) async fn handle_stake_deregistration(bst: &BuildStdTx) -> crate::Resu }); gtxd.set_inputs(wallet_utxos); - // ToDo: go through all addresses and check all stake keys are equal let sa = drasil_murin::wallet::reward_address_from_address(&wal_addr[0])?; gtxd.set_stake_address(sa); gtxd.set_senders_addresses(wal_addr.clone()); @@ -77,7 +78,8 @@ pub(crate) async fn handle_stake_deregistration(bst: &BuildStdTx) -> crate::Resu return Err(format!("ERROR could not connect to dbsync: '{:?}'", e.to_string()).into()); } }; - let current_slot = drasil_mimir::get_slot(&mut dbsync).map_err(|e| MurinError::ProtocolCommandError(e.to_string()))?; + let current_slot = drasil_mimir::get_slot(&mut dbsync) + .map_err(|e| MurinError::ProtocolCommandError(e.to_string()))?; gtxd.set_current_slot(current_slot as u64); deregtxd.set_registered(Some(false)); // the whole point @@ -142,9 +144,5 @@ mod test { println!("handle_stake_deregistration func value (changes with time): {func_value}\n"); assert_eq!(func_value.len(), real_value.len()); - - // No need to test if deregistration succeeded in this unit test because handle_stake_deregistration - // only returns UnsignedTransaction. It first needs to be signed in a later stage before - // the deregistration kicks in. } } diff --git a/drasil-hugin/src/protocol/stdtx/standard_tx.rs b/drasil-hugin/src/protocol/stdtx/standard_tx.rs index 3f2b09c5..8fd74668 100644 --- a/drasil-hugin/src/protocol/stdtx/standard_tx.rs +++ b/drasil-hugin/src/protocol/stdtx/standard_tx.rs @@ -83,7 +83,6 @@ pub(crate) async fn handle_stx(bss: &BuildStdTx) -> Result { ); gtxd.set_inputs(wallet_utxos); - // ToDo: go through all addresses and check all stake keys are equal let sa = wallet::reward_address_from_address(&std_asset_txd.wallet_addresses[0])?; gtxd.set_stake_address(sa); gtxd.set_senders_addresses(std_asset_txd.wallet_addresses.clone()); @@ -122,17 +121,9 @@ pub(crate) async fn handle_stx(bss: &BuildStdTx) -> Result { })?; let first_addr = Address::from_bech32(&first_address_str)?; - // ToDo: - // - Add Wallets - - // If addresses are provided check they all belong to the same wallet, if yes - // get utxos for the addresses and build TransWallet with that UTxOs - let uw = TransWallet::new(&first_addr, >xd.get_inputs()); wallets.add_wallet(&uw); - // - Add Endpoint to get AssetHandles From AddressSet - let txb_param: AtSATParams = (&std_asset_txd, &wallets, &first_addr); let asset_transfer = AtSATBuilder::new(txb_param); let builder = drasil_murin::TxBuilder::new(>xd, &vec![]); diff --git a/drasil-hugin/src/protocol/stdtx/withdrawal_handler.rs b/drasil-hugin/src/protocol/stdtx/withdrawal_handler.rs index 8fc37b93..45464228 100644 --- a/drasil-hugin/src/protocol/stdtx/withdrawal_handler.rs +++ b/drasil-hugin/src/protocol/stdtx/withdrawal_handler.rs @@ -1,7 +1,6 @@ -use drasil_murin::{RawTx, PerformTxb, MurinError}; +use drasil_murin::{MurinError, PerformTxb, RawTx}; - -use crate::{create_response, BuildStdTx, Operation, CmdError}; +use crate::{create_response, BuildStdTx, CmdError, Operation}; pub(crate) async fn handle_reward_withdrawal(bst: &BuildStdTx) -> crate::Result { let op = bst @@ -10,52 +9,44 @@ pub(crate) async fn handle_reward_withdrawal(bst: &BuildStdTx) -> crate::Result< .filter(|op| op.is_reward_withdrawal()) .ok_or("ERROR: No transaction specific data supplied for Ada withdrawal")?; - let mut gtxd = bst - .transaction_pattern() - .clone() - .into_txdata() - .await?; + let mut gtxd = bst.transaction_pattern().clone().into_txdata().await?; gtxd.set_user_id(bst.customer_id()); - /* - // it is wrong to use gtxd use the specific transaction parameters instead - gtxd.set_withdrawal( - BigNum::from_str( - &api::withdrawable_rewards( - >xd.get_stake_address().to_bech32(None)? - ).await?.to_string() - )? + + gtxd.set_current_slot( + drasil_mimir::get_slot( + &mut drasil_mimir::establish_connection() + .map_err(|e| CmdError::Custom { + str: format!("ERROR could not connect to dbsync: '{:?}'", e.to_string()), + }) + .map_err(|e| MurinError::ProtocolCommandError(e.to_string()))?, + ) + .map_err(|e| MurinError::ProtocolCommandError(e.to_string()))? as u64, ); - */ - gtxd.set_current_slot(drasil_mimir::get_slot( - &mut drasil_mimir::establish_connection().map_err(|e| - CmdError::Custom {str: format!("ERROR could not connect to dbsync: '{:?}'", e.to_string())} - ).map_err(|e| MurinError::ProtocolCommandError(e.to_string()))? - ).map_err(|e| MurinError::ProtocolCommandError(e.to_string()))? as u64); let tx_data = &drasil_murin::TxBuilder::new(>xd, &Vec::::new()); - let app_type = &drasil_murin::txbuilder::stdtx::AtAWBuilder::new( - &match op { - Operation::RewardWithdrawal{ withdrawal_amount: _ } => op.into_withdrawal().await?, - _ => { - return Err(format!("ERROR wrong input data provided for '{:?}'", bst.tx_type()).into()) - } + let app_type = &drasil_murin::txbuilder::stdtx::AtAWBuilder::new(&match op { + Operation::RewardWithdrawal { + withdrawal_amount: _, + } => op.into_withdrawal().await?, + _ => { + return Err(format!("ERROR wrong input data provided for '{:?}'", bst.tx_type()).into()) } - ); + }); let bld_tx = tx_data.build(app_type).await?; let raw_tx = &RawTx::new( - &bld_tx.get_tx_body(), - &bld_tx.get_txwitness(), - &bld_tx.get_tx_unsigned(), - &bld_tx.get_metadata(), - >xd.to_string(), - &"".to_string(), - &bld_tx.get_used_utxos(), - &hex::encode(gtxd.get_stake_address().to_bytes()), - &bst.customer_id(), - &[-1] + &bld_tx.get_tx_body(), + &bld_tx.get_txwitness(), + &bld_tx.get_tx_unsigned(), + &bld_tx.get_metadata(), + >xd.to_string(), + &"".to_string(), + &bld_tx.get_used_utxos(), + &hex::encode(gtxd.get_stake_address().to_bytes()), + &bst.customer_id(), + &[-1], ); let response = create_response( @@ -66,4 +57,4 @@ pub(crate) async fn handle_reward_withdrawal(bst: &BuildStdTx) -> crate::Result< .to_string(); Ok(response) -} \ No newline at end of file +} diff --git a/drasil-mimir/Cargo.toml b/drasil-mimir/Cargo.toml index d6690a74..9fdc111a 100644 --- a/drasil-mimir/Cargo.toml +++ b/drasil-mimir/Cargo.toml @@ -5,8 +5,8 @@ edition = "2021" description = "Drasil Blockchain Application Framework - DBsync library" repository = "https://github.com/Sbcdn/drasil.git" documentation = "https://docs.drasil.io" -license = "LICENSE_GPL.md" -readme = "README.md" +license = "https://github.com/Sbcdn/drasil/blob/main/LICENSE.md" +readme = "https://github.com/Sbcdn/drasil/blob/main/README.md" authors = ["Torben Poguntke "] [dependencies] diff --git a/drasil-mimir/src/api.rs b/drasil-mimir/src/api.rs index 2fe25d47..edd3de17 100644 --- a/drasil-mimir/src/api.rs +++ b/drasil-mimir/src/api.rs @@ -25,6 +25,7 @@ pub fn get_utxo_tokens( Ok(multi_assets) } +/// Select the first seen Base Address of a stake address pub fn select_addr_of_first_transaction(stake_address_in: &str) -> Result { log::debug!( "Try to find first address used by this stake address: {}", @@ -108,6 +109,7 @@ pub fn get_asset_utxos_on_addr( Ok(utxos) } +/// Get the current slot number pub fn get_slot(conn: &mut PgConnection) -> Result { let slot = block::table .filter(block::block_no.is_not_null()) @@ -123,6 +125,7 @@ pub fn get_slot(conn: &mut PgConnection) -> Result { } } +/// get total ada staked in an epoch for a stakepool pub fn get_tot_stake_per_pool( conn: &mut PgConnection, pool: &String, @@ -138,6 +141,7 @@ pub fn get_tot_stake_per_pool( Ok(pool_stake) } +/// Retrieve delegations for a stakepool pub fn get_delegations_per_pool_for_epochs( conn: &mut PgConnection, pool: &String, @@ -161,6 +165,7 @@ pub fn get_delegations_per_pool_for_epochs( Ok(deleg) } +/// get total ada staked for a given epoch pub fn get_pool_total_stake( conn: &mut PgConnection, pool: &String, @@ -178,6 +183,7 @@ pub fn get_pool_total_stake( Ok(tot_stake) } +/// get current epoch number pub fn get_epoch(conn: &mut PgConnection) -> Result { let epoch = epoch_stake::table .filter(epoch_stake::epoch_no.is_not_null()) @@ -188,6 +194,7 @@ pub fn get_epoch(conn: &mut PgConnection) -> Result { Ok(epoch) } +/// Get fingerprint from dbsync for a given token pub fn get_fingerprint( conn: &mut PgConnection, policy: &String, @@ -416,9 +423,8 @@ pub fn get_mint_metadata(fingerprint_in: &str) -> Result(&mut crate::establish_connection()?) .map_err(|_| MimirError::NotOnChainMetadataFound)?; - let tokenname = String::from_utf8(metadata.2.clone()).unwrap_or( - hex::encode(metadata.2.clone()) - ); + let tokenname = + String::from_utf8(metadata.2.clone()).unwrap_or(hex::encode(metadata.2.clone())); Ok(TokenInfoMint { fingerprint: metadata.0, policy: hex::encode(metadata.1), @@ -498,24 +504,18 @@ pub async fn txhash_is_spent(txhash: &String) -> Result { } /// The sum of all rewards ever received by the given stake address. -pub async fn total_rewards( - stake_addr: &str, -) -> Result { - Ok( - reward::table +pub async fn total_rewards(stake_addr: &str) -> Result { + Ok(reward::table .inner_join(stake_address::table.on(stake_address::id.eq(reward::addr_id))) .filter(stake_address::view.eq(stake_addr.to_string())) .select(reward::amount) .load::(&mut establish_connection()?)? .iter() - .sum() - ) + .sum()) } /// The sum of all reward withdrawals ever made by the given stake address. -pub async fn total_withdrawals( - stake_addr: &str, -) -> Result { +pub async fn total_withdrawals(stake_addr: &str) -> Result { let response = withdrawal::table .inner_join(stake_address::table.on(stake_address::id.eq(withdrawal::addr_id))) .filter(stake_address::view.eq(stake_addr.to_string())) @@ -527,10 +527,8 @@ pub async fn total_withdrawals( } /// The sum of all delegations (deposits) ever made by the given stake address. -pub async fn total_deposits( - stake_addr: &str, -) -> Result { - let response = delegation::table +pub async fn total_deposits(stake_addr: &str) -> Result { + let response = delegation::table .inner_join(tx::table.on(tx::id.eq(delegation::tx_id))) .inner_join(stake_address::table.on(stake_address::id.eq(delegation::addr_id))) .filter(stake_address::view.eq(stake_addr.to_string())) @@ -542,10 +540,8 @@ pub async fn total_deposits( } /// The total amount of rewards that the given stake address -/// has earned but not withdrawn. -pub async fn withdrawable_rewards( - stake_addr: &str, -) -> Result { +/// has earned but not withdrawn. +pub async fn withdrawable_rewards(stake_addr: &str) -> Result { let response = reward::table .inner_join(stake_address::table.on(stake_address::id.eq(reward::addr_id))) .filter(stake_address::view.eq(stake_addr.to_string())) @@ -555,13 +551,13 @@ pub async fn withdrawable_rewards( .sum::() .add( withdrawal::table - .inner_join(stake_address::table.on(stake_address::id.eq(withdrawal::addr_id))) - .filter(stake_address::view.eq(stake_addr.to_string())) - .select(withdrawal::amount) - .load::(&mut establish_connection()?)? - .iter() - .sum::() - .neg() + .inner_join(stake_address::table.on(stake_address::id.eq(withdrawal::addr_id))) + .filter(stake_address::view.eq(stake_addr.to_string())) + .select(withdrawal::amount) + .load::(&mut establish_connection()?)? + .iter() + .sum::() + .neg(), ); Ok(response) } @@ -569,12 +565,12 @@ pub async fn withdrawable_rewards( #[cfg(test)] mod tests { use crate::TokenInfoMint; - use serde_json::json; - use tokio; use bigdecimal::BigDecimal; - use std::str::FromStr; use dotenv::dotenv; + use serde_json::json; use std::ops::{Add, Neg}; + use std::str::FromStr; + use tokio; #[test] fn stake_registration() { @@ -587,13 +583,13 @@ mod tests { stake_address_view, tx_hash, stake_registration_cert_index, - stake_registration_epoch_no + stake_registration_epoch_no, ) = func_value[0].clone(); assert_eq!(func_value.len(), 1); assert_eq!(stake_address_view, stake_addr_in.to_string()); assert_eq!( - hex::encode(tx_hash.clone()), + hex::encode(tx_hash.clone()), "c6a5fb39114863da737a824f355c09f720479a94bff91b3613639e7313128dc7".to_string() ); assert_eq!(stake_registration_cert_index, 0); @@ -614,11 +610,14 @@ mod tests { tx_hash, stake_deregistration_cert_index, stake_deregistration_epoch_no, - stake_deregistration_redeemer_id + stake_deregistration_redeemer_id, ) = func_value.last().unwrap(); assert_eq!(stake_address_view, stake_addr_in); - assert_eq!(hex::encode(tx_hash), "49d55da2db879398172ada91da2f02d902a51daf744b5ff6da8c0c96467c0c2a"); // assumed to be correct + assert_eq!( + hex::encode(tx_hash), + "49d55da2db879398172ada91da2f02d902a51daf744b5ff6da8c0c96467c0c2a" + ); // assumed to be correct assert_eq!(stake_deregistration_cert_index, &0); assert_eq!(stake_deregistration_epoch_no, &8); assert_eq!(stake_deregistration_redeemer_id, &None); @@ -642,9 +641,11 @@ mod tests { fingerprint: "asset1t3m9e0gysc4xy392q25qwgj2hwca5qf3nhgcf4".to_string(), policy: "f0ff48bbb7bbe9d59a40f1ce90e9e9d0ff5002ec48f232b49ca0fb9a".to_string(), tokenname: "000643b0766963746f722e656c6261".to_string(), - meta_key: 721, - json: Some(json!({"f0ff48bbb7bbe9d59a40f1ce90e9e9d0ff5002ec48f232b49ca0fb9a": {"000de140766963746f722e656c6261": {"og": 0, "name": "$victor.elba", "image": "ipfs://zb2rhoGr5TMRmSYhupacB5pVSbViLWrt2MyTs1DH8i8ArRQAU", "length": 11, "rarity": "basic", "version": 1, "mediaType": "image/jpeg", "og_number": 0, "characters": "letters,special", "numeric_modifiers": ""}}})), - txhash: "fcc86f8adb7349eca89ec75a79be19091fb3040bf94baf95fdd421a625eaf045".to_string(), + meta_key: 721, + json: Some( + json!({"f0ff48bbb7bbe9d59a40f1ce90e9e9d0ff5002ec48f232b49ca0fb9a": {"000de140766963746f722e656c6261": {"og": 0, "name": "$victor.elba", "image": "ipfs://zb2rhoGr5TMRmSYhupacB5pVSbViLWrt2MyTs1DH8i8ArRQAU", "length": 11, "rarity": "basic", "version": 1, "mediaType": "image/jpeg", "og_number": 0, "characters": "letters,special", "numeric_modifiers": ""}}}), + ), + txhash: "fcc86f8adb7349eca89ec75a79be19091fb3040bf94baf95fdd421a625eaf045".to_string(), }; assert_eq!(func_value.fingerprint, real_value.fingerprint); @@ -654,7 +655,7 @@ mod tests { assert_eq!(func_value.json, real_value.json); assert_eq!(func_value.txhash, real_value.txhash); } - + #[tokio::test] async fn total_rewards() { dotenv().ok(); @@ -687,12 +688,7 @@ mod tests { let manual_value = super::total_rewards(stake_addr) .await .unwrap() - .add( - super::total_withdrawals(stake_addr) - .await - .unwrap() - .neg() - ); + .add(super::total_withdrawals(stake_addr).await.unwrap().neg()); assert_eq!(func_value, manual_value); } } diff --git a/drasil-mimir/src/lib.rs b/drasil-mimir/src/lib.rs index 38ae85c9..4d3de312 100644 --- a/drasil-mimir/src/lib.rs +++ b/drasil-mimir/src/lib.rs @@ -25,23 +25,3 @@ pub fn establish_connection() -> Result { let database_url = env::var("DBSYNC_DB_URL")?; Ok(PgConnection::establish(&database_url)?) } - -/* -// Wenn rerunning diesel-cli you need to copy this into the schema!!!! -// Also add 'unspent_utxos' to : allow_tables_to_appear_in_same_query makro in schmea at the end of the file -// The missing types are in module and a 'crate::' in front of them. -// Diesel is not good here.... - -table! { - unspent_utxos (id){ - id -> Int8, - tx_id -> Int8, - hash -> Bytea, - index -> Int2, - address -> Varchar, - value -> Numeric, - data_hash -> Nullable, - stake_address -> Nullable, - } -} -*/ diff --git a/drasil-murin/Cargo.toml b/drasil-murin/Cargo.toml index a9ebce8f..a88550ff 100644 --- a/drasil-murin/Cargo.toml +++ b/drasil-murin/Cargo.toml @@ -5,8 +5,8 @@ edition = "2021" description = "Drasil Blockchain Application Framework - Cardano Blockchain Library" repository = "https://github.com/Sbcdn/drasil.git" documentation = "https://docs.drasil.io" -license = "LICENSE_GPL.md" -readme = "README.md" +license = "https://github.com/Sbcdn/drasil/blob/main/LICENSE.md" +readme = "https://github.com/Sbcdn/drasil/blob/main/README.md" authors = ["Torben Poguntke "] [dependencies] diff --git a/drasil-murin/src/cardano/cip30/wallet.rs b/drasil-murin/src/cardano/cip30/wallet.rs index b243e7e9..8d38add2 100644 --- a/drasil-murin/src/cardano/cip30/wallet.rs +++ b/drasil-murin/src/cardano/cip30/wallet.rs @@ -10,24 +10,11 @@ use crate::error::MurinError; /// decode an hex encoded address into an address pub async fn decode_address_from_bytes(bytes: &String) -> Result { - //let stake_cred_key = ccrypto::Ed25519KeyHash::from_bytes(hex::decode(bytes)?)?; - //let stake_cred = caddr::StakeCredential::from_keyhash(&stake_cred_key); - //let mut netbyte : u8 = 0b1111; - //if *network == clib::NetworkIdKind::Testnet { - // netbyte = 0b1110; - //} Ok(caddr::Address::from_bytes(hex::decode(bytes)?)?) - //Ok(caddr::RewardAddress::new(netbyte,&stake_cred).to_address()) } /// decode an hex encoded address into an address pub async fn address_from_string(str: &String) -> Result { - //let stake_cred_key = ccrypto::Ed25519KeyHash::from_bytes(hex::decode(bytes)?)?; - //let stake_cred = caddr::StakeCredential::from_keyhash(&stake_cred_key); - //let mut netbyte : u8 = 0b1111; - //if *network == clib::NetworkIdKind::Testnet { - // netbyte = 0b1110; - //} match hex::decode(str) { Ok(bytes) => Ok(caddr::Address::from_bytes(bytes)?), Err(_) => match caddr::Address::from_bech32(str) { @@ -37,16 +24,10 @@ pub async fn address_from_string(str: &String) -> Result Result { - //let stake_cred_key = ccrypto::Ed25519KeyHash::from_bytes(hex::decode(bytes)?)?; - //let stake_cred = caddr::StakeCredential::from_keyhash(&stake_cred_key); - //let mut netbyte : u8 = 0b1111; - //if *network == clib::NetworkIdKind::Testnet { - // netbyte = 0b1110; - //} match hex::decode(str) { Ok(bytes) => Ok(caddr::Address::from_bytes(bytes)?), Err(_) => match caddr::Address::from_bech32(str) { @@ -63,7 +44,6 @@ pub async fn addresses_from_string( addresses: &Vec, ) -> Result, MurinError> { let mut ret = Vec::::new(); - //Ok(caddr::Address::from_bytes(hex::decode(bytes)?)?) for addr in addresses { ret.push(address_from_string(addr).await?) } @@ -206,7 +186,6 @@ pub fn bech32_stake_address_from_str(str: &str) -> Result { pub fn payment_keyhash_from_address( addr: &caddr::Address, ) -> Result { - //info!("\nAddress in get_payment_address: {:?}",addr); let address = caddr::BaseAddress::from_address(addr); let err = MurinError::new("ERROR wallet::get_pubkey gut not deserialize pub key from address"); match address { @@ -387,22 +366,6 @@ pub fn restore_bip0039_wallet( } }); - /* - let account_key1 = root_key - .derive(crate::txbuilders::harden(1852u32)) - .derive(crate::txbuilders::harden(1815u32)) - .derive(crate::txbuilders::harden(0u32)); - let ac1_chaincode = account_key1.chaincode(); - let ac1_private_key = account_key1.to_raw_key(); // for signatures - let ac1_public_key = account_key1.to_raw_key().to_public(); - let ac1_public_key_hash = account_key1.to_raw_key().to_public().hash(); // for Native Script Input / Verification - let vkey1 = "5840".to_string() - + &((hex::encode(ac1_public_key.as_bytes())) + &hex::encode(ac1_chaincode.clone())); // .vkey - let skey1 = "5880".to_string() - + &(hex::encode(ac1_private_key.as_bytes()) - + &hex::encode(ac1_public_key.as_bytes()) - + &hex::encode(ac1_chaincode)); // .skey - */ Ok((root_key.to_hex(), root_key)) } diff --git a/drasil-murin/src/cardano/mod.rs b/drasil-murin/src/cardano/mod.rs index 2e022434..6c1470b2 100644 --- a/drasil-murin/src/cardano/mod.rs +++ b/drasil-murin/src/cardano/mod.rs @@ -12,29 +12,14 @@ pub use supporting_functions::*; use cardano_serialization_lib as clib; use cardano_serialization_lib::utils as cutils; -use serde::{Deserialize, Serialize}; -use std::env; -use std::path::PathBuf; - -//use octavo_digest::Digest; -// use octavo_digest::blake2::*; pub fn blake2b160(data: &[u8]) -> [u8; 20] { - //Vec:: { let mut out = [0u8; 20]; let mut context = Blake2b::new(20); context.input(data); context.result(&mut out); Blake2b::blake2b(&mut out, data, &[]); out - - // let mut result = vec![0; 20]; - // let mut b2b = Blake2s160::default(); - - // b2b.update(data); - // b2b.result(&mut result); - // println!("Result: {:?}",result); - // result } pub fn string_to_policy(str: &String) -> Result { @@ -53,80 +38,8 @@ pub fn make_fingerprint(p: &String, a: &String) -> Result { let policy = hex::decode(p)?; let tn = hex::decode(a)?; let data = [&policy[..], &tn[..]].concat(); - //policy.append(&mut tn.name()); let hash = blake2b160(&data); let fingerprint = bech32::Bech32::new("asset".to_string(), hash.to_base32()).unwrap(); debug!("Maker Fingerprint: {:?}", fingerprint); Ok(fingerprint.to_string()) } - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] -pub struct ExUnitPrice { - priceSteps: f64, - priceMemory: f64, -} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] -pub struct ExUnit { - steps: f64, - memory: f64, -} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] -pub struct ProtocolVersion { - minor: u32, - major: u32, -} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] -pub struct PlutusScriptV1 {} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] -pub struct Cpp { - maxValueSize: u64, - minUTxOValue: Option, - minPoolCost: u64, - monetaryExpansion: f64, - stakeAddressDeposit: u64, - txFeeFixed: u64, - poolRetireMaxEpoch: u32, - stakePoolDeposit: u64, - maxBlockExecutionUnits: ExUnit, - stakePoolTargetNum: u32, - maxBlockHeaderSize: u32, - maxCollateralInputs: u32, - txFeePerByte: u64, - treasuryCut: f32, - protocolVersion: ProtocolVersion, - collateralPercentage: u32, - poolPledgeInfluence: f32, - maxTxExecutionUnits: ExUnit, - executionUnitPrices: ExUnitPrice, - decentralization: u32, - utxoCostPerWord: u64, - maxTxSize: u64, - maxBlockBodySize: u64, - // costModels : PlutusScriptV1, -} - -impl Cpp { - // ToDO: - // Not happy with this solution, we would always read the parameters again, - // it would be nice to store them for each start of hearth somehwere globaly in memory - // and retrievem them from there without the need to read the file each time - // Maybe via Redis ? - - pub fn get_protcol_parameters(path: Option<&String>) -> Result { - let path_pp: PathBuf = match path { - None => { - let path_pp_env = env::var("CARDANO_PROTOCOL_PARAMETER_PATH")?; - PathBuf::from(path_pp_env) - } - Some(path) => PathBuf::from(path), - }; - // Protocol Parameter JSON - let pp_data = std::fs::read_to_string(path_pp)?; - let pp: Cpp = serde_json::from_str(&pp_data)?; - Ok(pp) - } -} diff --git a/drasil-murin/src/cardano/models.rs b/drasil-murin/src/cardano/models.rs index 3d807712..069f414e 100644 --- a/drasil-murin/src/cardano/models.rs +++ b/drasil-murin/src/cardano/models.rs @@ -79,9 +79,9 @@ pub_struct!(Assets { amount: u64, }); -pub_struct!(Value { // lovelace is empty String or "lovelace" in currency symbol - currencySymbol : String, // Hexadecimal ByteString ; what type to make lib::Asset out of it? - assets : Vec, // Hexadecimal ByteString ; what type to make lib:Asset out of it ? +pub_struct!(Value { + currencySymbol : String, + assets : Vec, }); @@ -104,7 +104,6 @@ pub_struct!(TxInput { value : Vec, }); -//#[derive(Serialize,Deserialize, Debug,Clone)] pub_struct!(MpTxData { script_outputs : Vec, outputs : Vec, diff --git a/drasil-murin/src/cardano/supporting_functions.rs b/drasil-murin/src/cardano/supporting_functions.rs index 12cb553a..9bb5f600 100644 --- a/drasil-murin/src/cardano/supporting_functions.rs +++ b/drasil-murin/src/cardano/supporting_functions.rs @@ -38,8 +38,6 @@ pub fn _ccli_query_utxos_address( .arg(addr.to_bech32(Some(net.1.to_string())).unwrap()) .arg(magic) .arg(magic_n) - //.stdout(std::process::Stdio::null()) - //.stderr(std::process::Stdio::piped()) .output() .expect("Get utxos with Cardano-Cli failed"); @@ -162,11 +160,6 @@ pub fn _ccli_query_utxos_address( txuos.add(&txuo); } } - // io::stdin().read_line(&mut line).expect("ERROR: Could not read Tx-Data from stdin"); - // info!("Line: {}",line); - //let txh = TxHash {tx_hash : tx_hash.clone(), message : "success".to_string()}; - //serde_json::to_writer(&io::stdout(),&txh).unwrap(); - //let _r = fs::remove_file(format!("tmp_tx/{}.tx",tx_hash)); return Some(txuos); } else { info!("Error: could not read stdin, {:?}", ret.status); @@ -289,7 +282,6 @@ pub fn get_stake_keyhash(addr: &caddr::Address) -> ccrypto::Ed25519KeyHash { } pub fn get_payment_keyhash(addr: &caddr::Address) -> ccrypto::Ed25519KeyHash { - //info!("\nAddress in get_payment_address: {:?}",addr); let address = caddr::BaseAddress::from_address(addr); let payment_cred_key: ccrypto::Ed25519KeyHash; match address { @@ -316,7 +308,6 @@ pub fn get_payment_keyhash(addr: &caddr::Address) -> ccrypto::Ed25519KeyHash { } } } - //info!("Payment Addres: {:?}\n",hex::encode(payment_cred_key.to_bytes())); payment_cred_key } /* @@ -674,9 +665,6 @@ pub fn split_output_txo(txo: clib::TransactionOutput, split_txos: &mut clib::Tra } } } - //if name.to_bytes() == hex::decode("5436").unwrap() || name.to_bytes() == hex::decode("5435").unwrap() { - // info!("Name! {:?}\n",name.to_bytes()); - //} } match value.coin().checked_sub( &new_txo @@ -692,7 +680,6 @@ pub fn split_output_txo(txo: clib::TransactionOutput, split_txos: &mut clib::Tra match rest_val.multiasset() { None => { let added_val = new_txo.amount(); - //added_val.set_coin(&rest_val.coin().checked_add(&new_txo.amount().coin()).unwrap()); new_txo = clib::TransactionOutput::new( &addr, &added_val, ); @@ -780,8 +767,6 @@ pub fn find_suitable_coins( inputs: &mut TransactionUnspentOutputs, overhead: u64, ) -> (Option, u64) { - //Fee need to be considered in needed value - let coins = cutils::from_bignum(&nv.coin()); let max_coins = coins + (coins / 100 * overhead); // Coins + Overhead in % @@ -790,33 +775,13 @@ pub fn find_suitable_coins( let mut multi_storage = TransactionUnspentOutputs::new(); let mut coin_storage = TransactionUnspentOutputs::new(); - //debug!("\n\nTXINS in find suitabe coins: {:?}\n\n", inputs); - - //debug!( - // "\nFIND COINS: max_coins {:?}, coins: {:?}\n", - // max_coins, coins - //); 'outer: for tx in inputs.clone() { - debug!( - "\n-------TXIn : {:?}#{:?}", - tx.input().transaction_id().to_hex(), - tx.input().index() - ); - let lc = cutils::from_bignum(&tx.output().amount().coin()); - //debug!( - // "\n---LC: {:?}----TXIn : {:?}{:?}", - // lc, - // tx.input().transaction_id(), - // tx.input().index() - //); if lc > coins { match tx.output().amount().multiasset() { Some(multi) => match multi.len() { 0 => { - //debug!("Multiasset of Len 0: Found Coins: {:?}", lc); if lc < max_coins { - //debug!("No Multiasset: Found Coins: {:?}", lc); selection.add(&tx); debug!("Selection: {:?}", selection); return (Some(selection), lc); @@ -826,21 +791,16 @@ pub fn find_suitable_coins( } 1..=21 => { - //debug!("Multiasses with less than 21 NFTs, Found Coins: {:?}", lc); selection.add(&tx); - //debug!("Selection: {:?}", selection); return (Some(selection), lc); } _ => { - //debug!("More than 21 NFTs, Found Coins: {:?}", lc); - //debug!("Trying find better option, store this one"); multi_storage.add(&tx); } }, None => { if lc < max_coins { - //debug!("No Multiasset: Found Coins: {:?}", lc); selection.add(&tx); debug!("Selection: {:?}", selection); return (Some(selection), lc); @@ -865,7 +825,6 @@ pub fn find_suitable_coins( } if !coin_storage.is_empty() { coin_storage.sort_by_coin(); - //debug!("Took from coinstorage: {:?}", coin_storage); let tx = coin_storage.get(0); selection.add(&tx); @@ -873,24 +832,15 @@ pub fn find_suitable_coins( return (Some(selection), acc); } else { for tx in inputs { - //debug!( - // "\n-------TXIn in Acc : {:?}{:?}", - // tx.input().transaction_id(), - // tx.input().index() - //); let lc = cutils::from_bignum(&tx.output().amount().coin()); acc += lc; - //debug!("Acc {:?}, LC: {:?}", acc, lc); selection.add(&tx); if acc > coins + MIN_ADA { - //debug!("Return in Accumulator {:?}", acc); return (Some(selection), acc); } } } - //debug!("SUITABLE COINS: {:?}", acc); - if selection.is_empty() { debug!("Selection length = 0"); (None, 0) @@ -953,8 +903,7 @@ pub fn find_utxos_by_address( #[allow(clippy::too_many_arguments)] pub fn balance_tx( input_txuos: &mut TransactionUnspentOutputs, - // script_outputs : Option<&TransactionUnspentOutput>, - _tokens: &Tokens, //&Vec<(ccrypto::ScriptHash, clib::AssetName, BigNum)>, + _tokens: &Tokens, txos: &mut clib::TransactionOutputs, already_paid: Option<&cutils::Value>, fee: &cutils::BigNum, @@ -1021,7 +970,6 @@ pub fn balance_tx( if matching_addresses { *acc_change = acc_change.checked_add(&value).unwrap(); } else { - // TODO: Make SC ADDR Variable to be able to use different Smart Contracts if let Some(sc) = sc_addr.clone() { if input_address_pkey == get_stake_keyhash(&sc) { *acc_change = acc_change.checked_add(&value)?; diff --git a/drasil-murin/src/txbuilder/marketplace/mod.rs b/drasil-murin/src/txbuilder/marketplace/mod.rs index 9f7c1163..c6738495 100644 --- a/drasil-murin/src/txbuilder/marketplace/mod.rs +++ b/drasil-murin/src/txbuilder/marketplace/mod.rs @@ -175,52 +175,6 @@ impl MpTxData { } } -pub fn make_mp_contract_utxo_output( - txos: &mut clib::TransactionOutputs, - receiver: caddr::Address, - datum: &ccrypto::DataHash, - tokens: &Vec, - //token_utxos : &TransactionUnspentOutputs, - set_datum: bool, -) -> Option { - ////////////////////////////////////////////////////////////////////////////////////////////////////// - // - //Add Script Outputs for Transaction Body - // Add the NFT from the smart contract - /////////////////////////////////////////////////////////////////////////////////////////////////////// - //let mut txuos = TransactionUnspentOutputs::new(); - // let mut txuo : Option = None; - - if !tokens.is_empty() { - let mut value = cutils::Value::new(&cutils::to_bignum(0u64)); - //let mut lovelaces : u64 = 0; - let mut multiasset = clib::MultiAsset::new(); - - for token in tokens { - let mut assets = clib::Assets::new(); - assets.insert(&token.1, &token.2); - multiasset.insert(&token.0, &assets); - } - value.set_multiasset(&multiasset); - - // Todo calc min ada needs to go to txbuilders module - let min_ada_utxo = crate::calc_min_ada_for_utxo(&value, Some(datum.clone())); - value.set_coin(&min_ada_utxo); - let mut txout = clib::TransactionOutput::new(&receiver, &value); - //let txin = clib::TransactionInput::new( - // &ccrypto::TransactionHash::from_bytes(hex::decode(o.txhash.clone()).unwrap()).unwrap(),o.txinput); - - if set_datum { - txout.set_data_hash(datum) - }; - txos.add(&txout); - - Some(txos.clone()) - } else { - None - } -} - pub struct MarketPlaceDatum { price: u64, seller: Ed25519KeyHash, @@ -358,56 +312,3 @@ pub fn decode_mp_datum(bytes: &[u8]) -> Result { token_name, }) } - -pub fn make_inputs_txb( - inputs: &Vec, -) -> (clib::TransactionInputs, TransactionUnspentOutputs) { - ////////////////////////////////////////////////////////////////////////////////////////////////////// - // - //Add wallet inputs for the transaction - // Add the inputs for this transaction - /////////////////////////////////////////////////////////////////////////////////////////////////////// - let mut txuos = TransactionUnspentOutputs::new(); // Available in 9.2.0 beta not in 9.1.2 - let mut txins = clib::TransactionInputs::new(); - for i in inputs { - let txuo_in = &clib::TransactionInput::new( - &ccrypto::TransactionHash::from_bytes(hex::decode(i.txhash.clone()).unwrap()).unwrap(), - i.txinput, - ); - - let mut value = cutils::Value::new(&cutils::to_bignum(0u64)); - let mut lovelaces: u64 = 0; - let mut multiasset = clib::MultiAsset::new(); - for v in &i.value { - if v.currencySymbol.is_empty() || v.currencySymbol == "lovelace" { - for a in &v.assets { - lovelaces += a.amount; - } - } else { - let cs: clib::PolicyID = - clib::PolicyID::from_bytes(hex::decode(&v.currencySymbol).unwrap()).unwrap(); - let mut assets = clib::Assets::new(); - for a in &v.assets { - let tn: clib::AssetName = - clib::AssetName::new(hex::decode(&a.tokenName).unwrap()).unwrap(); - assets.insert(&tn, &cutils::to_bignum(a.amount)); - //info!("{:?}.{:?}",cs,assets); - multiasset.insert(&cs, &assets); - } - } - } - value.set_coin(&cutils::to_bignum(lovelaces)); - value.set_multiasset(&multiasset); - let addr = &caddr::Address::from_bech32(&i.address).unwrap(); - let txuo_out = clib::TransactionOutput::new(addr, &value); - let txuo: cutils::TransactionUnspentOutput = - cutils::TransactionUnspentOutput::new(txuo_in, &txuo_out); - //info!("TXOU: {:?}",txuo); - //info!(); - - txuos.add(&txuo); - txins.add(txuo_in); - } - - (txins.clone(), txuos.clone()) -} diff --git a/drasil-murin/src/txbuilder/minter/build_minttx.rs b/drasil-murin/src/txbuilder/minter/build_minttx.rs index 22aba20c..4e309d3b 100644 --- a/drasil-murin/src/txbuilder/minter/build_minttx.rs +++ b/drasil-murin/src/txbuilder/minter/build_minttx.rs @@ -15,9 +15,7 @@ use cardano_serialization_lib::{crypto as ccrypto, utils as cutils}; use clib::address::Address; use super::models::{ColMinterTxData, PriceCMintHandle}; -//use std::env; -// One Shot Minter Builder Type #[derive(Debug, Clone)] pub struct AtCMBuilder { pub scripts: Vec, @@ -70,8 +68,7 @@ impl<'a> super::PerformTxb> for AtCMBuilder { } let native_script = &self.scripts[0]; - let mintpolicy = native_script.hash(); //clib::ScriptHashNamespace::NativeScript - // let minttokens = mintasset_into_tokenasset(self.stxd.get_mint_tokens(), mintpolicy.clone()); + let mintpolicy = native_script.hash(); ///////////////////////////////////////////////////////////////////////////////////////////////////// // @@ -114,18 +111,12 @@ impl<'a> super::PerformTxb> for AtCMBuilder { // Inputs let mut input_txuos = gtxd.clone().get_inputs(); - - info!("\n Before USED UTXOS"); // Check if some utxos in inputs are in use and remove them if let Some(used_utxos) = crate::utxomngr::usedutxos::check_any_utxo_used(&input_txuos)? { - info!("\n\n"); - info!("USED UTXOS: {:?}", used_utxos); - info!("\n\n"); input_txuos.remove_used_utxos(used_utxos); } let collateral_input_txuo = gtxd.clone().get_collateral(); - debug!("\nCollateral Input: {:?}", collateral_input_txuo); // Balance TX let mut fee_paid = false; @@ -143,18 +134,12 @@ impl<'a> super::PerformTxb> for AtCMBuilder { needed_value.set_coin(&needed_value.coin().checked_add(&security).unwrap()); let mut needed_value = cutils::Value::new(&needed_value.coin()); - debug!("Needed Value: {:?}", needed_value); - debug!( - "\n\n\n\n\nTxIns Before selection:\n {:?}\n\n\n\n\n", - input_txuos - ); - let (txins, mut input_txuos) = input_selection( None, &mut needed_value, &input_txuos, gtxd.clone().get_collateral(), - None, //Some(native_script_address).as_ref(), + None, )?; let saved_input_txuos = input_txuos.clone(); @@ -173,13 +158,13 @@ impl<'a> super::PerformTxb> for AtCMBuilder { &mut input_txuos, &Tokens::new(), &mut txouts, - Some(mint_val_zero_coin).as_ref(), // but not the ADA!!!! + Some(mint_val_zero_coin).as_ref(), fee, &mut fee_paid, &mut first_run, &mut txos_paid, &mut tbb_values, - &receiver, //who is sender ? + &receiver, &change_address, &mut acc, None, @@ -220,12 +205,6 @@ impl<'a> super::PerformTxb> for AtCMBuilder { txbody.set_mint(&mint); - //let req_signer = native_script.get_required_signers(); - //info!("Len Req SIgner: {:?}",req_signer.len()); - //for i in 0..req_signer.len() { - // info!("Required Signer: {:?}" ,req_signer.get(i).to_bech32("pkh_")) //req_signer.len() - //} - let mut txwitness = clib::TransactionWitnessSet::new(); let mut native_scripts = clib::NativeScripts::new(); native_scripts.add(native_script); diff --git a/drasil-murin/src/txbuilder/minter/build_oneshot_mint.rs b/drasil-murin/src/txbuilder/minter/build_oneshot_mint.rs index 6d78de58..33d2158e 100644 --- a/drasil-murin/src/txbuilder/minter/build_oneshot_mint.rs +++ b/drasil-murin/src/txbuilder/minter/build_oneshot_mint.rs @@ -116,47 +116,18 @@ impl<'a> super::PerformTxb> for AtOSMBuilder { debug!("Needed Value: {:?}", needed_value); - //let mut signers_address_utxos = (TransactionUnspentOutputs::new(),TransactionUnspentOutputs::new()); - //if let Some(signer) = minttxd.get_signer() { - // signers_address_utxos = find_utxos_by_address(signer.clone(), &input_txuos); - //} - - //println!("Signer Address UTXOS: {:?}",signers_address_utxos.0); let (txins, mut input_txuos) = input_selection( None, &mut needed_value, &input_txuos, gtxd.clone().get_collateral(), - None, //Some(native_script_address).as_ref(), + None, )?; - /* - if let Some(signer) = minttxd.get_signer() { - if input_txuos.contains_any(&signers_address_utxos.0) { - info!("\n\nUtxo Input set contains minimum one utxo from the listing address\n\n"); - } else { - if !signers_address_utxos.0.is_empty() { - // ToDo: - // In this case it would be better to have some larger Ada only Utxo -> Create a function to find one - txins.add(&signers_address_utxos.0.get(0).input()); - input_txuos.add(&signers_address_utxos.0.get(0)); - } else { - return Err( - MurinError::new( - &format!( - "Error: The Address which is needed for signature does not contain ADA, please provide suitable amount of ADA to: {:?}",signer.to_bech32(None) - ) - ) - ) - } - } - } - */ let saved_input_txuos = input_txuos.clone(); let vkey_counter = get_vkey_count(&input_txuos, None) + 1; // +1 due to signature in finalize - // ToDo: let mut mint_val_zero_coin = mint_val.clone(); mint_val_zero_coin.set_coin(&cutils::to_bignum(0u64)); @@ -164,13 +135,13 @@ impl<'a> super::PerformTxb> for AtOSMBuilder { &mut input_txuos, &minttokens, &mut txouts, - Some(mint_val_zero_coin).as_ref(), // but not the ADA!!!! + Some(mint_val_zero_coin).as_ref(), fee, &mut fee_paid, &mut first_run, &mut txos_paid, &mut tbb_values, - &change_address, //who is sender ? + &change_address, &change_address, &mut acc, None, @@ -210,7 +181,7 @@ impl<'a> super::PerformTxb> for AtOSMBuilder { let req_signer = self.script.get_required_signers(); info!("Len Req SIgner: {:?}", req_signer.len()); for i in 0..req_signer.len() { - info!("Required Signer: {:?}", req_signer.get(i).to_bech32("pkh_")) //req_signer.len() + info!("Required Signer: {:?}", req_signer.get(i).to_bech32("pkh_")) } let mut txwitness = clib::TransactionWitnessSet::new(); diff --git a/drasil-murin/src/txbuilder/minter/mod.rs b/drasil-murin/src/txbuilder/minter/mod.rs index 200744ee..466f0887 100644 --- a/drasil-murin/src/txbuilder/minter/mod.rs +++ b/drasil-murin/src/txbuilder/minter/mod.rs @@ -181,7 +181,6 @@ impl std::str::FromStr for MinterTxData { type Err = MurinError; fn from_str(src: &str) -> std::result::Result { let slice: Vec<&str> = src.split('|').collect(); - //debug!("Slice: {:?}",slice); if slice.len() == 8 { // restore token vector let mut tokens = Vec::::new(); @@ -272,7 +271,7 @@ pub struct MetadataFile { pub name: String, #[serde(rename(serialize = "mediaType", deserialize = "mediaType"))] pub media_type: String, - pub src: serde_json::Value, // Source -> The problem is the deserialization on the Source type as it has on serde side no implementation, need to be doen with serde_json::Value + pub src: serde_json::Value, pub other: Option>, } @@ -340,9 +339,8 @@ impl AssetMetadata { Value::String(s) => match hex::decode(s) { Ok(v) => { a.tokenname = hex::encode(v.clone()); - a.name = Some(String::from_utf8(v.clone()).unwrap_or( - hex::encode(v) - )); + a.name = + Some(String::from_utf8(v.clone()).unwrap_or(hex::encode(v))); } Err(_e) => { a.tokenname = hex::encode(s.as_bytes()); @@ -448,26 +446,7 @@ pub fn make_mint_metadata( let policy_str = hex::encode(policy_id.to_bytes()); let mut toplevel_metadata = clib::metadata::GeneralTransactionMetadata::new(); - //let mut raw_metadata = Vec::::new(); - //debug!("RawMetadata: {:?}", raw_metadata); - - // Check if all tokens have metadata available - /* let mut i = 0; - 'avail_tok: for token in tokens.clone() { - let t_name = str::from_utf8(&token.1.name())?.to_string(); - debug!("TName: {}", t_name); - for asset in raw_metadata.assets.clone() { - if asset.tokenname == t_name { - i += 1; - continue 'avail_tok; - } - } - } - if tokens.len() != i { - return Err(MurinError::new(&format!("Error provided metadata and tokens to mint are not fitting, please provide correct metadata: \n {:?}",raw_metadata))); - } - */ let mut metamap = clib::metadata::MetadataMap::new(); let mut assetmap = MetadataMap::new(); @@ -498,19 +477,13 @@ fn chunk_string(metamap: &mut MetadataMap, key: &str, s: &String) -> Result<(), let chunks = s .as_bytes() .chunks(64) - .map(|c| - String::from(str::from_utf8(c).unwrap_or( - &hex::encode(c) - )) - ) + .map(|c| String::from(str::from_utf8(c).unwrap_or(&hex::encode(c)))) .collect::>(); log::debug!("Chunks: {:?}", chunks); let mut list = MetadataList::new(); for s in chunks { - list.add(&clib::metadata::TransactionMetadatum::new_text( - s, - )?) + list.add(&clib::metadata::TransactionMetadatum::new_text(s)?) } metamap.insert_str(key, &clib::metadata::TransactionMetadatum::new_list(&list))?; } else { @@ -671,7 +644,6 @@ pub fn make_mint_metadata_from_json( let policy_str = hex::encode(policy_id.to_bytes()); let mut toplevel_metadata = clib::metadata::GeneralTransactionMetadata::new(); - //let mut raw_metadata = Vec::::new(); debug!("RawMetadata: {:?}", raw_metadata); diff --git a/drasil-murin/src/txbuilder/modules/transfer/models.rs b/drasil-murin/src/txbuilder/modules/transfer/models.rs index 44d79fb4..0ae6169a 100644 --- a/drasil-murin/src/txbuilder/modules/transfer/models.rs +++ b/drasil-murin/src/txbuilder/modules/transfer/models.rs @@ -190,35 +190,15 @@ impl TransBuilder { self.replace_transfer((&fee_transfer.0, fee_transfer.1))?; log::debug!("\n\n\nAfter FeeSet: \n{:?}\n", self.transfers); } else { - //ToDo: Do not error out, add fee to sending wallet log::debug!( "\n\n\nno transfer for specified fee_addr exists\n{:?}\n", self.transfers ); - /* - if self.transfers.len() == 1 { - self.transfers[0].source.add_fee(&fee)?; - } else { - log::debug!( - "\n\n\nno transfer for specified fee_addr exists and more than one transfer in transaction, cannot automatically determine fee payer\n{:?}\n", - self.transfers - ); - return Err(TransferError::Custom( - "no transfer for specified fee_addr exists".to_string(), - )); - } - */ + return Err(TransferError::Custom( "no transfer for specified fee_addr exists".to_string(), )); } - // Balance all transfers - //let mut handles = Vec::<_>::new(); - //self.transfers.iter_mut().for_each(|n| { - // log::debug!("Pay Address: {:?}", n.source.pay_addr); - // log::trace!("Wallets: {:?}", self.wallets); - // let r = n.balance(self.wallets.get_wallet(&n.source.pay_addr)?)?; - //}); for t in &mut self.transfers { log::debug!("Pay Address: {:?}", t.source.pay_addr); @@ -226,13 +206,6 @@ impl TransBuilder { t.balance(self.wallets.get_wallet(&t.source.pay_addr)?)?; } - //handles.push(); - - //let handler = tokio::spawn(async move { t.balance(wallet).await }); - //handles.push(handler); - - //futures::future::join_all(handles.into_iter()).await; - // Determine total tx inputs log::debug!("\n Determine total tx inputs....."); let txins: TransactionInputs = diff --git a/drasil-murin/src/txbuilder/modules/txtools/lib.rs b/drasil-murin/src/txbuilder/modules/txtools/lib.rs deleted file mode 100644 index 8b137891..00000000 --- a/drasil-murin/src/txbuilder/modules/txtools/lib.rs +++ /dev/null @@ -1 +0,0 @@ - diff --git a/drasil-murin/src/txbuilder/modules/txtools/mod.rs b/drasil-murin/src/txbuilder/modules/txtools/mod.rs index df71909d..752f2378 100644 --- a/drasil-murin/src/txbuilder/modules/txtools/mod.rs +++ b/drasil-murin/src/txbuilder/modules/txtools/mod.rs @@ -1,4 +1,3 @@ pub mod error; -pub mod lib; pub mod models; pub mod utxo_handling; diff --git a/drasil-murin/src/txbuilder/modules/txtools/models.rs b/drasil-murin/src/txbuilder/modules/txtools/models.rs index a137f04e..d1369b21 100644 --- a/drasil-murin/src/txbuilder/modules/txtools/models.rs +++ b/drasil-murin/src/txbuilder/modules/txtools/models.rs @@ -1,16 +1,5 @@ use crate::clib; use crate::clib::utils::BigNum; -//use crate::TransactionUnspentOutputs; pub type TokenAsset = (clib::PolicyID, clib::AssetName, BigNum); pub type MintTokenAsset = (Option, clib::AssetName, BigNum); - -/* -pub(crate) type TxBO = ( - clib::TransactionBody, - clib::TransactionWitnessSet, - clib::metadata::AuxiliaryData, - TransactionUnspentOutputs, - usize, -); - */ diff --git a/drasil-murin/src/txbuilder/modules/txtools/utxo_handling.rs b/drasil-murin/src/txbuilder/modules/txtools/utxo_handling.rs index fe0cccde..7adbfef8 100644 --- a/drasil-murin/src/txbuilder/modules/txtools/utxo_handling.rs +++ b/drasil-murin/src/txbuilder/modules/txtools/utxo_handling.rs @@ -22,7 +22,6 @@ pub async fn find_token_utxos( if let Some(multi) = value.multiasset() { if let Some(toks) = multi.get(&asset.0) { if let Some(amt) = toks.get(&asset.1) { - // for tok in 0..toks.len() { if needed_amt >= asset.2 { log::debug!( "Found a utxo containing {} tokens {}.{}!", @@ -199,8 +198,6 @@ pub fn input_selection( exclude: Option, on_addr: Option<&Address>, ) -> Result<(clib::TransactionInputs, TransactionUnspentOutputs), TxToolsError> { - //debug!("\n\nMULTIASSETS: {:?}\n\n", txins); - let (mut purecoinassets, mut multiassets) = crate::cardano::supporting_functions::splitt_coin_multi(txins); @@ -233,18 +230,13 @@ pub fn input_selection( } if let Some(exclude_utxo) = exclude { - //debug!("Exclude: {:?}", exclude_utxo); let c_index = crate::cardano::supporting_functions::find_collateral_by_txhash_txix( &exclude_utxo, &purecoinassets, ); - //debug!( - // "Some excludes to check for deletion found, Index: {:?}", - // c_index - //); + if let Some(index) = c_index { purecoinassets.swap_remove(index); - //debug!("deleted exclude from inputs: {:?}\n", col); // Double check if crate::cardano::supporting_functions::find_collateral_by_txhash_txix( &exclude_utxo, @@ -289,10 +281,6 @@ pub fn input_selection( // Delete script input from multi assets to not select it again if let Some(i) = multiassets.find_utxo_index(&token_selection.get(i)) { multiassets.swap_remove(i); - //debug!( - // "Deleted token utxo from multiasset inputs: \n {:?}\n", - // tutxo - //); } } } @@ -378,15 +366,6 @@ pub fn combine_wallet_outputs(txos: &clib::TransactionOutputs) -> clib::Transact for o in 0..txos.len() { _txos.push(txos.get(o)) } - /* - let wallets: Vec = _txos - .iter() - .filter( - |n| true, /*clib::address::BaseAddress::from_address(&n.address()).is_some()*/ - ) - .map(|n| n.to_owned()) - .collect(); - */ let addresses = _txos .iter() @@ -416,14 +395,6 @@ pub fn combine_wallet_outputs(txos: &clib::TransactionOutputs) -> clib::Transact _ => {} } }); - /* - let r: Vec = _txos - .iter() - .filter(|n| clib::address::BaseAddress::from_address(&n.address()).is_none()) - .map(|n| n.to_owned()) - .collect(); - for e in r { - out.add(&e); - }*/ + out } diff --git a/drasil-murin/src/txbuilder/rwdist/build_rwd.rs b/drasil-murin/src/txbuilder/rwdist/build_rwd.rs index 862a0bea..9bf1c878 100644 --- a/drasil-murin/src/txbuilder/rwdist/build_rwd.rs +++ b/drasil-murin/src/txbuilder/rwdist/build_rwd.rs @@ -173,7 +173,6 @@ impl<'a> super::PerformTxb> for AtRWDBuilder { if let Some(f) = &self.stxd.get_fee() { contract_fee += f; } - //log::debug!("any wallet call....."); let any_script_wallet = wallets.get_wallet_cid(rwd_contract_ids[0])?; let cfee_val = cutils::Value::new(&cutils::to_bignum(contract_fee)); @@ -226,8 +225,6 @@ impl<'a> super::PerformTxb> for AtRWDBuilder { let mut native_scripts = clib::NativeScripts::new(); for id in rwd_contract_ids { - log::debug!("wallet_id: {:?}", id); - //log::debug!("wallets: {:?}", self.wallets); let w = builder.wallets.get_wallet_cid(id)?; native_scripts.add(&w.script.as_ref().unwrap().script); diff --git a/drasil-murin/src/txbuilder/rwdist/mod.rs b/drasil-murin/src/txbuilder/rwdist/mod.rs index ad78274d..b662db36 100644 --- a/drasil-murin/src/txbuilder/rwdist/mod.rs +++ b/drasil-murin/src/txbuilder/rwdist/mod.rs @@ -119,9 +119,6 @@ impl RWDTxData { rewards: &[RewardHandle], recipient_stake_addr: &caddr::Address, recipient_payment_addr: &caddr::Address, - //fee_wallet_addr : &caddr::Address, - //fee : &u64, - //reward_utxos : &Option, ) -> RWDTxData { RWDTxData { rewards: rewards.to_vec(), @@ -191,10 +188,6 @@ impl ToString for RWDTxData { // prepare tokens vector let mut s_tokens = String::new(); for ta in self.get_rewards() { - //let mut subs = String::new(); - //subs.push_str(&(hex::encode(ta.0.to_bytes()) + "?")); - //subs.push_str(&(hex::encode(ta.1.to_bytes()) + "?")); - //subs.push_str(&(hex::encode(ta.2.to_bytes()) + "!")); s_tokens.push_str(&ta.to_string()); s_tokens.push('!'); } @@ -254,14 +247,6 @@ impl std::str::FromStr for RWDTxData { let rwds: Vec<&str> = slice[0].split('!').collect(); for rwd in rwds { rewards.push(RewardHandle::from(rwd.to_string())); - /* - let rwd_slice: Vec<&str> = token.split('?').collect(); - tokens.push(( - clib::PolicyID::from_bytes(hex::decode(token_slice[0])?)?, - clib::AssetName::from_bytes(hex::decode(token_slice[1])?)?, - cutils::BigNum::from_bytes(hex::decode(token_slice[2])?)?, - )) - */ } debug!("Tokens: {:?}", rewards); @@ -301,11 +286,9 @@ impl std::str::FromStr for RWDTxData { reward_utxos: token_utxos, }) } else { - Err(MurinError::new( - //std::io::Error::new( - // std::io::ErrorKind::InvalidData, - &format!("Error the provided string '{src}' cannot be parsed into 'RWDTxData' "), - )) + Err(MurinError::new(&format!( + "Error the provided string '{src}' cannot be parsed into 'RWDTxData' " + ))) } } } diff --git a/drasil-murin/src/txbuilder/stdtx/build_cpo.rs b/drasil-murin/src/txbuilder/stdtx/build_cpo.rs index 7e2f53b9..c6a84f09 100644 --- a/drasil-murin/src/txbuilder/stdtx/build_cpo.rs +++ b/drasil-murin/src/txbuilder/stdtx/build_cpo.rs @@ -11,7 +11,6 @@ use crate::error::MurinError; use crate::txbuilder::{input_selection, TxBO}; use crate::{PerformTxb, TxData}; -// One Shot Minter Builder Type #[derive(Debug, Clone)] pub struct AtCPOBuilder<'a> { pub txo_values: Vec<( diff --git a/drasil-sleipnir/Cargo.toml b/drasil-sleipnir/Cargo.toml index 346e2eb8..f66ffb13 100644 --- a/drasil-sleipnir/Cargo.toml +++ b/drasil-sleipnir/Cargo.toml @@ -5,8 +5,8 @@ edition = "2021" description = "Drasil Blockchain Application Framework - Client Portal Library" repository = "https://github.com/Sbcdn/drasil.git" documentation = "https://docs.drasil.io" -license = "LICENSE_GPL.md" -readme = "README.md" +license = "https://github.com/Sbcdn/drasil/blob/main/LICENSE.md" +readme = "https://github.com/Sbcdn/drasil/blob/main/README.md" authors = ["Torben Poguntke "] [dependencies] @@ -33,9 +33,3 @@ drasil-gungnir = { path = "../drasil-gungnir", version = "0.1.0" } drasil-hugin = { path = "../drasil-hugin", version = "0.1.0" } drasil-dvltath = { path = "../drasil-dvltath", version = "0.1.0" } -[features] -clib = ["structopt"] - -[[bin]] -name = "create_mintpolicy" -required-features = ["clib"] diff --git a/drasil-sleipnir/src/apiauth/mod.rs b/drasil-sleipnir/src/apiauth/mod.rs index de6f7e46..7bdf6581 100644 --- a/drasil-sleipnir/src/apiauth/mod.rs +++ b/drasil-sleipnir/src/apiauth/mod.rs @@ -46,9 +46,7 @@ pub struct ApiClaims { pub fn create_jwt(uid: &i64, duration: Option) -> Result { let user = drasil_hugin::database::TBDrasilUser::get_user_by_user_id(uid)?; - if !user.email_verified - //&& check_identification(u.identification) - { + if !user.email_verified { return Err(SleipnirError::new("invalid user")); } diff --git a/drasil-sleipnir/src/bin/create_mintpolicy.rs b/drasil-sleipnir/src/bin/create_mintpolicy.rs deleted file mode 100644 index beb4c637..00000000 --- a/drasil-sleipnir/src/bin/create_mintpolicy.rs +++ /dev/null @@ -1,76 +0,0 @@ -use chrono::{NaiveDateTime, Utc}; -use drasil_sleipnir::*; -use std::str::FromStr; -#[cfg(feature = "clib")] -use structopt::StructOpt; - -#[derive(Debug, StructOpt)] -#[structopt( - name = "create minting policy", - about = "Creates a minting policy contract" -)] -struct Opt { - //#[structopt(short, long, about="for stdout output set true")] - //output: Option, - #[structopt(short, long, about = "User id as integer")] - user: i32, - - #[structopt(short, long, about = "Optional: Testnet -> true")] - network: Option, - - #[structopt( - short, - long, - about = "Optional: Wallet Bech32-Address which needs to sign the mint" - )] - signer: Option, - - #[structopt( - short, - long, - about = "Optionla: Date until for timelocking the policy-id" - )] - timelock: Option, -} - -/* - pub fingerprint : String, - pub policy_id : String, - pub tokenname : String, - pub contract_id : i64, - pub user_id : i64, - pub vesting_period : DateTime, - pub pools : Vec::, - pub mode : Calculationmode, - pub equation : String, - pub start_epoch : i64, - pub end_epoch : Option, - pub modificator_equ : Option, -*/ -fn main() -> Result<(), SleipnirError> { - //dotenv::dotenv().ok(); - //let database_url = env::var("DRASIL_REWARD_DB")?; - let opt = Opt::from_args(); - - let mut vd = None; - if let Some(date) = opt.timelock { - vd = Some(chrono::DateTime::::from_utc( - NaiveDateTime::parse_from_str(&date, "%Y-%m-%d %H:%M:%S")?, - Utc, - )); - } - - let mut signer = None; - if let Some(a) = opt.signer { - signer = Some(murin::clib::address::Address::from_bech32(&a)?); - } - - let mut network = murin::clib::NetworkIdKind::Mainnet; - if let Some(_) = opt.network { - network = murin::clib::NetworkIdKind::Testnet; - } - - sleipnir::minting::create_policy_script(network, opt.user, signer, vd)?; - - Ok(()) -} diff --git a/drasil-sleipnir/src/minting/api.rs b/drasil-sleipnir/src/minting/api.rs index 38cdab45..0fd26f31 100644 --- a/drasil-sleipnir/src/minting/api.rs +++ b/drasil-sleipnir/src/minting/api.rs @@ -88,7 +88,6 @@ pub async fn import_nfts_from_csv_metadata( let mut trdr = csv::Reader::from_reader(csv); let n = trdr.records().count(); log::debug!("Count: {:?}", n); - //log::debug!("Reader has headers: {:?}", rdr.has_headers()); let mut counter = 0; for result in rdr.records() { log::debug!("A Record was found: {:?}", result); @@ -124,7 +123,6 @@ pub async fn import_from_asset_metadata( mpid: i64, meta: Vec, ) -> Result, SleipnirError> { - //let gconn = &mut drasil_gungnir::establish_connection()?; let mint_project = MintProject::get_mintproject_by_id(mpid)?; println!("Try to find contract..."); let mint_contract = @@ -133,10 +131,7 @@ pub async fn import_from_asset_metadata( let mut nfts = Vec::::new(); for m in meta { let nft_id = m.tokenname.clone(); - //find_numbers(m.name.as_ref().unwrap())?; - //if nft_id.is_empty() { - // nft_id = m.tokenname.clone(); - //} + let asset = m.clone(); let nft = Nft::create_nft( &mint_project.nft_table_name, @@ -179,47 +174,3 @@ mod tests { println!("Imported NFTs"); } } -/* -\metadata -"{ - ""myassetname_utf8"" : { - ""name"":""myassetname_utf8"", - ""image"":""bafybeihcyruaeza7uyjd6ugicbcrqumejf6uf353e5etdkhotqffwtguva"", - ""mediaType"":""image/png"", - ""description"":""My Descritption for this NFT"", - ""files"":[ - { - ""name"":""myfilename1"", - ""mediaType"":""file/zip"", - ""src"": [""mySourcePath/file.zip""] - },{ - ""name"":""myfilename2"", - ""mediaType"":""video/mov"", - ""src"": [""mySourcePath/vid.mov""] - } - ], - ""other"":""properties"", - ""traits"":[""trait1"",""trait2"",""trait3"",""trait4""] - }, - - ""6d7961737365746e616d655f62696e617279"" : { - ""name"":""myassetname_binary"", - ""image"":""bafybeihcyruaeza7uyjd6ugicbcrqumejf6uf353e5etdkgotqffwtguva"", - ""mediaType"":""image/png"", - ""description"":""My Descritption for this NFT"", - ""files"":[ - { - ""name"":""myfilename1"", - ""mediaType"":""file/zip"", - ""src"": [""mySourcePath/file.zip""] - },{ - ""name"":""myfilename2"", - ""mediaType"":""video/mov"", - ""src"": [""mySourcePath/vid.mov""] - } - ], - ""other"":""properties"", - ""traits"":[""trait1"",""trait2"",""trait3"",""trait4"",""trait5"",""trait6"",""trait7"",""trait8""] - } -}" -*/ diff --git a/drasil-sleipnir/src/minting/mod.rs b/drasil-sleipnir/src/minting/mod.rs index 93f268fd..a71e1bef 100644 --- a/drasil-sleipnir/src/minting/mod.rs +++ b/drasil-sleipnir/src/minting/mod.rs @@ -11,7 +11,6 @@ pub async fn create_policy_script( user_id: i64, mint_signer: Option, time_constraint: Option>, - //contract_type : String, ) -> Result { // create rwd wallet & contract diff --git a/jobs/freki/Cargo.toml b/jobs/freki/Cargo.toml index cf9cfb80..3ba80b98 100644 --- a/jobs/freki/Cargo.toml +++ b/jobs/freki/Cargo.toml @@ -4,9 +4,9 @@ description = "Drasil Blockchain Application Framework - Reward Calculator" documentation = "https://docs.drasil.io" edition = "2021" homepage = "https://www.drasil.io" -license = "LICENSE.md" +license = "https://github.com/Sbcdn/drasil/blob/main/LICENSE.md" +readme = "https://github.com/Sbcdn/drasil/blob/main/README.md" name = "freki" -readme = "README.md" repository = "https://github.com/Sbcdn/freki.git" version = "0.1.0" diff --git a/jobs/utxopti/Cargo.toml b/jobs/utxopti/Cargo.toml index 340d1e86..d1e5e0c9 100644 --- a/jobs/utxopti/Cargo.toml +++ b/jobs/utxopti/Cargo.toml @@ -6,8 +6,8 @@ description = "Drasil Blockchain Application Framework - UTxO Optimizer" repository = "https://github.com/Sbcdn/freki.git" homepage = "https://www.drasil.io" documentation = "https://docs.drasil.io" -license = "LICENSE.md" -readme = "README.md" +license = "https://github.com/Sbcdn/drasil/blob/main/LICENSE.md" +readme = "https://github.com/Sbcdn/drasil/blob/main/README.md" authors = ["Torben Poguntke "] [dependencies] diff --git a/jobs/utxopti/src/lib.rs b/jobs/utxopti/src/lib.rs index 5f2a0b28..05097989 100644 --- a/jobs/utxopti/src/lib.rs +++ b/jobs/utxopti/src/lib.rs @@ -1,5 +1,4 @@ mod error; -mod models; use drasil_murin::cardano::supporting_functions; use drasil_murin::cardano::{self, Tokens, TransactionUnspentOutputs}; @@ -58,14 +57,7 @@ pub async fn optimize(addr: String, uid: i64, cid: i64) -> Result<()> { log::debug!("\nTransactions: \n"); for tx in transactions { log::debug!("Tx: for {:?}\n{}", &contract.address, tx.0.to_hex()); - let txh = submit_tx( - tx.0, - tx.1, - contract.user_id, - contract.contract_id, - //contract.version, - ) - .await?; + let txh = submit_tx(tx.0, tx.1, contract.user_id, contract.contract_id).await?; txhs.push(txh); } log::debug!("\n TxHashes for: {:?}, {:?}", &contract.address, txhs); @@ -78,7 +70,6 @@ async fn submit_tx( used_utxos: TransactionUnspentOutputs, uid: i64, cid: i64, - //version: f32, ) -> Result { let bld_tx = supporting_functions::tx_output_data( transaction.body(), @@ -135,7 +126,6 @@ fn reallocate_tokens( drasil_murin::clib::Transaction, drasil_murin::TransactionUnspentOutputs, )>::new(); - //let ada = t_utxos.coin_sum(); let (std_value, minutxo, utxo_count) = get_values_and_tamt_per_utxo(tokens, liquidity); log::trace!("\n\nTUTXO: BEFORE FILTER: \n{:?}\n\n", t_utxos); let set = t_utxos.filter_values(&std_value, Some(20))?; @@ -161,7 +151,6 @@ fn get_values_and_tamt_per_utxo( drasil_murin::clib::utils::BigNum, u64, ) { - //let max_token = let max_token = tokens .iter() .find(|n| { @@ -195,14 +184,6 @@ fn get_values_and_tamt_per_utxo( (std_value, minutxo, utxo_count) } -/* -struct TxBuilderOut { - utxos: drasil_murin::TransactionUnspentOutputs, - std_value: drasil_murin::clib::utils::Value, - utxo_amt: u64, - transactions: Vec<(drasil_murin::clib::Transaction, drasil_murin::TransactionUnspentOutputs)>, -} -*/ fn txbuilder( utxos: &mut drasil_murin::TransactionUnspentOutputs, std_value: &drasil_murin::clib::utils::Value, @@ -226,20 +207,9 @@ fn txbuilder( log::debug!("Continue building transactions"); let (tx, used_utxos, _new_utxo_amt) = make_new_tx(utxos, std_value, &utxo_amt, addr, script)?; - //.expect("Could not create transaction"); utxos.delete_set(&used_utxos); transactions.push((tx, used_utxos.clone())); - Ok( - (), /* - txbuilder( - &mut used_utxos, - std_value, - new_utxo_amt, - transactions, - addr, - script, - )? */ - ) + Ok(()) } } } @@ -435,7 +405,6 @@ fn finalize_tx( tmp_txb.set_network_id(&network); let tmp_transaction = drasil_murin::clib::Transaction::new(&tmp_txb, &txw, None); let fee = calc_txfee(&tmp_transaction, &a, &b, ex_unit_price, &steps, &mem, true); - //fee.checked_add(&drasil_murin::clib::utils::to_bignum(64))?; let mut outputs = outputs.clone(); outputs.add(&drasil_murin::clib::TransactionOutput::new( addr, diff --git a/jobs/utxopti/src/models.rs b/jobs/utxopti/src/models.rs deleted file mode 100644 index e69de29b..00000000 diff --git a/services/frigg/Cargo.toml b/services/frigg/Cargo.toml index 8027f7da..061fb293 100644 --- a/services/frigg/Cargo.toml +++ b/services/frigg/Cargo.toml @@ -6,8 +6,8 @@ description = "Drasil Blockchain Application Framework - Client Portal API" repository = "https://github.com/Sbcdn/frigg.git" homepage = "https://www.drasil.io" documentation = "https://docs.drasil.io" -license = "LICENSE.md" -readme = "README.md" +license = "https://github.com/Sbcdn/drasil/blob/main/LICENSE.md" +readme = "https://github.com/Sbcdn/drasil/blob/main/README.md" authors = ["Torben Poguntke "] diff --git a/services/frigg/src/handler/mint.rs b/services/frigg/src/handler/mint.rs index 57d4f4cf..f27f50ef 100644 --- a/services/frigg/src/handler/mint.rs +++ b/services/frigg/src/handler/mint.rs @@ -27,21 +27,6 @@ pub async fn entrp_create_nfts_from_csv( params: ImportNFTsfromCSV, ) -> WebResult { let user = get_user_from_string(&uid).await?; - /* - let i = sleipnir::minting::api::import_nfts_from_csv_metadata( - &hex::decode(params.csv_hex).unwrap(), - user, - params.project_id, - ) - .await?; - - //Ok(warp::reply::with_status( - // warp::reply::json(&json!({ "imported": i })), - // warp::http::StatusCode::CREATED, - //)); - */ - //////////////////// - // let payload = serde_json::json!(payload).to_string(); let job = drasil_sleipnir::jobs::Job { drasil_user_id: user, @@ -104,37 +89,6 @@ pub async fn entrp_create_nfts_from_csv_s( ) -> WebResult { let user = get_user_from_string(&uid).await?; - //let mut request_buf = String::new(); - //let mut file = File::create("/files/import_tmp").unwrap(); - //file.write_all(body.as_ref()).unwrap(); - //file.read_to_string(&mut request_buf).unwrap(); - /* - let mut pinned_stream = Box::pin(body); - while pinned_stream.has_remaining() { - let r = pinned_stream.remaining(); - let b = pinned_stream.bytes(); - let mut i = 0; - for (j, e) in b.enumerate() { - if let Ok(byte) = e { - request_buf.push(byte) - } - i = j; - log::debug!("{}", i); - } - if r > 0 { - pinned_stream.advance(i); - } else { - break; - } - //request_buf.extend::<&[u8]>(body.as_ref()); - } - */ - //let mut f = File::open(file).expect("no file found"); - //let metadata = file.metadata().expect("unable to read metadata"); - - //let mut buffer = body.bytes(); - //file.read_to_end(&mut buffer).expect("buffer overflow"); - log::debug!("Request buffer: {:?}", &body); let i = drasil_sleipnir::minting::api::import_nfts_from_csv_metadata(body.as_ref(), user, mid) .await?; diff --git a/services/heimdallr/Cargo.toml b/services/heimdallr/Cargo.toml index 6665197b..55c8b577 100644 --- a/services/heimdallr/Cargo.toml +++ b/services/heimdallr/Cargo.toml @@ -6,8 +6,8 @@ description = "Drasil Blockchain Application Framework - Application Gateway" repository = "https://github.com/Sbcdn/heimdallr.git" homepage = "https://www.drasil.io" documentation = "https://docs.drasil.io" -license = "LICENSE.md" -readme = "README.md" +license = "https://github.com/Sbcdn/drasil/blob/main/LICENSE.md" +readme = "https://github.com/Sbcdn/drasil/blob/main/README.md" authors = ["Torben Poguntke "] diff --git a/services/heimdallr/src/clientapi/handlers.rs b/services/heimdallr/src/clientapi/handlers.rs index d1d7a0da..4aad26ed 100644 --- a/services/heimdallr/src/clientapi/handlers.rs +++ b/services/heimdallr/src/clientapi/handlers.rs @@ -4,8 +4,8 @@ use std::str::FromStr; use drasil_hugin::client::{connect, Client}; use drasil_hugin::datamodel::models::{ - ContractAction, ContractType, MarketplaceActions, MultiSigType, OneShotReturn, ReturnError, - StdTxType, TransactionPattern, TxHash, UnsignedTransaction, + ContractAction, ContractType, MultiSigType, OneShotReturn, ReturnError, StdTxType, + TransactionPattern, TxHash, UnsignedTransaction, }; use drasil_hugin::{ BuildContract, BuildMultiSig, BuildStdTx, FinalizeContract, FinalizeMultiSig, FinalizeStdTx, diff --git a/services/loki/Cargo.toml b/services/loki/Cargo.toml index 86bfa403..851e171d 100644 --- a/services/loki/Cargo.toml +++ b/services/loki/Cargo.toml @@ -6,8 +6,8 @@ description = "Drasil Blockchain Application Framework - Websocket Interface" repository = "https://github.com/Sbcdn/drasil.git" homepage = "https://www.drasil.io" documentation = "https://docs.drasil.io" -license = "LICENSE.md" -readme = "README.md" +license = "https://github.com/Sbcdn/drasil/blob/main/LICENSE.md" +readme = "https://github.com/Sbcdn/drasil/blob/main/README.md" authors = ["Torben Poguntke "] [dependencies] diff --git a/services/loki/src/auth.rs b/services/loki/src/auth.rs index 0ee36f96..b39b26b1 100644 --- a/services/loki/src/auth.rs +++ b/services/loki/src/auth.rs @@ -17,10 +17,7 @@ struct ApiClaims { exp: usize, } -pub(crate) async fn authorize( - headers: HeaderMap, - //body: bytes::Bytes, -) -> Result { +pub(crate) async fn authorize(headers: HeaderMap) -> Result { let publ = std::env::var("JWT_PUB_KEY") .map_err(|_| Error::Custom("env jwt pub not existing".to_string()))?; let publ = publ.into_bytes(); @@ -72,23 +69,3 @@ fn jwt_from_header(headers: &HeaderMap) -> Result Result { - let expiration = Utc::now() - .checked_add_signed(chrono::Duration::seconds(1800)) - .expect("valid timestamp") - .timestamp(); - - let claims = ApiClaims { - sub: uid.to_owned(), - exp: expiration as usize, - }; - let header = Header::new(Algorithm::ES256); - let key = std::env::var("JWT_KEY") - .map_err(|_| Error::Custom("env jwt key path not existing".to_string()))?; - let key = key.into_bytes(); //std::fs::read(key).expect("Could not read jwt key file"); - encode(&header, &claims, &EncodingKey::from_ec_pem(&key).unwrap()) - .map_err(|_| Error::JWTTokenCreationError) -} -*/ diff --git a/services/loki/src/error.rs b/services/loki/src/error.rs index 25f8ff72..c0c7bc0c 100644 --- a/services/loki/src/error.rs +++ b/services/loki/src/error.rs @@ -12,8 +12,6 @@ pub enum Error { InvalidAuthHeaderError, #[error("internal error: {:?}", self)] Custom(String), - // #[error("could not create jwt token")] - // JWTTokenCreationError, #[error("rmq error: {0}")] RMQError(#[from] lapin::Error), #[error("rmq pool error: {0}")] diff --git a/services/loki/src/handlers.rs b/services/loki/src/handlers.rs index a9756281..70f7912d 100644 --- a/services/loki/src/handlers.rs +++ b/services/loki/src/handlers.rs @@ -108,7 +108,6 @@ async fn client_msg( }; match serde_json::from_str(message).unwrap() { - //"alive" | "alive\n" WSCom::Alive => { let locked = clients.lock().await; if let Some(v) = locked.get(&client_id) { @@ -139,6 +138,6 @@ async fn client_msg( } } } - } // _ => (), + } } } diff --git a/services/odin/Cargo.toml b/services/odin/Cargo.toml index ab194b97..1755705d 100644 --- a/services/odin/Cargo.toml +++ b/services/odin/Cargo.toml @@ -6,8 +6,8 @@ description = "Drasil Blockchain Application Framework - Drasil Core Runner" repository = "https://github.com/Sbcdn/odin.git" homepage = "https://www.drasil.io" documentation = "https://docs.drasil.io" -license = "LICENSE.md" -readme = "README.md" +license = "https://github.com/Sbcdn/drasil/blob/main/LICENSE.md" +readme = "https://github.com/Sbcdn/drasil/blob/main/README.md" authors = ["Torben Poguntke "] diff --git a/services/vidar/Cargo.toml b/services/vidar/Cargo.toml index 208815d3..4a9c2a59 100644 --- a/services/vidar/Cargo.toml +++ b/services/vidar/Cargo.toml @@ -6,8 +6,8 @@ description = "Drasil Blockchain Application Framework - Reward Information API" repository = "https://github.com/Sbcdn/vidar.git" homepage = "https://www.drasil.io" documentation = "https://docs.drasil.io" -license = "LICENSE.md" -readme = "README.md" +license = "https://github.com/Sbcdn/drasil/blob/main/LICENSE.md" +readme = "https://github.com/Sbcdn/drasil/blob/main/README.md" authors = ["Torben Poguntke "] [dependencies] diff --git a/worker/geri/Cargo.toml b/worker/geri/Cargo.toml index 9ddd76e6..f703196d 100644 --- a/worker/geri/Cargo.toml +++ b/worker/geri/Cargo.toml @@ -6,8 +6,8 @@ description = "Drasil Blockchain Application Framework - Redis Blockchain Transa repository = "https://github.com/Sbcdn/geri.git" homepage = "https://www.drasil.io" documentation = "https://docs.drasil.io" -license = "LICENSE.md" -readme = "README.md" +license = "https://github.com/Sbcdn/drasil/blob/main/LICENSE.md" +readme = "https://github.com/Sbcdn/drasil/blob/main/README.md" authors = ["Torben Poguntke "] [dependencies] diff --git a/worker/geri/src/main.rs b/worker/geri/src/main.rs index 4ad72903..3b07d850 100644 --- a/worker/geri/src/main.rs +++ b/worker/geri/src/main.rs @@ -123,8 +123,6 @@ fn run_stream_trimmer(stream: String, maxlen: i32) -> Result<()> { } Ok(()) } - -//#[tokio::main] pub fn main() -> Result<()> { use std::{thread, time}; pretty_env_logger::init(); diff --git a/worker/jobs/Cargo.toml b/worker/jobs/Cargo.toml index be59234a..cfbbc8a9 100644 --- a/worker/jobs/Cargo.toml +++ b/worker/jobs/Cargo.toml @@ -6,8 +6,8 @@ description = "Drasil Blockchain Application Framework - Job Processor for queue repository = "https://github.com/Sbcdn/drasil.git" homepage = "https://www.drasil.io" documentation = "https://docs.drasil.io" -license = "LICENSE.md" -readme = "README.md" +license = "https://github.com/Sbcdn/drasil/blob/main/LICENSE.md" +readme = "https://github.com/Sbcdn/drasil/blob/main/README.md" authors = ["Torben Poguntke "] [dependencies] diff --git a/worker/work_loki/Cargo.toml b/worker/work_loki/Cargo.toml index efa88a70..cd1ef04f 100644 --- a/worker/work_loki/Cargo.toml +++ b/worker/work_loki/Cargo.toml @@ -6,8 +6,8 @@ description = "Drasil Blockchain Application Framework - Queue worker for Loki w repository = "https://github.com/Sbcdn/drasil.git" homepage = "https://www.drasil.io" documentation = "https://docs.drasil.io" -license = "LICENSE.md" -readme = "README.md" +license = "https://github.com/Sbcdn/drasil/blob/main/LICENSE.md" +readme = "https://github.com/Sbcdn/drasil/blob/main/README.md" authors = ["Torben Poguntke "] [dependencies] diff --git a/worker/work_loki/src/handlers.rs b/worker/work_loki/src/handlers.rs deleted file mode 100644 index e69de29b..00000000 diff --git a/worker/work_loki/src/main.rs b/worker/work_loki/src/main.rs index 52a0848f..89c4f60c 100644 --- a/worker/work_loki/src/main.rs +++ b/worker/work_loki/src/main.rs @@ -1,7 +1,6 @@ extern crate pretty_env_logger; mod error; -mod handlers; mod models; use std::env;