Normalize line endings

This commit is contained in:
Anynomous
2025-09-18 14:51:29 +02:00
parent aed932726c
commit 86de7c6bcd
165 changed files with 0 additions and 53523 deletions
-73
View File
@@ -1,73 +0,0 @@
[package]
name = "grin_wallet_libwallet"
version = "5.4.0-alpha.1"
authors = ["Grin Developers <mimblewimble@lists.launchpad.net>"]
description = "Simple, private and scalable cryptocurrency implementation based on the MimbleWimble chain format."
license = "Apache-2.0"
repository = "https://github.com/mimblewimble/grin-wallet"
keywords = [ "crypto", "grin", "mimblewimble" ]
exclude = ["**/*.grin", "**/*.grin2"]
#build = "src/build/build.rs"
edition = "2018"
[dependencies]
blake2-rfc = "0.2"
rand = "0.6"
serde = "1"
serde_derive = "1"
serde_json = "1"
log = "0.4"
uuid = { version = "0.8", features = ["serde", "v4"] }
chrono = { version = "0.4.11", features = ["serde"] }
lazy_static = "1"
strum = "0.18"
strum_macros = "0.18"
thiserror = "1"
ed25519-dalek = "1.0.0-pre.4"
x25519-dalek = "0.6"
base64 = "0.9"
regex = "1.3"
sha2 = "0.10.0"
bs58 = "0.3"
age = "0.7"
curve25519-dalek = "2.1"
secrecy = "0.6"
bech32 = "0.7"
byteorder = "1.3"
num-bigint = "0.2"
#mwixnet onion
chacha20 = "0.8.1"
hmac = { version = "0.12.0", features = ["std"]}
grin_wallet_util = { path = "../util", version = "5.4.0-alpha.1" }
grin_wallet_config = { path = "../config", version = "5.4.0-alpha.1" }
##### Grin Imports
# For Release
grin_core = "5.3.3"
grin_keychain = "5.3.3"
grin_util = "5.3.3"
grin_store = "5.3.3"
# For beta release
# grin_core = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3"}
# grin_keychain = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
# grin_util = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
# grin_store = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
# For bleeding edge
# grin_core = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_keychain = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_util = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_store = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# For local testing
# grin_core = { path = "../../grin/core"}
# grin_keychain = { path = "../../grin/keychain"}
# grin_util = { path = "../../grin/util"}
# grin_store = { path = "../../grin/store"}
#####
-49
View File
@@ -1,49 +0,0 @@
// Copyright 2021 The Grin Develope;
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Functions defining wallet 'addresses', i.e. ed2559 keys based on
//! a derivation path
use crate::grin_util::secp::key::SecretKey;
use crate::Error;
use grin_keychain::{ChildNumber, Identifier, Keychain, SwitchCommitmentType};
use crate::blake2::blake2b::blake2b;
/// Derive a secret key given a derivation path and index
pub fn address_from_derivation_path<K>(
keychain: &K,
parent_key_id: &Identifier,
index: u32,
) -> Result<SecretKey, Error>
where
K: Keychain,
{
let mut key_path = parent_key_id.to_path();
// An output derivation for acct m/0
// is m/0/0/0, m/0/0/1 (for instance), m/1 is m/1/0/0, m/1/0/1
// Address generation path should be
// for m/0: m/0/1/0, m/0/1/1
// for m/1: m/1/1/0, m/1/1/1
key_path.path[1] = ChildNumber::from(1);
key_path.depth += 1;
key_path.path[key_path.depth as usize - 1] = ChildNumber::from(index);
let key_id = Identifier::from_path(&key_path);
let sec_key = keychain.derive_key(0, &key_id, SwitchCommitmentType::None)?;
let hashed = blake2b(32, &[], &sec_key.0[..]);
Ok(SecretKey::from_slice(
&keychain.secp(),
&hashed.as_bytes()[..],
)?)
}
-27
View File
@@ -1,27 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! lower-level wallet functions which build upon core::libtx to perform wallet
//! operations
#![deny(non_upper_case_globals)]
#![deny(non_camel_case_types)]
#![deny(non_snake_case)]
#![deny(unused_mut)]
#![warn(missing_docs)]
pub mod foreign;
pub mod owner;
pub mod owner_updater;
pub mod types;
-233
View File
@@ -1,233 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Generic implementation of owner API functions
use strum::IntoEnumIterator;
use crate::api_impl::owner::{check_ttl, post_tx};
use crate::grin_core::core::FeeFields;
use crate::grin_keychain::Keychain;
use crate::grin_util::secp::key::SecretKey;
use crate::internal::{selection, tx, updater};
use crate::slate_versions::SlateVersion;
use crate::{
address, BlockFees, CbData, Error, NodeClient, Slate, SlateState, TxLogEntryType, VersionInfo,
WalletBackend,
};
use super::owner::tx_lock_outputs;
const FOREIGN_API_VERSION: u16 = 2;
/// Return the version info
pub fn check_version() -> VersionInfo {
VersionInfo {
foreign_api_version: FOREIGN_API_VERSION,
supported_slate_versions: SlateVersion::iter().collect(),
}
}
/// Build a coinbase transaction
pub fn build_coinbase<'a, T: ?Sized, C, K>(
w: &mut T,
keychain_mask: Option<&SecretKey>,
block_fees: &BlockFees,
test_mode: bool,
) -> Result<CbData, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
updater::build_coinbase(&mut *w, keychain_mask, block_fees, test_mode)
}
/// Receive a tx as recipient
pub fn receive_tx<'a, T: ?Sized, C, K>(
w: &mut T,
keychain_mask: Option<&SecretKey>,
slate: &Slate,
dest_acct_name: Option<&str>,
use_test_rng: bool,
) -> Result<Slate, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let mut ret_slate = slate.clone();
check_ttl(w, &ret_slate)?;
let parent_key_id = match dest_acct_name {
Some(d) => {
let pm = w.get_acct_path(d.to_owned())?;
match pm {
Some(p) => p.path,
None => w.parent_key_id(),
}
}
None => w.parent_key_id(),
};
// Don't do this multiple times
let tx = updater::retrieve_txs(
&mut *w,
None,
Some(ret_slate.id),
None,
Some(&parent_key_id),
use_test_rng,
)?;
for t in &tx {
if t.tx_type == TxLogEntryType::TxReceived {
return Err(Error::TransactionAlreadyReceived(ret_slate.id.to_string()));
}
}
ret_slate.tx = Some(Slate::empty_transaction());
let height = w.last_confirmed_height()?;
let keychain = w.keychain(keychain_mask)?;
let context = tx::add_output_to_slate(
&mut *w,
keychain_mask,
&mut ret_slate,
height,
&parent_key_id,
false,
use_test_rng,
)?;
// Add our contribution to the offset
ret_slate.adjust_offset(&keychain, &context)?;
let excess = ret_slate.calc_excess(keychain.secp())?;
if let Some(ref mut p) = ret_slate.payment_proof {
let sig = tx::create_payment_proof_signature(
ret_slate.amount,
&excess,
p.sender_address,
address::address_from_derivation_path(&keychain, &parent_key_id, 0)?,
)?;
p.receiver_signature = Some(sig);
}
ret_slate.amount = 0;
ret_slate.fee_fields = FeeFields::zero();
ret_slate.remove_other_sigdata(&keychain, &context.sec_nonce, &context.sec_key)?;
ret_slate.state = SlateState::Standard2;
Ok(ret_slate)
}
/// Receive a tx that this wallet has issued
pub fn finalize_tx<'a, T: ?Sized, C, K>(
w: &mut T,
keychain_mask: Option<&SecretKey>,
slate: &Slate,
post_automatically: bool,
) -> Result<Slate, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let mut sl = slate.clone();
let mut context = w.get_private_context(keychain_mask, sl.id.as_bytes())?;
check_ttl(w, &sl)?;
if sl.state == SlateState::Invoice2 {
// Add our contribution to the offset
sl.adjust_offset(&w.keychain(keychain_mask)?, &context)?;
let mut temp_ctx = context.clone();
temp_ctx.sec_key = context.initial_sec_key.clone();
temp_ctx.sec_nonce = context.initial_sec_nonce.clone();
selection::repopulate_tx(&mut *w, keychain_mask, &mut sl, &temp_ctx, false)?;
tx::complete_tx(&mut *w, keychain_mask, &mut sl, &context)?;
tx::update_stored_tx(&mut *w, keychain_mask, &context, &mut sl, true)?;
{
let mut batch = w.batch(keychain_mask)?;
batch.delete_private_context(sl.id.as_bytes())?;
batch.commit()?;
}
sl.state = SlateState::Invoice3;
sl.amount = 0;
} else if sl.state == SlateState::Standard2 {
let keychain = w.keychain(keychain_mask)?;
let parent_key_id = w.parent_key_id();
if let Some(args) = context.late_lock_args.take() {
// Transaction was late locked, select inputs+change now
// and insert into original context
let current_height = w.w2n_client().get_chain_tip()?.0;
let mut temp_sl =
tx::new_tx_slate(&mut *w, context.amount, false, 2, false, args.ttl_blocks)?;
let temp_context = selection::build_send_tx(
w,
&keychain,
keychain_mask,
&mut temp_sl,
current_height,
args.minimum_confirmations,
args.max_outputs as usize,
args.num_change_outputs as usize,
args.selection_strategy_is_use_all,
Some(context.fee.map(|f| f.fee()).unwrap_or(0)),
parent_key_id.clone(),
false,
true,
false,
)?;
// Add inputs and outputs to original context
context.input_ids = temp_context.input_ids;
context.output_ids = temp_context.output_ids;
// Store the updated context
{
let mut batch = w.batch(keychain_mask)?;
batch.save_private_context(sl.id.as_bytes(), &context)?;
batch.commit()?;
}
// Now do the actual locking
tx_lock_outputs(w, keychain_mask, &sl)?;
}
// Add our contribution to the offset
sl.adjust_offset(&keychain, &context)?;
selection::repopulate_tx(&mut *w, keychain_mask, &mut sl, &context, true)?;
tx::complete_tx(&mut *w, keychain_mask, &mut sl, &context)?;
tx::verify_slate_payment_proof(&mut *w, keychain_mask, &parent_key_id, &context, &sl)?;
tx::update_stored_tx(&mut *w, keychain_mask, &context, &sl, false)?;
{
let mut batch = w.batch(keychain_mask)?;
batch.delete_private_context(sl.id.as_bytes())?;
batch.commit()?;
}
sl.state = SlateState::Standard3;
sl.amount = 0;
} else {
return Err(Error::SlateState);
}
if post_automatically {
post_tx(w.w2n_client(), sl.tx_or_err()?, true)?;
}
Ok(sl)
}
File diff suppressed because it is too large Load Diff
-146
View File
@@ -1,146 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A threaded persistent Updater that can be controlled by a grin wallet
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use crate::grin_keychain::Keychain;
use crate::grin_util::secp::key::SecretKey;
use crate::grin_util::Mutex;
use crate::api_impl::owner;
use crate::types::NodeClient;
use crate::Error;
use crate::{WalletInst, WalletLCProvider};
const MESSAGE_QUEUE_MAX_LEN: usize = 10_000;
/// Update status messages which can be returned to listening clients
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum StatusMessage {
/// Wallet is performing a regular update, matching the UTXO set against
/// current wallet outputs
UpdatingOutputs(String),
/// Wallet is updating transactions, potentially retrieving transactions
/// by kernel if needed
UpdatingTransactions(String),
/// Warning that the wallet is about to perform a full UTXO scan
FullScanWarn(String),
/// Status and percentage complete messages returned during the
/// scanning process
Scanning(String, u8),
/// UTXO scanning is complete
ScanningComplete(String),
/// Warning of issues that may have occured during an update
UpdateWarning(String),
}
/// Helper function that starts a simple log thread for updater messages
pub fn start_updater_log_thread(
rx: Receiver<StatusMessage>,
queue: Arc<Mutex<Vec<StatusMessage>>>,
) -> Result<(), Error> {
let _ = thread::Builder::new()
.name("wallet-updater-status".to_string())
.spawn(move || {
while let Ok(m) = rx.recv() {
// save to our message queue to be read by other consumers
{
let mut q = queue.lock();
q.insert(0, m.clone());
while q.len() > MESSAGE_QUEUE_MAX_LEN {
q.pop();
}
}
match m {
StatusMessage::UpdatingOutputs(s) => debug!("{}", s),
StatusMessage::UpdatingTransactions(s) => debug!("{}", s),
StatusMessage::FullScanWarn(s) => warn!("{}", s),
StatusMessage::Scanning(s, m) => {
debug!("{}", s);
warn!("Scanning - {}% complete", m);
}
StatusMessage::ScanningComplete(s) => warn!("{}", s),
StatusMessage::UpdateWarning(s) => warn!("{}", s),
}
}
})?;
Ok(())
}
/// Handles and launches a background update thread
pub struct Updater<'a, L, C, K>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
wallet_inst: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
is_running: Arc<AtomicBool>,
}
impl<'a, L, C, K> Updater<'a, L, C, K>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
/// create a new updater
pub fn new(
wallet_inst: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
is_running: Arc<AtomicBool>,
) -> Self {
is_running.store(false, Ordering::Relaxed);
Updater {
wallet_inst,
is_running,
}
}
/// Start the updater at the given frequency
pub fn run(
&self,
frequency: Duration,
keychain_mask: Option<SecretKey>,
status_send_channel: &Option<Sender<StatusMessage>>,
) -> Result<(), Error> {
self.is_running.store(true, Ordering::Relaxed);
loop {
let wallet_opened = {
let mut w_lock = self.wallet_inst.lock();
let w_provider = w_lock.lc_provider()?;
w_provider.wallet_inst().is_ok()
};
// Business goes here
if wallet_opened {
owner::update_wallet_state(
self.wallet_inst.clone(),
(&keychain_mask).as_ref(),
status_send_channel,
false,
)?;
}
if !self.is_running.load(Ordering::Relaxed) {
break;
}
thread::sleep(frequency);
}
Ok(())
}
}
-346
View File
@@ -1,346 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Types specific to the wallet api, mostly argument serialization
use crate::grin_core::core::Output;
use crate::grin_core::libtx::secp_ser;
use crate::grin_keychain::{BlindingFactor, Identifier};
use crate::grin_util::secp::pedersen;
use crate::slate_versions::ser as dalek_ser;
use crate::slate_versions::SlateVersion;
use crate::types::OutputData;
use crate::SlatepackAddress;
use chrono::prelude::*;
use ed25519_dalek::Signature as DalekSignature;
pub use crate::mwixnet::{Hop, MixnetReqCreationParams, SwapReq};
/// Type for storing amounts (in nanogrins).
/// Serializes as a string but can deserialize from a string or u64.
#[derive(Serialize, Deserialize)]
pub struct Amount(#[serde(with = "secp_ser::string_or_u64")] pub u64);
/// V2 Init / Send TX API Args
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct InitTxArgs {
/// The human readable account name from which to draw outputs
/// for the transaction, overriding whatever the active account is as set via the
/// [`set_active_account`](../grin_wallet_api/owner/struct.Owner.html#method.set_active_account) method.
pub src_acct_name: Option<String>,
#[serde(with = "secp_ser::string_or_u64")]
/// The amount to send, in nanogrins. (`1 G = 1_000_000_000nG`)
pub amount: u64,
/// Does the amount include the fee, or will fees be spent in addition to the amount?
pub amount_includes_fee: Option<bool>,
#[serde(with = "secp_ser::string_or_u64")]
/// The minimum number of confirmations an output
/// should have in order to be included in the transaction.
pub minimum_confirmations: u64,
/// By default, the wallet selects as many inputs as possible in a
/// transaction, to reduce the Output set and the fees. The wallet will attempt to spend
/// include up to `max_outputs` in a transaction, however if this is not enough to cover
/// the whole amount, the wallet will include more outputs. This parameter should be considered
/// a soft limit.
pub max_outputs: u32,
/// The target number of change outputs to create in the transaction.
/// The actual number created will be `num_change_outputs` + whatever remainder is needed.
pub num_change_outputs: u32,
/// If `true`, attempt to use up as many outputs as
/// possible to create the transaction, up the 'soft limit' of `max_outputs`. This helps
/// to reduce the size of the UTXO set and the amount of data stored in the wallet, and
/// minimizes fees. This will generally result in many inputs and a large change output(s),
/// usually much larger than the amount being sent. If `false`, the transaction will include
/// as many outputs as are needed to meet the amount, (and no more) starting with the smallest
/// value outputs.
pub selection_strategy_is_use_all: bool,
/// Optionally set the output target slate version (acceptable
/// down to the minimum slate version compatible with the current. If `None` the slate
/// is generated with the latest version.
pub target_slate_version: Option<u16>,
/// Number of blocks from current after which TX should be ignored
#[serde(with = "secp_ser::opt_string_or_u64")]
#[serde(default)]
pub ttl_blocks: Option<u64>,
/// If set, require a payment proof for the particular recipient
#[serde(default)]
pub payment_proof_recipient_address: Option<SlatepackAddress>,
/// If true, just return an estimate of the resulting slate, containing fees and amounts
/// locked without actually locking outputs or creating the transaction. Note if this is set to
/// 'true', the amount field in the slate will contain the total amount locked, not the provided
/// transaction amount
pub estimate_only: Option<bool>,
/// EXPERIMENTAL: if flagged, create the transaction as late-locked, i.e. don't select actual
/// inputs until just before finalization
#[serde(default)]
pub late_lock: Option<bool>,
/// Sender arguments. If present, the underlying function will also attempt to send the
/// transaction to a destination and optionally finalize the result
pub send_args: Option<InitTxSendArgs>,
}
/// Send TX API Args, for convenience functionality that inits the transaction and sends
/// in one go
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct InitTxSendArgs {
/// The destination, contents will depend on the particular method
pub dest: String,
/// Whether to post the transaction if the send and finalize were successful
pub post_tx: bool,
/// Whether to use dandelion when posting. If false, skip the dandelion relay
pub fluff: bool,
/// If set, skip the Slatepack TOR send attempt
pub skip_tor: bool,
}
impl Default for InitTxArgs {
fn default() -> InitTxArgs {
InitTxArgs {
src_acct_name: None,
amount: 0,
amount_includes_fee: None,
minimum_confirmations: 10,
max_outputs: 500,
num_change_outputs: 1,
selection_strategy_is_use_all: true,
target_slate_version: None,
ttl_blocks: None,
estimate_only: Some(false),
payment_proof_recipient_address: None,
late_lock: Some(false),
send_args: None,
}
}
}
/// V2 Issue Invoice Tx Args
#[derive(Clone, Serialize, Deserialize)]
pub struct IssueInvoiceTxArgs {
/// The human readable account name to which the received funds should be added
/// overriding whatever the active account is as set via the
/// [`set_active_account`](../grin_wallet_api/owner/struct.Owner.html#method.set_active_account) method.
pub dest_acct_name: Option<String>,
/// The invoice amount in nanogrins. (`1 G = 1_000_000_000nG`)
#[serde(with = "secp_ser::string_or_u64")]
pub amount: u64,
/// Optionally set the output target slate version (acceptable
/// down to the minimum slate version compatible with the current. If `None` the slate
/// is generated with the latest version.
pub target_slate_version: Option<u16>,
}
impl Default for IssueInvoiceTxArgs {
fn default() -> IssueInvoiceTxArgs {
IssueInvoiceTxArgs {
dest_acct_name: None,
amount: 0,
target_slate_version: None,
}
}
}
/// Sort tx retrieval order
#[derive(Clone, Serialize, Deserialize)]
pub enum RetrieveTxQuerySortOrder {
/// Ascending
Asc,
/// Descending
Desc,
}
/// Valid sort fields for a transaction list retrieval query
#[derive(Clone, Serialize, Deserialize)]
pub enum RetrieveTxQuerySortField {
/// Transaction Id
Id,
/// Creation Timestamp
CreationTimestamp,
/// Confirmation Timestamp
ConfirmationTimestamp,
/// TotalAmount (AmountCredited-AmountDebited)
TotalAmount,
/// Amount Credited
AmountCredited,
/// Amount Debited
AmountDebited,
}
/// Retrieve Transaction List Pagination Arguments
#[derive(Clone, Serialize, Deserialize)]
pub struct RetrieveTxQueryArgs {
/// Retrieve transactions with an id higher than or equal to the given
/// If None, consider items from the first transaction and later
pub min_id: Option<u32>,
/// Retrieve tranactions with an id less than or equal to the given
/// If None, consider items from the last transaction and earlier
pub max_id: Option<u32>,
/// The maximum number of transactions to return
/// if both `before_id_inc` and `after_id_inc` are supplied, this will apply
/// to the before and earlier set
pub limit: Option<u32>,
/// whether to exclude cancelled transactions in the returned set
pub exclude_cancelled: Option<bool>,
/// whether to only consider outstanding transactions
pub include_outstanding_only: Option<bool>,
/// whether to only consider confirmed-only transactions
pub include_confirmed_only: Option<bool>,
/// whether to only consider sent transactions
pub include_sent_only: Option<bool>,
/// whether to only consider received transactions
pub include_received_only: Option<bool>,
/// whether to only consider coinbase transactions
pub include_coinbase_only: Option<bool>,
/// whether to only consider reverted transactions
pub include_reverted_only: Option<bool>,
/// lower bound on the total amount (amount_credited - amount_debited), inclusive
#[serde(with = "secp_ser::opt_string_or_u64")]
#[serde(default)]
pub min_amount: Option<u64>,
/// higher bound on the total amount (amount_credited - amount_debited), inclusive
#[serde(with = "secp_ser::opt_string_or_u64")]
#[serde(default)]
pub max_amount: Option<u64>,
/// lower bound on the creation timestamp, inclusive
pub min_creation_timestamp: Option<DateTime<Utc>>,
/// higher bound on on the creation timestamp, inclusive
pub max_creation_timestamp: Option<DateTime<Utc>>,
/// lower bound on the confirmation timestamp, inclusive
pub min_confirmed_timestamp: Option<DateTime<Utc>>,
/// higher bound on the confirmation timestamp, inclusive
pub max_confirmed_timestamp: Option<DateTime<Utc>>,
/// Field within the tranasction list on which to sort
/// defaults to ID if not present
pub sort_field: Option<RetrieveTxQuerySortField>,
/// Sort order, defaults to ASC if not present (earliest is first)
pub sort_order: Option<RetrieveTxQuerySortOrder>,
}
impl Default for RetrieveTxQueryArgs {
fn default() -> Self {
Self {
min_id: None,
max_id: None,
limit: None,
exclude_cancelled: Some(false),
include_outstanding_only: Some(false),
include_confirmed_only: Some(false),
include_sent_only: Some(false),
include_received_only: Some(false),
include_coinbase_only: Some(false),
include_reverted_only: Some(false),
min_amount: None,
max_amount: None,
min_creation_timestamp: None,
max_creation_timestamp: None,
min_confirmed_timestamp: None,
max_confirmed_timestamp: None,
sort_field: Some(RetrieveTxQuerySortField::Id),
sort_order: Some(RetrieveTxQuerySortOrder::Asc),
}
}
}
/// Fees in block to use for coinbase amount calculation
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BlockFees {
/// fees
#[serde(with = "secp_ser::string_or_u64")]
pub fees: u64,
/// height
#[serde(with = "secp_ser::string_or_u64")]
pub height: u64,
/// key id
pub key_id: Option<Identifier>,
}
impl BlockFees {
/// return key id
pub fn key_id(&self) -> Option<Identifier> {
self.key_id.clone()
}
}
/// Map Outputdata to commits
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct OutputCommitMapping {
/// Output Data
pub output: OutputData,
/// The commit
#[serde(
serialize_with = "secp_ser::as_hex",
deserialize_with = "secp_ser::commitment_from_hex"
)]
pub commit: pedersen::Commitment,
}
/// Node height result
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct NodeHeightResult {
/// Last known height
#[serde(with = "secp_ser::string_or_u64")]
pub height: u64,
/// Hash
pub header_hash: String,
/// Whether this height was updated from the node
pub updated_from_node: bool,
}
/// Version request result
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct VersionInfo {
/// API version
pub foreign_api_version: u16,
/// Slate version
pub supported_slate_versions: Vec<SlateVersion>,
}
/// Packaged Payment Proof
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PaymentProof {
/// Amount
#[serde(with = "secp_ser::string_or_u64")]
pub amount: u64,
/// Kernel Excess
#[serde(
serialize_with = "secp_ser::as_hex",
deserialize_with = "secp_ser::commitment_from_hex"
)]
pub excess: pedersen::Commitment,
/// Recipient Wallet Address
pub recipient_address: SlatepackAddress,
/// Recipient Signature
#[serde(with = "dalek_ser::dalek_sig_serde")]
pub recipient_sig: DalekSignature,
/// Sender Wallet Address
pub sender_address: SlatepackAddress,
/// Sender Signature
#[serde(with = "dalek_ser::dalek_sig_serde")]
pub sender_sig: DalekSignature,
}
/// Build output result
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BuiltOutput {
/// Blinding Factor
#[serde(
serialize_with = "secp_ser::as_hex",
deserialize_with = "secp_ser::blind_from_hex"
)]
pub blind: BlindingFactor,
/// Key Identifier
pub key_id: Identifier,
/// Output
pub output: Output,
}
-363
View File
@@ -1,363 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Error types for libwallet
use crate::grin_core::core::{committed, transaction};
use crate::grin_core::libtx;
use crate::grin_keychain;
use crate::grin_util::secp;
use crate::util;
use grin_store;
/// Wallet errors, mostly wrappers around underlying crypto or I/O errors.
#[derive(Clone, Eq, PartialEq, Debug, thiserror::Error, Serialize, Deserialize)]
pub enum Error {
/// Not enough funds
#[error("Not enough funds. Required: {needed_disp:?}, Available: {available_disp:?}")]
NotEnoughFunds {
/// available funds
available: u64,
/// Display friendly
available_disp: String,
/// Needed funds
needed: u64,
/// Display friendly
needed_disp: String,
},
/// Fee error
#[error("Fee Error: {0}")]
Fee(String),
/// LibTX Error
#[error("LibTx Error")]
LibTX(#[from] libtx::Error),
/// Keychain error
#[error("Keychain error")]
Keychain(#[from] grin_keychain::Error),
/// Transaction Error
#[error("Transaction error")]
Transaction(#[from] transaction::Error),
/// API Error
#[error("Client Callback Error: {0}")]
ClientCallback(String),
/// Error from underlying secp lib
#[error("Secp Lib Error")]
Secp(#[from] secp::Error),
/// Onion V3 Address Error
#[error("Onion V3 Address Error: {0}")]
OnionV3Address(#[from] util::OnionV3AddressError),
/// Callback implementation error conversion
#[error("Trait Implementation error")]
CallbackImpl(&'static str),
/// Wallet backend error
#[error("Wallet store error: {0}")]
Backend(String),
/// Callback implementation error conversion
#[error("Restore Error")]
Restore,
/// An error in the format of the JSON structures exchanged by the wallet
#[error("JSON format error: {0}")]
Format(String),
/// Other serialization errors
#[error("Ser/Deserialization error")]
Deser(crate::grin_core::ser::Error),
/// IO Error
#[error("I/O error {0}")]
IO(String),
/// Error when contacting a node through its API
#[error("Node API error")]
Node,
/// Error contacting wallet API
#[error("Wallet Communication Error: {0}")]
WalletComms(String),
/// Error originating from hyper.
#[error("Hyper error")]
Hyper,
/// Error originating from hyper uri parsing.
#[error("Uri parsing error")]
Uri,
/// Signature error
#[error("Signature error: {0}")]
Signature(String),
/// OwnerAPIEncryption
#[error("{}", _0)]
APIEncryption(String),
/// Attempt to use duplicate transaction id in separate transactions
#[error("Duplicate transaction ID error")]
DuplicateTransactionId,
/// Wallet seed already exists
#[error("Wallet seed exists error: {0}")]
WalletSeedExists(String),
/// Wallet seed doesn't exist
#[error("Wallet seed doesn't exist error")]
WalletSeedDoesntExist,
/// Wallet seed doesn't exist
#[error("Wallet seed decryption error")]
WalletSeedDecryption,
/// Transaction doesn't exist
#[error("Transaction {0} doesn't exist")]
TransactionDoesntExist(String),
/// Transaction already rolled back
#[error("Transaction {0} cannot be cancelled")]
TransactionNotCancellable(String),
/// Cancellation error
#[error("Cancellation Error: {0}")]
TransactionCancellationError(&'static str),
/// Cancellation error
#[error("Tx dump Error: {0}")]
TransactionDumpError(&'static str),
/// Attempt to repost a transaction that's already confirmed
#[error("Transaction already confirmed error")]
TransactionAlreadyConfirmed,
/// Transaction has already been received
#[error("Transaction {0} has already been received")]
TransactionAlreadyReceived(String),
/// Transaction has been cancelled
#[error("Transaction {0} has been cancelled")]
TransactionWasCancelled(String),
/// Attempt to repost a transaction that's not completed and stored
#[error("Transaction building not completed: {0}")]
TransactionBuildingNotCompleted(u32),
/// Invalid BIP-32 Depth
#[error("Invalid BIP32 Depth (must be 1 or greater)")]
InvalidBIP32Depth,
/// Attempt to add an account that exists
#[error("Account Label '{0}' already exists")]
AccountLabelAlreadyExists(String),
/// Reference unknown account label
#[error("Unknown Account Label '{0}'")]
UnknownAccountLabel(String),
/// Error from summing commitments via committed trait.
#[error("Committed Error")]
Committed(committed::Error),
/// Error from summing commitments
#[error("Committed Error: {0}")]
Commit(String),
/// Error Deserializing commit
#[error("Commit Deserialize Error: {0}")]
CommitDeser(String),
/// Error Deserializing key
#[error("Server Key Deserialize Error: {0}")]
ServerKeyDeser(String),
/// Parsing integert
#[error("Can't parse as u64: {0}")]
U64Deser(String),
/// Can't parse slate version
#[error("Can't parse slate version")]
SlateVersionParse,
/// Can't serialize slate
#[error("Can't Serialize slate")]
SlateSer,
/// Can't deserialize slate
#[error("Can't Deserialize slate")]
SlateDeser,
/// Invalid slate state
#[error("Invalid slate state")]
SlateState,
/// Can't serialize slate pack
#[error("Can't Serialize slatepack")]
SlatepackSer,
/// Can't deserialize slate
#[error("Can't Deserialize slatepack: {0}")]
SlatepackDeser(String),
/// Unknown slate version
#[error("Unknown Slate Version: {0}")]
SlateVersion(u16),
/// Attempt to use slate transaction data that doesn't exists
#[error("Slate transaction required in this context")]
SlateTransactionRequired,
/// Attempt to downgrade slate that can't be downgraded
#[error("Can't downgrade slate: {0}")]
SlateInvalidDowngrade(String),
/// Compatibility error between incoming slate versions and what's expected
#[error("Compatibility Error: {0}")]
Compatibility(String),
/// Keychain doesn't exist (wallet not openend)
#[error("Keychain doesn't exist (has wallet been opened?)")]
KeychainDoesntExist,
/// Lifecycle Error
#[error("Lifecycle Error: {0}")]
Lifecycle(String),
/// Invalid Keychain Mask Error
#[error("Supplied Keychain Mask Token is incorrect")]
InvalidKeychainMask,
/// Tor Process error
#[error("Tor Process Error: {0}")]
TorProcess(String),
/// Tor Configuration Error
#[error("Tor Config Error: {0}")]
TorConfig(String),
/// Generating ED25519 Public Key
#[error("Error generating ed25519 secret key: {0}")]
ED25519Key(String),
/// Generating Payment Proof
#[error("Payment Proof generation error: {0}")]
PaymentProof(String),
/// Retrieving Payment Proof
#[error("Payment Proof retrieval error: {0}")]
PaymentProofRetrieval(String),
/// Retrieving Payment Proof
#[error("Payment Proof parsing error: {0}")]
PaymentProofParsing(String),
/// Decoding OnionV3 addresses to payment proof addresses
#[error("Proof Address decoding: {0}")]
AddressDecoding(String),
/// Transaction has expired it's TTL
#[error("Transaction Expired")]
TransactionExpired,
/// Kernel features args don't exist
#[error("Kernel Features Arg {0} missing")]
KernelFeaturesMissing(String),
/// Unknown Kernel Feature
#[error("Unknown Kernel Feature: {0}")]
UnknownKernelFeatures(u8),
/// Invalid Kernel Feature
#[error("Invalid Kernel Feature: {0}")]
InvalidKernelFeatures(u8),
/// Invalid Slatepack Data
#[error("Invalid Slatepack Data: {0}")]
InvalidSlatepackData(String),
/// Slatepack Encryption
#[error("Couldn't encrypt Slatepack: {0}")]
SlatepackEncryption(String),
/// Slatepack Decryption
#[error("Couldn't decrypt Slatepack: {0}")]
SlatepackDecryption(String),
/// age error
#[error("Age error: {0}")]
Age(String),
/// Rewind Hash parsing error
#[error("Rewind Hash error: {0}")]
RewindHash(String),
/// Nonce creation error
#[error("Nonce error: {0}")]
Nonce(String),
/// Slatepack address parsing error
#[error("SlatepackAddress error: {0}")]
SlatepackAddress(String),
/// Retrieving Stored Tx
#[error("Stored Tx error: {0}")]
StoredTx(String),
/// Other
#[error("Generic error: {0}")]
GenericError(String),
}
impl From<grin_store::Error> for Error {
fn from(error: grin_store::Error) -> Error {
Error::Backend(format!("{}", error))
}
}
impl From<age::EncryptError> for Error {
fn from(error: age::EncryptError) -> Error {
Error::Age(format!("{}", error))
}
}
impl From<age::DecryptError> for Error {
fn from(error: age::DecryptError) -> Error {
Error::Age(format!("{}", error))
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Error {
Error::IO(e.to_string())
}
}
impl From<&str> for Error {
fn from(error: &str) -> Error {
Error::Age(format!("Bech32 Key Encoding - {}", error))
}
}
impl From<bech32::Error> for Error {
fn from(error: bech32::Error) -> Error {
Error::SlatepackAddress(format!("{}", error))
}
}
-28
View File
@@ -1,28 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! lower-level wallet functions which build upon core::libtx to perform wallet
//! operations
#![deny(non_upper_case_globals)]
#![deny(non_camel_case_types)]
#![deny(non_snake_case)]
#![deny(unused_mut)]
#![warn(missing_docs)]
pub mod keys;
pub mod scan;
pub mod selection;
pub mod tx;
pub mod updater;
-129
View File
@@ -1,129 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Wallet key management functions
use crate::error::Error;
use crate::grin_keychain::{ChildNumber, ExtKeychain, Identifier, Keychain};
use crate::grin_util::secp::key::SecretKey;
use crate::types::{AcctPathMapping, NodeClient, WalletBackend};
/// Get next available key in the wallet for a given parent
pub fn next_available_key<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
) -> Result<Identifier, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let child = wallet.next_child(keychain_mask)?;
Ok(child)
}
/// Retrieve an existing key from a wallet
pub fn retrieve_existing_key<'a, T: ?Sized, C, K>(
wallet: &T,
key_id: Identifier,
mmr_index: Option<u64>,
) -> Result<(Identifier, u32), Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let existing = wallet.get(&key_id, &mmr_index)?;
let key_id = existing.key_id.clone();
let derivation = existing.n_child;
Ok((key_id, derivation))
}
/// Returns a list of account to BIP32 path mappings
pub fn accounts<'a, T: ?Sized, C, K>(wallet: &mut T) -> Result<Vec<AcctPathMapping>, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
Ok(wallet.acct_path_iter().collect())
}
/// Adds an new parent account path with a given label
pub fn new_acct_path<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
label: &str,
) -> Result<Identifier, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let label = label.to_owned();
if wallet.acct_path_iter().any(|l| l.label == label) {
return Err(Error::AccountLabelAlreadyExists(label));
}
// We're always using paths at m/k/0 for parent keys for output derivations
// so find the highest of those, then increment (to conform with external/internal
// derivation chains in BIP32 spec)
let highest_entry = wallet.acct_path_iter().max_by(|a, b| {
<u32>::from(a.path.to_path().path[0]).cmp(&<u32>::from(b.path.to_path().path[0]))
});
let return_id = {
if let Some(e) = highest_entry {
let mut p = e.path.to_path();
p.path[0] = ChildNumber::from(<u32>::from(p.path[0]) + 1);
p.to_identifier()
} else {
ExtKeychain::derive_key_id(2, 0, 0, 0, 0)
}
};
let save_path = AcctPathMapping {
label: label,
path: return_id.clone(),
};
let mut batch = wallet.batch(keychain_mask)?;
batch.save_acct_path(save_path)?;
batch.commit()?;
Ok(return_id)
}
/// Adds/sets a particular account path with a given label
pub fn set_acct_path<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
label: &str,
path: &Identifier,
) -> Result<(), Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let label = label.to_owned();
let save_path = AcctPathMapping {
label: label,
path: path.clone(),
};
let mut batch = wallet.batch(keychain_mask)?;
batch.save_acct_path(save_path)?;
batch.commit()?;
Ok(())
}
-645
View File
@@ -1,645 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Functions to restore a wallet's outputs from just the master seed
use crate::api_impl::owner_updater::StatusMessage;
use crate::grin_core::consensus::{valid_header_version, WEEK_HEIGHT};
use crate::grin_core::core::HeaderVersion;
use crate::grin_core::global;
use crate::grin_core::libtx::proof;
use crate::grin_keychain::{Identifier, Keychain, SwitchCommitmentType};
use crate::grin_util::secp::key::SecretKey;
use crate::grin_util::secp::pedersen;
use crate::grin_util::secp::{ContextFlag, Secp256k1};
use crate::grin_util::Mutex;
use crate::grin_util::{from_hex, ToHex};
use crate::internal::{keys, updater};
use crate::types::*;
use crate::{wallet_lock, Error, OutputCommitMapping};
use blake2_rfc::blake2b::blake2b;
use std::cmp;
use std::collections::HashMap;
use std::sync::mpsc::Sender;
use std::sync::Arc;
/// Utility struct for return values from below
#[derive(Debug, Clone)]
struct OutputResult {
///
pub commit: pedersen::Commitment,
///
pub key_id: Identifier,
///
pub n_child: u32,
///
pub mmr_index: u64,
///
pub value: u64,
///
pub height: u64,
///
pub lock_height: u64,
///
pub is_coinbase: bool,
}
#[derive(Debug, Clone)]
/// Collect stats in case we want to just output a single tx log entry
/// for restored non-coinbase outputs
struct RestoredTxStats {
///
pub log_id: u32,
///
pub amount_credited: u64,
///
pub num_outputs: usize,
}
fn identify_utxo_outputs<'a, K>(
keychain: &K,
outputs: Vec<(pedersen::Commitment, pedersen::RangeProof, bool, u64, u64)>,
status_send_channel: &Option<Sender<StatusMessage>>,
percentage_complete: u8,
) -> Result<Vec<OutputResult>, Error>
where
K: Keychain + 'a,
{
let mut wallet_outputs: Vec<OutputResult> = Vec::new();
let legacy_builder = proof::LegacyProofBuilder::new(keychain);
let builder = proof::ProofBuilder::new(keychain);
let legacy_version = HeaderVersion(1);
for output in outputs.iter() {
let (commit, proof, is_coinbase, height, mmr_index) = output;
// attempt to unwind message from the RP and get a value
// will fail if it's not ours
let info = {
// Before HF+2wk, try legacy rewind first
let info_legacy =
if valid_header_version(height.saturating_sub(2 * WEEK_HEIGHT), legacy_version) {
proof::rewind(keychain.secp(), &legacy_builder, *commit, None, *proof)?
} else {
None
};
// If legacy didn't work, try new rewind
if info_legacy.is_none() {
proof::rewind(keychain.secp(), &builder, *commit, None, *proof)?
} else {
info_legacy
}
};
let (amount, key_id, switch) = match info {
Some(i) => i,
None => {
continue;
}
};
let lock_height = if *is_coinbase {
*height + global::coinbase_maturity()
} else {
*height
};
let msg = format!(
"Output found: {:?}, amount: {:?}, key_id: {:?}, mmr_index: {},",
commit, amount, key_id, mmr_index,
);
if let Some(ref s) = status_send_channel {
let _ = s.send(StatusMessage::Scanning(msg, percentage_complete));
}
if switch != SwitchCommitmentType::Regular {
let msg = format!("Unexpected switch commitment type {:?}", switch);
if let Some(ref s) = status_send_channel {
let _ = s.send(StatusMessage::UpdateWarning(msg));
}
}
wallet_outputs.push(OutputResult {
commit: *commit,
key_id: key_id.clone(),
n_child: key_id.to_path().last_path_index(),
value: amount,
height: *height,
lock_height: lock_height,
is_coinbase: *is_coinbase,
mmr_index: *mmr_index,
});
}
Ok(wallet_outputs)
}
fn collect_chain_outputs_rewind_hash<'a, C>(
client: C,
rewind_hash: String,
start_index: u64,
end_index: Option<u64>,
status_send_channel: &Option<Sender<StatusMessage>>,
) -> Result<ViewWallet, Error>
where
C: NodeClient + 'a,
{
let batch_size = 1000;
let start_index_stat = start_index;
let mut start_index = start_index;
let mut vw = ViewWallet {
rewind_hash: rewind_hash,
output_result: vec![],
total_balance: 0,
last_pmmr_index: 0,
};
let secp = Secp256k1::with_caps(ContextFlag::VerifyOnly);
loop {
let (highest_index, last_retrieved_index, outputs) =
client.get_outputs_by_pmmr_index(start_index, end_index, batch_size)?;
let range = highest_index as f64 - start_index_stat as f64;
let progress = last_retrieved_index as f64 - start_index_stat as f64;
let percentage_complete = cmp::min(((progress / range) * 100.0) as u8, 99);
let msg = format!(
"Checking {} outputs, up to index {}. (Highest index: {})",
outputs.len(),
highest_index,
last_retrieved_index,
);
if let Some(ref s) = status_send_channel {
let _ = s.send(StatusMessage::Scanning(msg, percentage_complete));
}
// Scanning outputs
for output in outputs.iter() {
let (commit, proof, is_coinbase, height, mmr_index) = output;
let rewind_hash = from_hex(vw.rewind_hash.as_str())
.map_err(|e| Error::RewindHash(format!("Unable to decode rewind hash: {}", e)))?;
let rewind_nonce = blake2b(32, &commit.0, &rewind_hash);
let nonce = SecretKey::from_slice(&secp, rewind_nonce.as_bytes())
.map_err(|e| Error::Nonce(format!("Unable to create nonce: {}", e)))?;
let info = secp.rewind_bullet_proof(*commit, nonce.clone(), None, *proof);
if info.is_err() {
continue;
}
let info = info.unwrap();
vw.total_balance += info.value;
let lock_height = if *is_coinbase {
*height + global::coinbase_maturity()
} else {
*height
};
let output_info = ViewWalletOutputResult {
commit: commit.to_hex(),
value: info.value,
height: *height,
mmr_index: *mmr_index,
is_coinbase: *is_coinbase,
lock_height: lock_height,
};
vw.output_result.push(output_info);
}
if highest_index <= last_retrieved_index {
vw.last_pmmr_index = last_retrieved_index;
break;
}
start_index = last_retrieved_index + 1;
}
Ok(vw)
}
fn collect_chain_outputs<'a, C, K>(
keychain: &K,
client: C,
start_index: u64,
end_index: Option<u64>,
status_send_channel: &Option<Sender<StatusMessage>>,
) -> Result<(Vec<OutputResult>, u64), Error>
where
C: NodeClient + 'a,
K: Keychain + 'a,
{
let batch_size = 1000;
let start_index_stat = start_index;
let mut start_index = start_index;
let mut result_vec: Vec<OutputResult> = vec![];
let last_retrieved_return_index;
loop {
let (highest_index, last_retrieved_index, outputs) =
client.get_outputs_by_pmmr_index(start_index, end_index, batch_size)?;
let range = highest_index as f64 - start_index_stat as f64;
let progress = last_retrieved_index as f64 - start_index_stat as f64;
let perc_complete = cmp::min(((progress / range) * 100.0) as u8, 99);
let msg = format!(
"Checking {} outputs, up to index {}. (Highest index: {})",
outputs.len(),
highest_index,
last_retrieved_index,
);
if let Some(ref s) = status_send_channel {
let _ = s.send(StatusMessage::Scanning(msg, perc_complete));
}
result_vec.append(&mut identify_utxo_outputs(
keychain,
outputs.clone(),
status_send_channel,
perc_complete as u8,
)?);
if highest_index <= last_retrieved_index {
last_retrieved_return_index = last_retrieved_index;
break;
}
start_index = last_retrieved_index + 1;
}
Ok((result_vec, last_retrieved_return_index))
}
///
fn restore_missing_output<'a, L, C, K>(
wallet_inst: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
keychain_mask: Option<&SecretKey>,
output: OutputResult,
found_parents: &mut HashMap<Identifier, u32>,
tx_stats: &mut Option<&mut HashMap<Identifier, RestoredTxStats>>,
) -> Result<(), Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
wallet_lock!(wallet_inst, w);
let commit = w.calc_commit_for_cache(keychain_mask, output.value, &output.key_id)?;
let mut batch = w.batch(keychain_mask)?;
let parent_key_id = output.key_id.parent_path();
if !found_parents.contains_key(&parent_key_id) {
found_parents.insert(parent_key_id.clone(), 0);
if let Some(ref mut s) = tx_stats {
s.insert(
parent_key_id.clone(),
RestoredTxStats {
log_id: batch.next_tx_log_id(&parent_key_id)?,
amount_credited: 0,
num_outputs: 0,
},
);
}
}
let log_id = if tx_stats.is_none() || output.is_coinbase {
let log_id = batch.next_tx_log_id(&parent_key_id)?;
let entry_type = match output.is_coinbase {
true => TxLogEntryType::ConfirmedCoinbase,
false => TxLogEntryType::TxReceived,
};
let mut t = TxLogEntry::new(parent_key_id.clone(), entry_type, log_id);
t.confirmed = true;
t.amount_credited = output.value;
t.num_outputs = 1;
t.update_confirmation_ts();
batch.save_tx_log_entry(t, &parent_key_id)?;
log_id
} else if let Some(ref mut s) = tx_stats {
let ts = s.get(&parent_key_id).unwrap().clone();
s.insert(
parent_key_id.clone(),
RestoredTxStats {
log_id: ts.log_id,
amount_credited: ts.amount_credited + output.value,
num_outputs: ts.num_outputs + 1,
},
);
ts.log_id
} else {
0
};
let _ = batch.save(OutputData {
root_key_id: parent_key_id.clone(),
key_id: output.key_id,
n_child: output.n_child,
mmr_index: Some(output.mmr_index),
commit: commit,
value: output.value,
status: OutputStatus::Unspent,
height: output.height,
lock_height: output.lock_height,
is_coinbase: output.is_coinbase,
tx_log_entry: Some(log_id),
});
let max_child_index = *found_parents.get(&parent_key_id).unwrap();
if output.n_child >= max_child_index {
found_parents.insert(parent_key_id, output.n_child);
}
batch.commit()?;
Ok(())
}
///
fn cancel_tx_log_entry<'a, L, C, K>(
wallet_inst: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
keychain_mask: Option<&SecretKey>,
output: &OutputData,
) -> Result<(), Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let parent_key_id = output.key_id.parent_path();
wallet_lock!(wallet_inst, w);
let updated_tx_entry = if output.tx_log_entry.is_some() {
let entries = updater::retrieve_txs(
&mut **w,
output.tx_log_entry,
None,
None,
Some(&parent_key_id),
false,
)?;
if !entries.is_empty() {
let mut entry = entries[0].clone();
match entry.tx_type {
TxLogEntryType::TxSent => entry.tx_type = TxLogEntryType::TxSentCancelled,
TxLogEntryType::TxReceived => entry.tx_type = TxLogEntryType::TxReceivedCancelled,
_ => {}
}
Some(entry)
} else {
None
}
} else {
None
};
let mut batch = w.batch(keychain_mask)?;
if let Some(t) = updated_tx_entry {
batch.save_tx_log_entry(t, &parent_key_id)?;
}
batch.commit()?;
Ok(())
}
/// Scan outputs with a given rewind hash view wallet.
/// Retrieve all outputs information that belongs to it.
pub fn scan_rewind_hash<'a, L, C, K>(
wallet_inst: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
rewind_hash: String,
start_height: u64,
end_height: u64,
status_send_channel: &Option<Sender<StatusMessage>>,
) -> Result<ViewWallet, Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
if let Some(ref s) = status_send_channel {
let _ = s.send(StatusMessage::Scanning("Starting UTXO scan".to_owned(), 0));
}
let client = {
wallet_lock!(wallet_inst, w);
w.w2n_client().clone()
};
// Retrieve the actual PMMR index range we're looking for
let pmmr_range = client.height_range_to_pmmr_indices(start_height, Some(end_height))?;
let chain_outs = collect_chain_outputs_rewind_hash(
client,
rewind_hash,
pmmr_range.0,
Some(pmmr_range.1),
status_send_channel,
)?;
let msg = format!(
"Identified {} wallet_outputs as belonging to this wallet",
chain_outs.output_result.len(),
);
if let Some(ref s) = status_send_channel {
let _ = s.send(StatusMessage::Scanning(msg, 99));
}
if let Some(ref s) = status_send_channel {
let _ = s.send(StatusMessage::ScanningComplete(
"Scanning Complete".to_owned(),
));
}
Ok(chain_outs)
}
/// Check / repair wallet contents by scanning against chain
/// assume wallet contents have been freshly updated with contents
/// of latest block
pub fn scan<'a, L, C, K>(
wallet_inst: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
keychain_mask: Option<&SecretKey>,
delete_unconfirmed: bool,
start_height: u64,
end_height: u64,
status_send_channel: &Option<Sender<StatusMessage>>,
) -> Result<ScannedBlockInfo, Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
// First, get a definitive list of outputs we own from the chain
if let Some(ref s) = status_send_channel {
let _ = s.send(StatusMessage::Scanning("Starting UTXO scan".to_owned(), 0));
}
let (client, keychain) = {
wallet_lock!(wallet_inst, w);
(w.w2n_client().clone(), w.keychain(keychain_mask)?)
};
// Retrieve the actual PMMR index range we're looking for
let pmmr_range = client.height_range_to_pmmr_indices(start_height, Some(end_height))?;
let (chain_outs, last_index) = collect_chain_outputs(
&keychain,
client,
pmmr_range.0,
Some(pmmr_range.1),
status_send_channel,
)?;
let msg = format!(
"Identified {} wallet_outputs as belonging to this wallet",
chain_outs.len(),
);
if let Some(ref s) = status_send_channel {
let _ = s.send(StatusMessage::Scanning(msg, 99));
}
// Now, get all outputs owned by this wallet (regardless of account)
let wallet_outputs = {
wallet_lock!(wallet_inst, w);
updater::retrieve_outputs(&mut **w, keychain_mask, true, None, None)?
};
let mut missing_outs = vec![];
let mut accidental_spend_outs = vec![];
let mut locked_outs = vec![];
// check all definitive outputs exist in the wallet outputs
for deffo in chain_outs.into_iter() {
let matched_out = wallet_outputs.iter().find(|wo| wo.commit == deffo.commit);
match matched_out {
Some(s) => {
if s.output.status == OutputStatus::Spent {
accidental_spend_outs.push((s.output.clone(), deffo.clone()));
}
if s.output.status == OutputStatus::Locked {
locked_outs.push((s.output.clone(), deffo.clone()));
}
}
None => missing_outs.push(deffo),
}
}
// mark problem spent outputs as unspent (confirmed against a short-lived fork, for example)
for m in accidental_spend_outs.into_iter() {
let mut o = m.0;
let msg = format!(
"Output for {} with ID {} ({:?}) marked as spent but exists in UTXO set. \
Marking unspent and cancelling any associated transaction log entries.",
o.value, o.key_id, m.1.commit,
);
if let Some(ref s) = status_send_channel {
let _ = s.send(StatusMessage::Scanning(msg, 99));
}
o.status = OutputStatus::Unspent;
// any transactions associated with this should be cancelled
cancel_tx_log_entry(wallet_inst.clone(), keychain_mask, &o)?;
wallet_lock!(wallet_inst, w);
let mut batch = w.batch(keychain_mask)?;
batch.save(o)?;
batch.commit()?;
}
let mut found_parents: HashMap<Identifier, u32> = HashMap::new();
// Restore missing outputs, adding transaction for it back to the log
for m in missing_outs.into_iter() {
let msg = format!(
"Confirmed output for {} with ID {} ({:?}, index {}) exists in UTXO set but not in wallet. \
Restoring.",
m.value, m.key_id, m.commit, m.mmr_index
);
if let Some(ref s) = status_send_channel {
let _ = s.send(StatusMessage::Scanning(msg, 99));
}
restore_missing_output(
wallet_inst.clone(),
keychain_mask,
m,
&mut found_parents,
&mut None,
)?;
}
if delete_unconfirmed {
// Unlock locked outputs
for m in locked_outs.into_iter() {
let mut o = m.0;
let msg = format!(
"Confirmed output for {} with ID {} ({:?}) exists in UTXO set and is locked. \
Unlocking and cancelling associated transaction log entries.",
o.value, o.key_id, m.1.commit,
);
if let Some(ref s) = status_send_channel {
let _ = s.send(StatusMessage::Scanning(msg, 99));
}
o.status = OutputStatus::Unspent;
cancel_tx_log_entry(wallet_inst.clone(), keychain_mask, &o)?;
wallet_lock!(wallet_inst, w);
let mut batch = w.batch(keychain_mask)?;
batch.save(o)?;
batch.commit()?;
}
let unconfirmed_outs: Vec<&OutputCommitMapping> = wallet_outputs
.iter()
.filter(|o| o.output.status == OutputStatus::Unconfirmed)
.collect();
// Delete unconfirmed outputs
for m in unconfirmed_outs.into_iter() {
let o = m.output.clone();
let msg = format!(
"Unconfirmed output for {} with ID {} ({:?}) not in UTXO set. \
Deleting and cancelling associated transaction log entries.",
o.value, o.key_id, m.commit,
);
if let Some(ref s) = status_send_channel {
let _ = s.send(StatusMessage::Scanning(msg, 99));
}
cancel_tx_log_entry(wallet_inst.clone(), keychain_mask, &o)?;
wallet_lock!(wallet_inst, w);
let mut batch = w.batch(keychain_mask)?;
batch.delete(&o.key_id, &o.mmr_index)?;
batch.commit()?;
}
}
// restore labels, account paths and child derivation indices
wallet_lock!(wallet_inst, w);
let label_base = "account";
let accounts: Vec<Identifier> = w.acct_path_iter().map(|m| m.path).collect();
let mut acct_index = accounts.len();
for (path, max_child_index) in found_parents.iter() {
// Only restore paths that don't exist
if !accounts.contains(path) {
let label = format!("{}_{}", label_base, acct_index);
let msg = format!("Setting account {} at path {}", label, path);
if let Some(ref s) = status_send_channel {
let _ = s.send(StatusMessage::Scanning(msg, 99));
}
keys::set_acct_path(&mut **w, keychain_mask, &label, path)?;
acct_index += 1;
}
let current_child_index = w.current_child_index(&path)?;
if *max_child_index >= current_child_index {
let mut batch = w.batch(keychain_mask)?;
debug!("Next child for account {} is {}", path, max_child_index + 1);
batch.save_child_index(path, max_child_index + 1)?;
batch.commit()?;
}
}
if let Some(ref s) = status_send_channel {
let _ = s.send(StatusMessage::ScanningComplete(
"Scanning Complete".to_owned(),
));
}
Ok(ScannedBlockInfo {
height: end_height,
hash: "".to_owned(),
start_pmmr_index: pmmr_range.0,
last_pmmr_index: last_index,
})
}
-716
View File
@@ -1,716 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Selection of inputs for building transactions
use crate::address;
use crate::error::Error;
use crate::grin_core::core::amount_to_hr_string;
use crate::grin_core::libtx::{
build,
proof::{ProofBuild, ProofBuilder},
tx_fee,
};
use crate::grin_keychain::{Identifier, Keychain};
use crate::grin_util::secp::key::SecretKey;
use crate::grin_util::secp::pedersen;
use crate::internal::keys;
use crate::slate::Slate;
use crate::types::*;
use crate::util::OnionV3Address;
use std::collections::HashMap;
use std::convert::TryInto;
/// Initialize a transaction on the sender side, returns a corresponding
/// libwallet transaction slate with the appropriate inputs selected,
/// and saves the private wallet identifiers of our selected outputs
/// into our transaction context
pub fn build_send_tx<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain: &K,
keychain_mask: Option<&SecretKey>,
slate: &mut Slate,
current_height: u64,
minimum_confirmations: u64,
max_outputs: usize,
change_outputs: usize,
selection_strategy_is_use_all: bool,
fixed_fee: Option<u64>,
parent_key_id: Identifier,
use_test_nonce: bool,
is_initiator: bool,
amount_includes_fee: bool,
) -> Result<Context, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let (elems, inputs, change_amounts_derivations, fee) = select_send_tx(
wallet,
keychain_mask,
slate.amount,
amount_includes_fee,
current_height,
minimum_confirmations,
max_outputs,
change_outputs,
selection_strategy_is_use_all,
&parent_key_id,
false,
)?;
if amount_includes_fee {
slate.amount = slate.amount.checked_sub(fee).ok_or(Error::GenericError(
format!("Transaction amount is too small to include fee").into(),
))?;
};
if fixed_fee.map(|f| fee != f).unwrap_or(false) {
return Err(Error::Fee(
"The initially selected fee is not sufficient".into(),
));
}
// Update the fee on the slate so we account for this when building the tx.
slate.fee_fields = fee.try_into().unwrap();
slate.add_transaction_elements(keychain, &ProofBuilder::new(keychain), elems)?;
// Create our own private context
let mut context = Context::new(
keychain.secp(),
&parent_key_id,
use_test_nonce,
is_initiator,
);
context.fee = Some(slate.fee_fields);
context.amount = slate.amount;
// Store our private identifiers for each input
for input in inputs {
context.add_input(&input.key_id, &input.mmr_index, input.value);
}
let mut commits: HashMap<Identifier, Option<String>> = HashMap::new();
// Store change output(s) and cached commits
for (change_amount, id, mmr_index) in &change_amounts_derivations {
context.add_output(&id, &mmr_index, *change_amount);
commits.insert(
id.clone(),
wallet.calc_commit_for_cache(keychain_mask, *change_amount, &id)?,
);
}
Ok(context)
}
/// Locks all corresponding outputs in the context, creates
/// change outputs and tx log entry
pub fn lock_tx_context<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
slate: &Slate,
current_height: u64,
context: &Context,
excess_override: Option<pedersen::Commitment>,
) -> Result<(), Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let mut output_commits: HashMap<Identifier, (Option<String>, u64)> = HashMap::new();
// Store cached commits before locking wallet
let mut total_change = 0;
for (id, _, change_amount) in &context.get_outputs() {
output_commits.insert(
id.clone(),
(
wallet.calc_commit_for_cache(keychain_mask, *change_amount, &id)?,
*change_amount,
),
);
total_change += change_amount;
}
debug!("Change amount is: {}", total_change);
let keychain = wallet.keychain(keychain_mask)?;
let tx_entry = {
let lock_inputs = context.get_inputs();
let slate_id = slate.id;
let height = current_height;
let parent_key_id = context.parent_key_id.clone();
let mut batch = wallet.batch(keychain_mask)?;
let log_id = batch.next_tx_log_id(&parent_key_id)?;
let mut t = TxLogEntry::new(parent_key_id.clone(), TxLogEntryType::TxSent, log_id);
t.tx_slate_id = Some(slate_id);
let filename = format!("{}.grintx", slate_id);
t.stored_tx = Some(filename);
t.fee = context.fee;
t.ttl_cutoff_height = match slate.ttl_cutoff_height {
0 => None,
n => Some(n),
};
if let Ok(e) = slate.calc_excess(keychain.secp()) {
t.kernel_excess = Some(e)
}
if let Some(e) = excess_override {
t.kernel_excess = Some(e)
}
t.kernel_lookup_min_height = Some(current_height);
let mut amount_debited = 0;
t.num_inputs = lock_inputs.len();
for id in lock_inputs {
let mut coin = batch.get(&id.0, &id.1).unwrap();
coin.tx_log_entry = Some(log_id);
amount_debited += coin.value;
batch.lock_output(&mut coin)?;
}
t.amount_debited = amount_debited;
// store extra payment proof info, if required
if let Some(ref p) = slate.payment_proof {
let sender_address_path = match context.payment_proof_derivation_index {
Some(p) => p,
None => {
return Err(Error::PaymentProof(
"Payment proof derivation index required".to_owned(),
)
.into());
}
};
let sender_key = address::address_from_derivation_path(
&keychain,
&parent_key_id,
sender_address_path,
)?;
let sender_address = OnionV3Address::from_private(&sender_key.0)?;
t.payment_proof = Some(StoredProofInfo {
receiver_address: p.receiver_address,
receiver_signature: p.receiver_signature,
sender_address: sender_address.to_ed25519()?,
sender_address_path,
sender_signature: None,
});
};
// write the output representing our change
for (id, _, _) in &context.get_outputs() {
t.num_outputs += 1;
let (commit, change_amount) = output_commits.get(&id).unwrap().clone();
t.amount_credited += change_amount;
batch.save(OutputData {
root_key_id: parent_key_id.clone(),
key_id: id.clone(),
n_child: id.to_path().last_path_index(),
commit: commit,
mmr_index: None,
value: change_amount,
status: OutputStatus::Unconfirmed,
height: height,
lock_height: 0,
is_coinbase: false,
tx_log_entry: Some(log_id),
})?;
}
batch.save_tx_log_entry(t.clone(), &parent_key_id)?;
batch.commit()?;
t
};
wallet.store_tx(
&format!("{}", tx_entry.tx_slate_id.unwrap()),
slate.tx_or_err()?,
)?;
Ok(())
}
/// Creates a new output in the wallet for the recipient,
/// returning the key of the fresh output
/// Also creates a new transaction containing the output
pub fn build_recipient_output<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
slate: &mut Slate,
current_height: u64,
parent_key_id: Identifier,
use_test_rng: bool,
is_initiator: bool,
) -> Result<(Identifier, Context, TxLogEntry), Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
// Create a potential output for this transaction
let key_id = keys::next_available_key(wallet, keychain_mask).unwrap();
let keychain = wallet.keychain(keychain_mask)?;
let key_id_inner = key_id.clone();
let amount = slate.amount;
let height = current_height;
let slate_id = slate.id;
slate.add_transaction_elements(
&keychain,
&ProofBuilder::new(&keychain),
vec![build::output(amount, key_id.clone())],
)?;
// Add blinding sum to our context
let mut context = Context::new(keychain.secp(), &parent_key_id, use_test_rng, is_initiator);
context.add_output(&key_id, &None, amount);
context.amount = amount;
context.fee = slate.fee_fields.as_opt();
let commit = wallet.calc_commit_for_cache(keychain_mask, amount, &key_id_inner)?;
let mut batch = wallet.batch(keychain_mask)?;
let log_id = batch.next_tx_log_id(&parent_key_id)?;
let mut t = TxLogEntry::new(parent_key_id.clone(), TxLogEntryType::TxReceived, log_id);
t.tx_slate_id = Some(slate_id);
t.amount_credited = amount;
t.num_outputs = 1;
t.ttl_cutoff_height = match slate.ttl_cutoff_height {
0 => None,
n => Some(n),
};
// when invoicing, this will be invalid
if let Ok(e) = slate.calc_excess(keychain.secp()) {
t.kernel_excess = Some(e)
}
t.kernel_lookup_min_height = Some(current_height);
batch.save(OutputData {
root_key_id: parent_key_id.clone(),
key_id: key_id_inner.clone(),
mmr_index: None,
n_child: key_id_inner.to_path().last_path_index(),
commit: commit,
value: amount,
status: OutputStatus::Unconfirmed,
height: height,
lock_height: 0,
is_coinbase: false,
tx_log_entry: Some(log_id),
})?;
batch.save_tx_log_entry(t.clone(), &parent_key_id)?;
batch.commit()?;
Ok((key_id, context, t))
}
/// Builds a transaction to send to someone from the HD seed associated with the
/// wallet and the amount to send. Handles reading through the wallet data file,
/// selecting outputs to spend and building the change.
pub fn select_send_tx<'a, T: ?Sized, C, K, B>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
amount: u64,
amount_includes_fee: bool,
current_height: u64,
minimum_confirmations: u64,
max_outputs: usize,
change_outputs: usize,
selection_strategy_is_use_all: bool,
parent_key_id: &Identifier,
include_inputs_in_sum: bool,
) -> Result<
(
Vec<Box<build::Append<K, B>>>,
Vec<OutputData>,
Vec<(u64, Identifier, Option<u64>)>, // change amounts and derivations
u64, // fee
),
Error,
>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
B: ProofBuild,
{
let (coins, _total, amount, fee) = select_coins_and_fee(
wallet,
amount,
amount_includes_fee,
current_height,
minimum_confirmations,
max_outputs,
change_outputs,
selection_strategy_is_use_all,
&parent_key_id,
)?;
// build transaction skeleton with inputs and change
let (parts, change_amounts_derivations) = inputs_and_change(
&coins,
wallet,
keychain_mask,
amount,
fee,
change_outputs,
include_inputs_in_sum,
)?;
Ok((parts, coins, change_amounts_derivations, fee))
}
/// Select outputs and calculating fee.
pub fn select_coins_and_fee<'a, T: ?Sized, C, K>(
wallet: &mut T,
amount: u64,
amount_includes_fee: bool,
current_height: u64,
minimum_confirmations: u64,
max_outputs: usize,
change_outputs: usize,
selection_strategy_is_use_all: bool,
parent_key_id: &Identifier,
) -> Result<
(
Vec<OutputData>,
u64, // total
u64, // amount
u64, // fee
),
Error,
>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
// select some spendable coins from the wallet
let (max_outputs, mut coins) = select_coins(
wallet,
amount,
current_height,
minimum_confirmations,
max_outputs,
selection_strategy_is_use_all,
parent_key_id,
);
// sender is responsible for setting the fee on the partial tx
// recipient should double check the fee calculation and not blindly trust the
// sender
// First attempt to spend without change
let mut fee = tx_fee(coins.len(), 1, 1);
let mut total: u64 = coins.iter().map(|c| c.value).sum();
let mut amount_with_fee = match amount_includes_fee {
true => amount,
false => amount + fee,
};
if total == 0 {
return Err(Error::NotEnoughFunds {
available: 0,
available_disp: amount_to_hr_string(0, false),
needed: amount_with_fee as u64,
needed_disp: amount_to_hr_string(amount_with_fee as u64, false),
});
}
// The amount with fee is more than the total values of our max outputs
if total < amount_with_fee && coins.len() == max_outputs {
return Err(Error::NotEnoughFunds {
available: total,
available_disp: amount_to_hr_string(total, false),
needed: amount_with_fee as u64,
needed_disp: amount_to_hr_string(amount_with_fee as u64, false),
});
}
let num_outputs = change_outputs + 1;
// We need to add a change address or amount with fee is more than total
if total != amount_with_fee {
fee = tx_fee(coins.len(), num_outputs, 1);
amount_with_fee = match amount_includes_fee {
true => amount,
false => amount + fee,
};
// Here check if we have enough outputs for the amount including fee otherwise
// look for other outputs and check again
while total < amount_with_fee {
// End the loop if we have selected all the outputs and still not enough funds
if coins.len() == max_outputs {
return Err(Error::NotEnoughFunds {
available: total as u64,
available_disp: amount_to_hr_string(total, false),
needed: amount_with_fee as u64,
needed_disp: amount_to_hr_string(amount_with_fee as u64, false),
});
}
// select some spendable coins from the wallet
coins = select_coins(
wallet,
amount_with_fee,
current_height,
minimum_confirmations,
max_outputs,
selection_strategy_is_use_all,
parent_key_id,
)
.1;
fee = tx_fee(coins.len(), num_outputs, 1);
total = coins.iter().map(|c| c.value).sum();
amount_with_fee = match amount_includes_fee {
true => amount,
false => amount + fee,
};
}
}
// If original amount includes fee, the new amount should
// be reduced, to accommodate the fee.
let new_amount = match amount_includes_fee {
true => amount.checked_sub(fee).ok_or(Error::GenericError(
format!("Transaction amount is too small to include fee").into(),
))?,
false => amount,
};
Ok((coins, total, new_amount, fee))
}
/// Selects inputs and change for a transaction
pub fn inputs_and_change<'a, T: ?Sized, C, K, B>(
coins: &[OutputData],
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
amount: u64,
fee: u64,
num_change_outputs: usize,
include_inputs_in_sum: bool,
) -> Result<
(
Vec<Box<build::Append<K, B>>>,
Vec<(u64, Identifier, Option<u64>)>,
),
Error,
>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
B: ProofBuild,
{
let mut parts = vec![];
// calculate the total across all inputs, and how much is left
let total: u64 = coins.iter().map(|c| c.value).sum();
// if we are spending 10,000 coins to send 1,000 then our change will be 9,000
// if the fee is 80 then the recipient will receive 1000 and our change will be
// 8,920
let change = total - amount - fee;
// build inputs using the appropriate derived key_ids
if include_inputs_in_sum {
for coin in coins {
if coin.is_coinbase {
parts.push(build::coinbase_input(coin.value, coin.key_id.clone()));
} else {
parts.push(build::input(coin.value, coin.key_id.clone()));
}
}
}
let mut change_amounts_derivations = vec![];
if change == 0 {
debug!("No change (sending exactly amount + fee), no change outputs to build");
} else {
debug!(
"Building change outputs: total change: {} ({} outputs)",
change, num_change_outputs
);
let part_change = change / num_change_outputs as u64;
let remainder_change = change % part_change;
for x in 0..num_change_outputs {
// n-1 equal change_outputs and a final one accounting for any remainder
let change_amount = if x == (num_change_outputs - 1) {
part_change + remainder_change
} else {
part_change
};
let change_key = wallet.next_child(keychain_mask).unwrap();
change_amounts_derivations.push((change_amount, change_key.clone(), None));
parts.push(build::output(change_amount, change_key));
}
}
Ok((parts, change_amounts_derivations))
}
/// Select spendable coins from a wallet.
/// Default strategy is to spend the maximum number of outputs (up to
/// max_outputs). Alternative strategy is to spend smallest outputs first
/// but only as many as necessary. When we introduce additional strategies
/// we should pass something other than a bool in.
/// TODO: Possibly move this into another trait to be owned by a wallet?
pub fn select_coins<'a, T: ?Sized, C, K>(
wallet: &mut T,
amount: u64,
current_height: u64,
minimum_confirmations: u64,
max_outputs: usize,
select_all: bool,
parent_key_id: &Identifier,
) -> (usize, Vec<OutputData>)
// max_outputs_available, Outputs
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
// first find all eligible outputs based on number of confirmations
let mut eligible = wallet
.iter()
.filter(|out| {
out.root_key_id == *parent_key_id
&& out.eligible_to_spend(current_height, minimum_confirmations)
})
.collect::<Vec<OutputData>>();
let max_available = eligible.len();
// sort eligible outputs by increasing value
eligible.sort_by_key(|out| out.value);
// use a sliding window to identify potential sets of possible outputs to spend
// Case of amount > total amount of max_outputs(500):
// The limit exists because by default, we always select as many inputs as
// possible in a transaction, to reduce both the Output set and the fees.
// But that only makes sense up to a point, hence the limit to avoid being too
// greedy. But if max_outputs(500) is actually not enough to cover the whole
// amount, the wallet should allow going over it to satisfy what the user
// wants to send. So the wallet considers max_outputs more of a soft limit.
if eligible.len() > max_outputs {
for window in eligible.windows(max_outputs) {
let windowed_eligibles = window.to_vec();
if let Some(outputs) = select_from(amount, select_all, windowed_eligibles) {
return (max_available, outputs);
}
}
// Not exist in any window of which total amount >= amount.
// Then take coins from the smallest one up to the total amount of selected
// coins = the amount.
if let Some(outputs) = select_from(amount, false, eligible.clone()) {
debug!(
"Extending maximum number of outputs. {} outputs selected.",
outputs.len()
);
return (max_available, outputs);
}
} else if let Some(outputs) = select_from(amount, select_all, eligible.clone()) {
return (max_available, outputs);
}
// we failed to find a suitable set of outputs to spend,
// so return the largest amount we can so we can provide guidance on what is
// possible
eligible.reverse();
(
max_available,
eligible.iter().take(max_outputs).cloned().collect(),
)
}
fn select_from(amount: u64, select_all: bool, outputs: Vec<OutputData>) -> Option<Vec<OutputData>> {
let total = outputs.iter().fold(0, |acc, x| acc + x.value);
if total >= amount {
if select_all {
Some(outputs.to_vec())
} else {
let mut selected_amount = 0;
Some(
outputs
.iter()
.take_while(|out| {
let res = selected_amount < amount;
selected_amount += out.value;
res
})
.cloned()
.collect(),
)
}
} else {
None
}
}
/// Repopulates output in the slate's tranacstion
/// with outputs from the stored context
/// change outputs and tx log entry
/// Remove the explicitly stored excess
pub fn repopulate_tx<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
slate: &mut Slate,
context: &Context,
update_fee: bool,
) -> Result<(), Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
// restore the original amount, fee
slate.amount = context.amount;
if update_fee {
slate.fee_fields = context
.fee
.ok_or_else(|| Error::Fee("Missing fee fields".into()))?;
}
let keychain = wallet.keychain(keychain_mask)?;
// restore my signature data
slate.add_participant_info(&keychain, &context, None)?;
let mut parts = vec![];
for (id, _, value) in &context.get_inputs() {
let input = wallet.iter().find(|out| out.key_id == *id);
if let Some(i) = input {
if i.is_coinbase {
parts.push(build::coinbase_input(*value, i.key_id.clone()));
} else {
parts.push(build::input(*value, i.key_id.clone()));
}
}
}
for (id, _, value) in &context.get_outputs() {
let output = wallet.iter().find(|out| out.key_id == *id);
if let Some(i) = output {
parts.push(build::output(*value, i.key_id.clone()));
}
}
let _ = slate.add_transaction_elements(&keychain, &ProofBuilder::new(&keychain), parts)?;
// restore the original offset
slate.tx_or_err_mut()?.offset = slate.offset.clone();
Ok(())
}
-683
View File
@@ -1,683 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Transaction building functions
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use std::io::Cursor;
use uuid::Uuid;
use crate::grin_core::consensus::valid_header_version;
use crate::grin_core::core::HeaderVersion;
use crate::grin_keychain::{Identifier, Keychain};
use crate::grin_util::secp::key::SecretKey;
use crate::grin_util::secp::pedersen;
use crate::grin_util::Mutex;
use crate::internal::{selection, updater};
use crate::slate::Slate;
use crate::types::{Context, NodeClient, StoredProofInfo, TxLogEntryType, WalletBackend};
use crate::util::OnionV3Address;
use crate::InitTxArgs;
use crate::{address, Error};
use ed25519_dalek::Keypair as DalekKeypair;
use ed25519_dalek::PublicKey as DalekPublicKey;
use ed25519_dalek::SecretKey as DalekSecretKey;
use ed25519_dalek::Signature as DalekSignature;
use ed25519_dalek::{Signer, Verifier};
use grin_core::core::FeeFields;
// static for incrementing test UUIDs
lazy_static! {
static ref SLATE_COUNTER: Mutex<u8> = Mutex::new(0);
}
/// Creates a new slate for a transaction, can be called by anyone involved in
/// the transaction (sender(s), receiver(s))
pub fn new_tx_slate<'a, T: ?Sized, C, K>(
wallet: &mut T,
amount: u64,
is_invoice: bool,
num_participants: u8,
use_test_rng: bool,
ttl_blocks: Option<u64>,
) -> Result<Slate, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let current_height = wallet.w2n_client().get_chain_tip()?.0;
let mut slate = Slate::blank(num_participants, is_invoice);
if let Some(b) = ttl_blocks {
slate.ttl_cutoff_height = current_height + b;
}
if use_test_rng {
{
let sc = SLATE_COUNTER.lock();
let bytes = [4, 54, 67, 12, 43, 2, 98, 76, 32, 50, 87, 5, 1, 33, 43, *sc];
slate.id = Uuid::from_slice(&bytes).unwrap();
}
*SLATE_COUNTER.lock() += 1;
}
slate.amount = amount;
if valid_header_version(current_height, HeaderVersion(1)) {
slate.version_info.block_header_version = 1;
}
if valid_header_version(current_height, HeaderVersion(2)) {
slate.version_info.block_header_version = 2;
}
if valid_header_version(current_height, HeaderVersion(3)) {
slate.version_info.block_header_version = 3;
}
// Set the features explicitly to 0 here.
// This will generate a Plain kernel (rather than a HeightLocked kernel).
slate.kernel_features = 0;
Ok(slate)
}
/// Estimates locked amount and fee for the transaction without creating one
pub fn estimate_send_tx<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
amount: u64,
amount_includes_fee: bool,
minimum_confirmations: u64,
max_outputs: usize,
num_change_outputs: usize,
selection_strategy_is_use_all: bool,
parent_key_id: &Identifier,
) -> Result<
(
u64, // total
u64, // fee
),
Error,
>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
// Get lock height
let current_height = wallet.w2n_client().get_chain_tip()?.0;
// ensure outputs we're selecting are up to date
updater::refresh_outputs(wallet, keychain_mask, parent_key_id, false)?;
// Sender selects outputs into a new slate and save our corresponding keys in
// a transaction context. The secret key in our transaction context will be
// randomly selected. This returns the public slate, and a closure that locks
// our inputs and outputs once we're convinced the transaction exchange went
// according to plan
// This function is just a big helper to do all of that, in theory
// this process can be split up in any way
let (_coins, total, _amount, fee) = selection::select_coins_and_fee(
wallet,
amount,
amount_includes_fee,
current_height,
minimum_confirmations,
max_outputs,
num_change_outputs,
selection_strategy_is_use_all,
parent_key_id,
)?;
Ok((total, fee))
}
/// Add inputs to the slate (effectively becoming the sender)
pub fn add_inputs_to_slate<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
slate: &mut Slate,
current_height: u64,
minimum_confirmations: u64,
max_outputs: usize,
num_change_outputs: usize,
selection_strategy_is_use_all: bool,
parent_key_id: &Identifier,
is_initiator: bool,
use_test_rng: bool,
amount_includes_fee: bool,
) -> Result<Context, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
// sender should always refresh outputs
updater::refresh_outputs(wallet, keychain_mask, parent_key_id, false)?;
// Sender selects outputs into a new slate and save our corresponding keys in
// a transaction context. The secret key in our transaction context will be
// randomly selected. This returns the public slate, and a closure that locks
// our inputs and outputs once we're convinced the transaction exchange went
// according to plan
// This function is just a big helper to do all of that, in theory
// this process can be split up in any way
let mut context = selection::build_send_tx(
wallet,
&wallet.keychain(keychain_mask)?,
keychain_mask,
slate,
current_height,
minimum_confirmations,
max_outputs,
num_change_outputs,
selection_strategy_is_use_all,
None,
parent_key_id.clone(),
use_test_rng,
is_initiator,
amount_includes_fee,
)?;
// Generate a kernel offset and subtract from our context's secret key. Store
// the offset in the slate's transaction kernel, and adds our public key
// information to the slate
slate.fill_round_1(&wallet.keychain(keychain_mask)?, &mut context)?;
context.initial_sec_key = context.sec_key.clone();
if !is_initiator {
// perform partial sig
slate.fill_round_2(
&wallet.keychain(keychain_mask)?,
&context.sec_key,
&context.sec_nonce,
)?;
}
Ok(context)
}
/// Add receiver output to the slate
pub fn add_output_to_slate<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
slate: &mut Slate,
current_height: u64,
parent_key_id: &Identifier,
is_initiator: bool,
use_test_rng: bool,
) -> Result<Context, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let keychain = wallet.keychain(keychain_mask)?;
// create an output using the amount in the slate
let (_, mut context, mut tx) = selection::build_recipient_output(
wallet,
keychain_mask,
slate,
current_height,
parent_key_id.clone(),
use_test_rng,
is_initiator,
)?;
// fill public keys
slate.fill_round_1(&keychain, &mut context)?;
context.initial_sec_key = context.sec_key.clone();
if !is_initiator {
// perform partial sig
slate.fill_round_2(&keychain, &context.sec_key, &context.sec_nonce)?;
// update excess in stored transaction
let mut batch = wallet.batch(keychain_mask)?;
tx.kernel_excess = Some(slate.calc_excess(keychain.secp())?);
batch.save_tx_log_entry(tx.clone(), &parent_key_id)?;
batch.commit()?;
}
Ok(context)
}
/// Create context, without adding inputs to slate
pub fn create_late_lock_context<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
slate: &mut Slate,
current_height: u64,
init_tx_args: &InitTxArgs,
parent_key_id: &Identifier,
use_test_rng: bool,
) -> Result<Context, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
// sender should always refresh outputs
updater::refresh_outputs(wallet, keychain_mask, parent_key_id, false)?;
// we're just going to run a selection to get the potential fee,
// but this won't be locked
let (_coins, _total, _amount, fee) = selection::select_coins_and_fee(
wallet,
init_tx_args.amount,
init_tx_args.amount_includes_fee.unwrap_or(false),
current_height,
init_tx_args.minimum_confirmations,
init_tx_args.max_outputs as usize,
init_tx_args.num_change_outputs as usize,
init_tx_args.selection_strategy_is_use_all,
&parent_key_id,
)?;
slate.fee_fields = FeeFields::new(0, fee)?;
let keychain = wallet.keychain(keychain_mask)?;
// Create our own private context
let mut context = Context::new(keychain.secp(), &parent_key_id, use_test_rng, true);
context.fee = Some(slate.fee_fields);
context.amount = slate.amount;
context.late_lock_args = Some(init_tx_args.clone());
// Generate a blinding factor for the tx and add
// public key info to the slate
slate.fill_round_1(&wallet.keychain(keychain_mask)?, &mut context)?;
Ok(context)
}
/// Complete a transaction
pub fn complete_tx<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
slate: &mut Slate,
context: &Context,
) -> Result<(), Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
// when self sending invoice tx, use initiator nonce to finalize
let (sec_key, sec_nonce) = {
if context.initial_sec_key != context.sec_key
&& context.initial_sec_nonce != context.sec_nonce
{
(
context.initial_sec_key.clone(),
context.initial_sec_nonce.clone(),
)
} else {
(context.sec_key.clone(), context.sec_nonce.clone())
}
};
slate.fill_round_2(&wallet.keychain(keychain_mask)?, &sec_key, &sec_nonce)?;
// Final transaction can be built by anyone at this stage
trace!("Slate to finalize is: {}", slate);
slate.finalize(&wallet.keychain(keychain_mask)?)?;
Ok(())
}
/// Rollback outputs associated with a transaction in the wallet
pub fn cancel_tx<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
parent_key_id: &Identifier,
tx_id: Option<u32>,
tx_slate_id: Option<Uuid>,
) -> Result<(), Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let mut tx_id_string = String::new();
if let Some(tx_id) = tx_id {
tx_id_string = tx_id.to_string();
} else if let Some(tx_slate_id) = tx_slate_id {
tx_id_string = tx_slate_id.to_string();
}
let tx_vec = updater::retrieve_txs(
wallet,
tx_id,
tx_slate_id,
None,
Some(&parent_key_id),
false,
)?;
if tx_vec.len() != 1 {
return Err(Error::TransactionDoesntExist(tx_id_string));
}
let tx = tx_vec[0].clone();
match tx.tx_type {
TxLogEntryType::TxSent | TxLogEntryType::TxReceived | TxLogEntryType::TxReverted => {}
_ => return Err(Error::TransactionNotCancellable(tx_id_string)),
}
if tx.confirmed {
return Err(Error::TransactionNotCancellable(tx_id_string));
}
// get outputs associated with tx
let res = updater::retrieve_outputs(
wallet,
keychain_mask,
false,
Some(tx.id),
Some(&parent_key_id),
)?;
let outputs = res.iter().map(|m| m.output.clone()).collect();
updater::cancel_tx_and_outputs(wallet, keychain_mask, tx, outputs, parent_key_id)?;
Ok(())
}
/// Update the stored transaction (this update needs to happen when the TX is finalised)
pub fn update_stored_tx<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
context: &Context,
slate: &Slate,
is_invoiced: bool,
) -> Result<(), Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
// finalize command
let tx_vec = updater::retrieve_txs(wallet, None, Some(slate.id), None, None, false)?;
let mut tx = None;
// don't want to assume this is the right tx, in case of self-sending
for t in tx_vec {
if t.tx_type == TxLogEntryType::TxSent && !is_invoiced {
tx = Some(t);
break;
}
if t.tx_type == TxLogEntryType::TxReceived && is_invoiced {
tx = Some(t);
break;
}
}
let mut tx = match tx {
Some(t) => t,
None => return Err(Error::TransactionDoesntExist(slate.id.to_string())),
};
let parent_key = tx.parent_key_id.clone();
{
let keychain = wallet.keychain(keychain_mask)?;
tx.kernel_excess = Some(slate.calc_excess(keychain.secp())?);
}
if let Some(ref p) = slate.clone().payment_proof {
let derivation_index = match context.payment_proof_derivation_index {
Some(i) => i,
None => 0,
};
let keychain = wallet.keychain(keychain_mask)?;
let parent_key_id = wallet.parent_key_id();
let excess = slate.calc_excess(keychain.secp())?;
let sender_key =
address::address_from_derivation_path(&keychain, &parent_key_id, derivation_index)?;
let sender_address = OnionV3Address::from_private(&sender_key.0)?;
let sig =
create_payment_proof_signature(slate.amount, &excess, p.sender_address, sender_key)?;
tx.payment_proof = Some(StoredProofInfo {
receiver_address: p.receiver_address,
receiver_signature: p.receiver_signature,
sender_address_path: derivation_index,
sender_address: sender_address.to_ed25519()?,
sender_signature: Some(sig),
})
}
wallet.store_tx(&format!("{}", tx.tx_slate_id.unwrap()), slate.tx_or_err()?)?;
let mut batch = wallet.batch(keychain_mask)?;
batch.save_tx_log_entry(tx, &parent_key)?;
batch.commit()?;
Ok(())
}
pub fn payment_proof_message(
amount: u64,
kernel_commitment: &pedersen::Commitment,
sender_address: DalekPublicKey,
) -> Result<Vec<u8>, Error> {
let mut msg = Vec::new();
msg.write_u64::<BigEndian>(amount)?;
msg.append(&mut kernel_commitment.0.to_vec());
msg.append(&mut sender_address.to_bytes().to_vec());
Ok(msg)
}
pub fn _decode_payment_proof_message(
msg: &[u8],
) -> Result<(u64, pedersen::Commitment, DalekPublicKey), Error> {
let mut rdr = Cursor::new(msg);
let amount = rdr.read_u64::<BigEndian>()?;
let mut commit_bytes = [0u8; 33];
for i in 0..33 {
commit_bytes[i] = rdr.read_u8()?;
}
let mut sender_address_bytes = [0u8; 32];
for i in 0..32 {
sender_address_bytes[i] = rdr.read_u8()?;
}
Ok((
amount,
pedersen::Commitment::from_vec(commit_bytes.to_vec()),
DalekPublicKey::from_bytes(&sender_address_bytes).unwrap(),
))
}
/// create a payment proof
pub fn create_payment_proof_signature(
amount: u64,
kernel_commitment: &pedersen::Commitment,
sender_address: DalekPublicKey,
sec_key: SecretKey,
) -> Result<DalekSignature, Error> {
let msg = payment_proof_message(amount, kernel_commitment, sender_address)?;
let d_skey = match DalekSecretKey::from_bytes(&sec_key.0) {
Ok(k) => k,
Err(e) => {
return Err(Error::ED25519Key(format!("{}", e)));
}
};
let pub_key: DalekPublicKey = (&d_skey).into();
let keypair = DalekKeypair {
public: pub_key,
secret: d_skey,
};
Ok(keypair.sign(&msg))
}
/// Verify all aspects of a completed payment proof on the current slate
pub fn verify_slate_payment_proof<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
parent_key_id: &Identifier,
context: &Context,
slate: &Slate,
) -> Result<(), Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let tx_vec = updater::retrieve_txs(
wallet,
None,
Some(slate.id),
None,
Some(parent_key_id),
false,
)?;
if tx_vec.is_empty() {
return Err(Error::PaymentProof(
"TxLogEntry with original proof info not found (is account correct?)".to_owned(),
));
}
let orig_proof_info = tx_vec[0].clone().payment_proof;
if orig_proof_info.is_some() && slate.payment_proof.is_none() {
return Err(Error::PaymentProof(
"Expected Payment Proof for this Transaction is not present".to_owned(),
));
}
if let Some(ref p) = slate.clone().payment_proof {
let orig_proof_info = match orig_proof_info {
Some(p) => p.clone(),
None => {
return Err(Error::PaymentProof(
"Original proof info not stored in tx".to_owned(),
));
}
};
let keychain = wallet.keychain(keychain_mask)?;
let index = match context.payment_proof_derivation_index {
Some(i) => i,
None => {
return Err(Error::PaymentProof(
"Payment proof derivation index required".to_owned(),
));
}
};
let orig_sender_sk =
address::address_from_derivation_path(&keychain, parent_key_id, index)?;
let orig_sender_address = OnionV3Address::from_private(&orig_sender_sk.0)?;
if p.sender_address != orig_sender_address.to_ed25519()? {
return Err(Error::PaymentProof(
"Sender address on slate does not match original sender address".to_owned(),
));
}
if orig_proof_info.receiver_address != p.receiver_address {
return Err(Error::PaymentProof(
"Recipient address on slate does not match original recipient address".to_owned(),
));
}
let msg = payment_proof_message(
slate.amount,
&slate.calc_excess(&keychain.secp())?,
orig_sender_address.to_ed25519()?,
)?;
let sig = match p.receiver_signature {
Some(s) => s,
None => {
return Err(Error::PaymentProof(
"Recipient did not provide requested proof signature".to_owned(),
));
}
};
if p.receiver_address.verify(&msg, &sig).is_err() {
return Err(Error::PaymentProof("Invalid proof signature".to_owned()));
};
}
Ok(())
}
#[cfg(test)]
mod test {
use super::*;
use rand::rngs::mock::StepRng;
use crate::grin_core::core::{FeeFields, KernelFeatures};
use crate::grin_core::libtx::{build, ProofBuilder};
use crate::grin_keychain::{
BlindSum, BlindingFactor, ExtKeychain, ExtKeychainPath, Keychain, SwitchCommitmentType,
};
use crate::grin_util::{secp, static_secp_instance};
#[test]
// demonstrate that input.commitment == referenced output.commitment
// based on the public key and amount begin spent
fn output_commitment_equals_input_commitment_on_spend() {
let keychain = ExtKeychain::from_random_seed(false).unwrap();
let builder = ProofBuilder::new(&keychain);
let key_id1 = ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier();
let tx1 = build::transaction(
KernelFeatures::Plain {
fee: FeeFields::zero(),
},
&[build::output(105, key_id1.clone())],
&keychain,
&builder,
)
.unwrap();
let tx2 = build::transaction(
KernelFeatures::Plain {
fee: FeeFields::zero(),
},
&[build::input(105, key_id1.clone())],
&keychain,
&builder,
)
.unwrap();
let inputs: Vec<_> = tx2.inputs().into();
assert_eq!(tx1.outputs()[0].commitment(), inputs[0].commitment());
}
#[test]
fn payment_proof_construction() {
let secp_inst = static_secp_instance();
let secp = secp_inst.lock();
let mut test_rng = StepRng::new(1_234_567_890_u64, 1);
let sec_key = secp::key::SecretKey::new(&secp, &mut test_rng);
let d_skey = DalekSecretKey::from_bytes(&sec_key.0).unwrap();
let address: DalekPublicKey = (&d_skey).into();
let kernel_excess = {
ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier();
let keychain = ExtKeychain::from_random_seed(true).unwrap();
let switch = SwitchCommitmentType::Regular;
let id1 = ExtKeychain::derive_key_id(1, 1, 0, 0, 0);
let id2 = ExtKeychain::derive_key_id(1, 2, 0, 0, 0);
let skey1 = keychain.derive_key(0, &id1, switch).unwrap();
let skey2 = keychain.derive_key(0, &id2, switch).unwrap();
let blinding_factor = keychain
.blind_sum(
&BlindSum::new()
.sub_blinding_factor(BlindingFactor::from_secret_key(skey1))
.add_blinding_factor(BlindingFactor::from_secret_key(skey2)),
)
.unwrap();
keychain
.secp()
.commit(0, blinding_factor.secret_key(&keychain.secp()).unwrap())
.unwrap()
};
let amount = 1_234_567_890_u64;
let msg = payment_proof_message(amount, &kernel_excess, address).unwrap();
println!("payment proof message is (len {}): {:?}", msg.len(), msg);
let decoded = _decode_payment_proof_message(&msg).unwrap();
assert_eq!(decoded.0, amount);
assert_eq!(decoded.1, kernel_excess);
assert_eq!(decoded.2, address);
let sig = create_payment_proof_signature(amount, &kernel_excess, address, sec_key).unwrap();
assert!(address.verify(&msg, &sig).is_ok());
}
}
-885
View File
@@ -1,885 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Utilities to check the status of all the outputs we have stored in
//! the wallet storage and update them.
use std::collections::{HashMap, HashSet};
use uuid::Uuid;
use crate::error::Error;
use crate::grin_core::consensus::reward;
use crate::grin_core::core::{Output, TxKernel};
use crate::grin_core::global;
use crate::grin_core::libtx::proof::ProofBuilder;
use crate::grin_core::libtx::reward;
use crate::grin_keychain::{Identifier, Keychain, SwitchCommitmentType};
use crate::grin_util as util;
use crate::grin_util::secp::key::SecretKey;
use crate::grin_util::secp::pedersen;
use crate::grin_util::static_secp_instance;
use crate::internal::keys;
use crate::types::{
NodeClient, OutputData, OutputStatus, TxLogEntry, TxLogEntryType, WalletBackend, WalletInfo,
};
use crate::{
BlockFees, CbData, OutputCommitMapping, RetrieveTxQueryArgs, RetrieveTxQuerySortField,
RetrieveTxQuerySortOrder,
};
use num_bigint::BigInt;
/// Retrieve all of the outputs (doesn't attempt to update from node)
pub fn retrieve_outputs<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
show_spent: bool,
tx_id: Option<u32>,
parent_key_id: Option<&Identifier>,
) -> Result<Vec<OutputCommitMapping>, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
// just read the wallet here, no need for a write lock
let mut outputs = wallet
.iter()
.filter(|out| show_spent || out.status != OutputStatus::Spent)
.collect::<Vec<_>>();
// only include outputs with a given tx_id if provided
if let Some(id) = tx_id {
outputs = outputs
.into_iter()
.filter(|out| out.tx_log_entry == Some(id))
.collect::<Vec<_>>();
}
if let Some(k) = parent_key_id {
outputs = outputs
.iter()
.filter(|o| o.root_key_id == *k)
.cloned()
.collect()
}
outputs.sort_by_key(|out| out.n_child);
let keychain = wallet.keychain(keychain_mask)?;
let res = outputs
.into_iter()
.map(|output| {
let commit = match output.commit.clone() {
Some(c) => pedersen::Commitment::from_vec(util::from_hex(&c).unwrap()),
None => keychain
.commit(output.value, &output.key_id, SwitchCommitmentType::Regular)
.unwrap(), // TODO: proper support for different switch commitment schemes
};
OutputCommitMapping { output, commit }
})
.collect();
Ok(res)
}
/// Apply advanced filtering to resultset from retrieve_txs below
pub fn apply_advanced_tx_list_filtering<'a, T: ?Sized, C, K>(
wallet: &mut T,
query_args: &RetrieveTxQueryArgs,
) -> Vec<TxLogEntry>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
// Apply simple bool, GTE or LTE fields
let txs_iter: Box<dyn Iterator<Item = TxLogEntry>> = Box::new(
wallet
.tx_log_iter()
.filter(|tx_entry| {
if let Some(v) = query_args.exclude_cancelled {
if v {
tx_entry.tx_type != TxLogEntryType::TxReceivedCancelled
&& tx_entry.tx_type != TxLogEntryType::TxSentCancelled
} else {
true
}
} else {
true
}
})
.filter(|tx_entry| {
if let Some(v) = query_args.include_outstanding_only {
if v {
!tx_entry.confirmed
} else {
true
}
} else {
true
}
})
.filter(|tx_entry| {
if let Some(v) = query_args.include_confirmed_only {
if v {
tx_entry.confirmed
} else {
true
}
} else {
true
}
})
.filter(|tx_entry| {
if let Some(v) = query_args.include_sent_only {
if v {
tx_entry.tx_type == TxLogEntryType::TxSent
|| tx_entry.tx_type == TxLogEntryType::TxSentCancelled
} else {
true
}
} else {
true
}
})
.filter(|tx_entry| {
if let Some(v) = query_args.include_received_only {
if v {
tx_entry.tx_type == TxLogEntryType::TxReceived
|| tx_entry.tx_type == TxLogEntryType::TxReceivedCancelled
} else {
true
}
} else {
true
}
})
.filter(|tx_entry| {
if let Some(v) = query_args.include_coinbase_only {
if v {
tx_entry.tx_type == TxLogEntryType::ConfirmedCoinbase
} else {
true
}
} else {
true
}
})
.filter(|tx_entry| {
if let Some(v) = query_args.include_reverted_only {
if v {
tx_entry.tx_type == TxLogEntryType::TxReverted
} else {
true
}
} else {
true
}
})
.filter(|tx_entry| {
if let Some(v) = query_args.min_id {
tx_entry.id >= v
} else {
true
}
})
.filter(|tx_entry| {
if let Some(v) = query_args.max_id {
tx_entry.id <= v
} else {
true
}
})
.filter(|tx_entry| {
if let Some(v) = query_args.min_amount {
if tx_entry.tx_type == TxLogEntryType::TxSent
|| tx_entry.tx_type == TxLogEntryType::TxSentCancelled
{
BigInt::from(tx_entry.amount_debited)
- BigInt::from(tx_entry.amount_credited)
>= BigInt::from(v)
} else {
BigInt::from(tx_entry.amount_credited)
- BigInt::from(tx_entry.amount_debited)
>= BigInt::from(v)
}
} else {
true
}
})
.filter(|tx_entry| {
if let Some(v) = query_args.max_amount {
if tx_entry.tx_type == TxLogEntryType::TxSent
|| tx_entry.tx_type == TxLogEntryType::TxSentCancelled
{
BigInt::from(tx_entry.amount_debited)
- BigInt::from(tx_entry.amount_credited)
<= BigInt::from(v)
} else {
BigInt::from(tx_entry.amount_credited)
- BigInt::from(tx_entry.amount_debited)
<= BigInt::from(v)
}
} else {
true
}
})
.filter(|tx_entry| {
if let Some(v) = query_args.min_creation_timestamp {
tx_entry.creation_ts >= v
} else {
true
}
})
.filter(|tx_entry| {
if let Some(v) = query_args.min_confirmed_timestamp {
tx_entry.creation_ts <= v
} else {
true
}
})
.filter(|tx_entry| {
if let Some(v) = query_args.min_confirmed_timestamp {
if let Some(t) = tx_entry.confirmation_ts {
t >= v
} else {
true
}
} else {
true
}
})
.filter(|tx_entry| {
if let Some(v) = query_args.max_confirmed_timestamp {
if let Some(t) = tx_entry.confirmation_ts {
t <= v
} else {
true
}
} else {
true
}
}),
);
let mut return_txs: Vec<TxLogEntry> = txs_iter.collect();
// Now apply requested sorting
if let Some(ref s) = query_args.sort_field {
match s {
RetrieveTxQuerySortField::Id => {
return_txs.sort_by_key(|tx| tx.id);
}
RetrieveTxQuerySortField::CreationTimestamp => {
return_txs.sort_by_key(|tx| tx.creation_ts);
}
RetrieveTxQuerySortField::ConfirmationTimestamp => {
return_txs.sort_by_key(|tx| tx.confirmation_ts);
}
RetrieveTxQuerySortField::TotalAmount => {
return_txs.sort_by_key(|tx| {
if tx.tx_type == TxLogEntryType::TxSent
|| tx.tx_type == TxLogEntryType::TxSentCancelled
{
BigInt::from(tx.amount_debited) - BigInt::from(tx.amount_credited)
} else {
BigInt::from(tx.amount_credited) - BigInt::from(tx.amount_debited)
}
});
}
RetrieveTxQuerySortField::AmountCredited => {
return_txs.sort_by_key(|tx| tx.amount_credited);
}
RetrieveTxQuerySortField::AmountDebited => {
return_txs.sort_by_key(|tx| tx.amount_debited);
}
}
} else {
return_txs.sort_by_key(|tx| tx.id);
}
if let Some(ref s) = query_args.sort_order {
match s {
RetrieveTxQuerySortOrder::Desc => return_txs.reverse(),
_ => {}
}
}
// Apply limit if requested
if let Some(l) = query_args.limit {
return_txs = return_txs.into_iter().take(l as usize).collect()
}
return_txs
}
/// Retrieve all of the transaction entries, or a particular entry
/// if `parent_key_id` is set, only return entries from that key
pub fn retrieve_txs<'a, T: ?Sized, C, K>(
wallet: &mut T,
tx_id: Option<u32>,
tx_slate_id: Option<Uuid>,
query_args: Option<RetrieveTxQueryArgs>,
parent_key_id: Option<&Identifier>,
outstanding_only: bool,
) -> Result<Vec<TxLogEntry>, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let mut txs;
// Adding in new transaction list query logic. If `tx_id` or `tx_slate_id`
// is provided, then `query_args` is ignored and old logic is followed.
if query_args.is_some() && tx_id.is_none() && tx_slate_id.is_none() {
txs = apply_advanced_tx_list_filtering(wallet, &query_args.unwrap())
} else {
txs = wallet
.tx_log_iter()
.filter(|tx_entry| {
let f_pk = match parent_key_id {
Some(k) => tx_entry.parent_key_id == *k,
None => true,
};
let f_tx_id = match tx_id {
Some(i) => tx_entry.id == i,
None => true,
};
let f_txs = match tx_slate_id {
Some(t) => tx_entry.tx_slate_id == Some(t),
None => true,
};
let f_outstanding = match outstanding_only {
true => {
!tx_entry.confirmed
&& (tx_entry.tx_type == TxLogEntryType::TxReceived
|| tx_entry.tx_type == TxLogEntryType::TxSent
|| tx_entry.tx_type == TxLogEntryType::TxReverted)
}
false => true,
};
f_pk && f_tx_id && f_txs && f_outstanding
})
.collect();
txs.sort_by_key(|tx| tx.creation_ts);
}
Ok(txs)
}
/// Refreshes the outputs in a wallet with the latest information
/// from a node
pub fn refresh_outputs<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
parent_key_id: &Identifier,
update_all: bool,
) -> Result<(), Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let height = wallet.w2n_client().get_chain_tip()?.0;
refresh_output_state(wallet, keychain_mask, height, parent_key_id, update_all)?;
Ok(())
}
/// build a local map of wallet outputs keyed by commit
/// and a list of outputs we want to query the node for
pub fn map_wallet_outputs<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
parent_key_id: &Identifier,
update_all: bool,
) -> Result<HashMap<pedersen::Commitment, (Identifier, Option<u64>, Option<u32>, bool)>, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let mut wallet_outputs = HashMap::new();
let keychain = wallet.keychain(keychain_mask)?;
let unspents: Vec<OutputData> = wallet
.iter()
.filter(|x| x.root_key_id == *parent_key_id && x.status != OutputStatus::Spent)
.collect();
let tx_entries = retrieve_txs(wallet, None, None, None, Some(&parent_key_id), true)?;
// Only select outputs that are actually involved in an outstanding transaction
let unspents = match update_all {
false => unspents
.into_iter()
.filter(|x| match x.tx_log_entry.as_ref() {
Some(t) => tx_entries.iter().any(|te| te.id == *t),
None => true,
})
.collect(),
true => unspents,
};
for out in unspents {
let commit = match out.commit.clone() {
Some(c) => pedersen::Commitment::from_vec(util::from_hex(&c).unwrap()),
None => keychain
.commit(out.value, &out.key_id, SwitchCommitmentType::Regular)
.unwrap(), // TODO: proper support for different switch commitment schemes
};
let val = (
out.key_id.clone(),
out.mmr_index,
out.tx_log_entry,
out.status == OutputStatus::Unspent,
);
wallet_outputs.insert(commit, val);
}
Ok(wallet_outputs)
}
/// Cancel transaction and associated outputs
pub fn cancel_tx_and_outputs<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
mut tx: TxLogEntry,
outputs: Vec<OutputData>,
parent_key_id: &Identifier,
) -> Result<(), Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let mut batch = wallet.batch(keychain_mask)?;
for mut o in outputs {
// unlock locked outputs
if o.status == OutputStatus::Unconfirmed || o.status == OutputStatus::Reverted {
batch.delete(&o.key_id, &o.mmr_index)?;
}
if o.status == OutputStatus::Locked {
o.status = OutputStatus::Unspent;
batch.save(o)?;
}
}
match tx.tx_type {
TxLogEntryType::TxSent => tx.tx_type = TxLogEntryType::TxSentCancelled,
TxLogEntryType::TxReceived | TxLogEntryType::TxReverted => {
tx.tx_type = TxLogEntryType::TxReceivedCancelled
}
_ => {}
}
batch.save_tx_log_entry(tx, parent_key_id)?;
batch.commit()?;
Ok(())
}
/// Apply refreshed API output data to the wallet
pub fn apply_api_outputs<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
wallet_outputs: &HashMap<pedersen::Commitment, (Identifier, Option<u64>, Option<u32>, bool)>,
api_outputs: &HashMap<pedersen::Commitment, (String, u64, u64)>,
reverted_kernels: HashSet<u32>,
height: u64,
parent_key_id: &Identifier,
) -> Result<(), Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
// now for each commit, find the output in the wallet and the corresponding
// api output (if it exists) and refresh it in-place in the wallet.
// Note: minimizing the time we spend holding the wallet lock.
{
let last_confirmed_height = wallet.last_confirmed_height()?;
// If the server height is less than our confirmed height, don't apply
// these changes as the chain is syncing, incorrect or forking
if height < last_confirmed_height {
warn!(
"Not updating outputs as the height of the node's chain \
is less than the last reported wallet update height."
);
warn!("Please wait for sync on node to complete or fork to resolve and try again.");
return Ok(());
}
let mut batch = wallet.batch(keychain_mask)?;
for (commit, (id, mmr_index, _, _)) in wallet_outputs.iter() {
if let Ok(mut output) = batch.get(id, mmr_index) {
match api_outputs.get(&commit) {
Some(o) => {
// if this is a coinbase tx being confirmed, it's recordable in tx log
if output.is_coinbase && output.status == OutputStatus::Unconfirmed {
let log_id = batch.next_tx_log_id(parent_key_id)?;
let mut t = TxLogEntry::new(
parent_key_id.clone(),
TxLogEntryType::ConfirmedCoinbase,
log_id,
);
t.confirmed = true;
t.amount_credited = output.value;
t.amount_debited = 0;
t.num_outputs = 1;
// calculate kernel excess for coinbase
{
let secp = static_secp_instance();
let secp = secp.lock();
let over_commit = secp.commit_value(output.value)?;
let excess = secp.commit_sum(vec![*commit], vec![over_commit])?;
t.kernel_excess = Some(excess);
t.kernel_lookup_min_height = Some(height);
}
t.update_confirmation_ts();
output.tx_log_entry = Some(log_id);
batch.save_tx_log_entry(t, &parent_key_id)?;
}
// also mark the transaction in which this output is involved as confirmed
// note that one involved input/output confirmation SHOULD be enough
// to reliably confirm the tx
if !output.is_coinbase
&& (output.status == OutputStatus::Unconfirmed
|| output.status == OutputStatus::Reverted)
{
let tx = batch.tx_log_iter().find(|t| {
Some(t.id) == output.tx_log_entry
&& t.parent_key_id == *parent_key_id
});
if let Some(mut t) = tx {
if t.tx_type == TxLogEntryType::TxReverted {
t.tx_type = TxLogEntryType::TxReceived;
t.reverted_after = None;
}
t.update_confirmation_ts();
t.confirmed = true;
batch.save_tx_log_entry(t, &parent_key_id)?;
}
}
output.height = o.1;
output.mark_unspent();
}
None => {
if !output.is_coinbase
&& output
.tx_log_entry
.map(|i| reverted_kernels.contains(&i))
.unwrap_or(false)
{
output.mark_reverted();
} else {
output.mark_spent();
}
}
}
batch.save(output)?;
}
}
for mut tx in batch.tx_log_iter() {
if reverted_kernels.contains(&tx.id) && tx.parent_key_id == *parent_key_id {
tx.tx_type = TxLogEntryType::TxReverted;
tx.reverted_after = tx.confirmation_ts.clone().and_then(|t| {
let now = chrono::Utc::now();
(now - t).to_std().ok()
});
tx.confirmed = false;
batch.save_tx_log_entry(tx, &parent_key_id)?;
}
}
{
batch.save_last_confirmed_height(parent_key_id, height)?;
}
batch.commit()?;
}
Ok(())
}
/// Builds a single api query to retrieve the latest output data from the node.
/// So we can refresh the local wallet outputs.
fn refresh_output_state<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
height: u64,
parent_key_id: &Identifier,
update_all: bool,
) -> Result<(), Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
debug!("Refreshing wallet outputs");
// build a local map of wallet outputs keyed by commit
// and a list of outputs we want to query the node for
let wallet_outputs = map_wallet_outputs(wallet, keychain_mask, parent_key_id, update_all)?;
let wallet_output_keys = wallet_outputs.keys().copied().collect();
let api_outputs = wallet
.w2n_client()
.get_outputs_from_node(wallet_output_keys)?;
// For any disappeared output, check the on-chain status of the corresponding transaction kernel
// If it is no longer present, the transaction was reverted due to a re-org
let reverted_kernels =
find_reverted_kernels(wallet, &wallet_outputs, &api_outputs, parent_key_id)?;
apply_api_outputs(
wallet,
keychain_mask,
&wallet_outputs,
&api_outputs,
reverted_kernels,
height,
parent_key_id,
)?;
clean_old_unconfirmed(wallet, keychain_mask, height)?;
Ok(())
}
fn find_reverted_kernels<'a, T: ?Sized, C, K>(
wallet: &mut T,
wallet_outputs: &HashMap<pedersen::Commitment, (Identifier, Option<u64>, Option<u32>, bool)>,
api_outputs: &HashMap<pedersen::Commitment, (String, u64, u64)>,
parent_key_id: &Identifier,
) -> Result<HashSet<u32>, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let mut client = wallet.w2n_client().clone();
let mut ids = HashSet::new();
// Get transaction IDs for outputs that are no longer unspent
for (commit, (_, _, tx_id, was_unspent)) in wallet_outputs {
if let Some(tx_id) = *tx_id {
if *was_unspent && !api_outputs.contains_key(commit) {
ids.insert(tx_id);
}
}
}
// Get corresponding kernels
let kernels = wallet
.tx_log_iter()
.filter(|t| {
ids.contains(&t.id)
&& t.parent_key_id == *parent_key_id
&& t.tx_type == TxLogEntryType::TxReceived
})
.filter_map(|t| {
t.kernel_excess
.map(|e| (t.id, e, t.kernel_lookup_min_height))
});
// Check each of the kernels on-chain
let mut reverted = HashSet::new();
for (id, excess, min_height) in kernels {
if client.get_kernel(&excess, min_height, None)?.is_none() {
reverted.insert(id);
}
}
Ok(reverted)
}
fn clean_old_unconfirmed<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
height: u64,
) -> Result<(), Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
if height < 50 {
return Ok(());
}
let mut ids_to_del = vec![];
for out in wallet.iter() {
if out.status == OutputStatus::Unconfirmed
&& out.height > 0
&& out.height < height - 50
&& out.is_coinbase
{
ids_to_del.push(out.key_id.clone())
}
}
let mut batch = wallet.batch(keychain_mask)?;
for id in ids_to_del {
batch.delete(&id, &None)?;
}
batch.commit()?;
Ok(())
}
/// Retrieve summary info about the wallet
/// caller should refresh first if desired
pub fn retrieve_info<'a, T: ?Sized, C, K>(
wallet: &mut T,
parent_key_id: &Identifier,
minimum_confirmations: u64,
) -> Result<WalletInfo, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let current_height = wallet.last_confirmed_height()?;
let outputs = wallet
.iter()
.filter(|out| out.root_key_id == *parent_key_id);
let mut unspent_total = 0;
let mut immature_total = 0;
let mut awaiting_finalization_total = 0;
let mut unconfirmed_total = 0;
let mut locked_total = 0;
let mut reverted_total = 0;
for out in outputs {
match out.status {
OutputStatus::Unspent => {
if out.is_coinbase && out.lock_height > current_height {
immature_total += out.value;
} else if out.num_confirmations(current_height) < minimum_confirmations {
// Treat anything less than minimum confirmations as "unconfirmed".
unconfirmed_total += out.value;
} else {
unspent_total += out.value;
}
}
OutputStatus::Unconfirmed => {
// We ignore unconfirmed coinbase outputs completely.
if !out.is_coinbase {
if minimum_confirmations == 0 {
unconfirmed_total += out.value;
} else {
awaiting_finalization_total += out.value;
}
}
}
OutputStatus::Locked => {
locked_total += out.value;
}
OutputStatus::Reverted => reverted_total += out.value,
OutputStatus::Spent => {}
}
}
Ok(WalletInfo {
last_confirmed_height: current_height,
minimum_confirmations,
total: unspent_total + unconfirmed_total + immature_total,
amount_awaiting_finalization: awaiting_finalization_total,
amount_awaiting_confirmation: unconfirmed_total,
amount_immature: immature_total,
amount_locked: locked_total,
amount_currently_spendable: unspent_total,
amount_reverted: reverted_total,
})
}
/// Build a coinbase output and insert into wallet
pub fn build_coinbase<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
block_fees: &BlockFees,
test_mode: bool,
) -> Result<CbData, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let (out, kern, block_fees) = receive_coinbase(wallet, keychain_mask, block_fees, test_mode)?;
Ok(CbData {
output: out,
kernel: kern,
key_id: block_fees.key_id,
})
}
//TODO: Split up the output creation and the wallet insertion
/// Build a coinbase output and the corresponding kernel
pub fn receive_coinbase<'a, T: ?Sized, C, K>(
wallet: &mut T,
keychain_mask: Option<&SecretKey>,
block_fees: &BlockFees,
test_mode: bool,
) -> Result<(Output, TxKernel, BlockFees), Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let height = block_fees.height;
let lock_height = height + global::coinbase_maturity();
let key_id = block_fees.key_id();
let parent_key_id = wallet.parent_key_id();
let key_id = match key_id {
Some(key_id) => match keys::retrieve_existing_key(wallet, key_id, None) {
Ok(k) => k.0,
Err(_) => keys::next_available_key(wallet, keychain_mask)?,
},
None => keys::next_available_key(wallet, keychain_mask)?,
};
{
// Now acquire the wallet lock and write the new output.
let amount = reward(block_fees.fees);
let commit = wallet.calc_commit_for_cache(keychain_mask, amount, &key_id)?;
let mut batch = wallet.batch(keychain_mask)?;
batch.save(OutputData {
root_key_id: parent_key_id,
key_id: key_id.clone(),
n_child: key_id.to_path().last_path_index(),
mmr_index: None,
commit: commit,
value: amount,
status: OutputStatus::Unconfirmed,
height: height,
lock_height: lock_height,
is_coinbase: true,
tx_log_entry: None,
})?;
batch.commit()?;
}
debug!(
"receive_coinbase: built candidate output - {:?}, {}",
key_id.clone(),
key_id,
);
let mut block_fees = block_fees.clone();
block_fees.key_id = Some(key_id.clone());
debug!("receive_coinbase: {:?}", block_fees);
let keychain = wallet.keychain(keychain_mask)?;
let (out, kern) = reward::output(
&keychain,
&ProofBuilder::new(&keychain),
&key_id,
block_fees.fees,
test_mode,
)?;
Ok((out, kern, block_fees))
}
-90
View File
@@ -1,90 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Higher level wallet functions which can be used by callers to operate
//! on the wallet, as well as helpers to invoke and instantiate wallets
//! and listeners
#![deny(non_upper_case_globals)]
#![deny(non_camel_case_types)]
#![deny(non_snake_case)]
#![deny(unused_mut)]
#![warn(missing_docs)]
use grin_wallet_config as config;
use grin_core;
use grin_keychain;
use grin_util;
use grin_wallet_util as util;
use blake2_rfc as blake2;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate log;
#[macro_use]
extern crate lazy_static;
extern crate strum;
#[macro_use]
extern crate strum_macros;
pub mod address;
pub mod api_impl;
mod error;
mod internal;
pub mod mwixnet;
mod slate;
pub mod slate_versions;
pub mod slatepack;
mod types;
pub use crate::error::Error;
pub use crate::slate::{ParticipantData, Slate, SlateState};
pub use crate::slate_versions::v4::sig_is_blank;
pub use crate::slate_versions::{
SlateVersion, VersionedBinSlate, VersionedCoinbase, VersionedSlate, CURRENT_SLATE_VERSION,
GRIN_BLOCK_HEADER_VERSION,
};
pub use crate::slatepack::{
Slatepack, SlatepackAddress, SlatepackArmor, SlatepackBin, Slatepacker, SlatepackerArgs,
};
pub use api_impl::owner_updater::StatusMessage;
pub use api_impl::types::{
Amount, BlockFees, BuiltOutput, InitTxArgs, InitTxSendArgs, IssueInvoiceTxArgs,
NodeHeightResult, OutputCommitMapping, PaymentProof, RetrieveTxQueryArgs,
RetrieveTxQuerySortField, RetrieveTxQuerySortOrder, VersionInfo,
};
pub use internal::scan::scan;
pub use slate_versions::ser as dalek_ser;
pub use types::{
AcctPathMapping, BlockIdentifier, CbData, Context, NodeClient, NodeVersionInfo, OutputData,
OutputStatus, ScannedBlockInfo, StoredProofInfo, TxLogEntry, TxLogEntryType, TxWrapper,
ViewWallet, WalletBackend, WalletInfo, WalletInitStatus, WalletInst, WalletLCProvider,
WalletOutputBatch,
};
/// Helper for taking a lock on the wallet instance
#[macro_export]
macro_rules! wallet_lock {
($wallet_inst: expr, $wallet: ident) => {
let inst = $wallet_inst.clone();
let mut w_lock = inst.lock();
let w_provider = w_lock.lc_provider()?;
let $wallet = w_provider.wallet_inst()?;
};
}
-24
View File
@@ -1,24 +0,0 @@
// Copyright 2023 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Onion modules for mxmixnet
mod onion;
mod types;
pub use onion::{
create_onion, onion::Onion, onion::OnionError, util as onion_util, ComSigError, ComSignature,
MwixnetPublicKey,
};
pub use types::{Hop, MixnetReqCreationParams, SwapReq};
@@ -1,230 +0,0 @@
// Copyright 2023 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Comsig modules for mxmixnet
use grin_util::secp::{
self as secp256k1zkp, pedersen::Commitment, rand::thread_rng, ContextFlag, Secp256k1, SecretKey,
};
use blake2_rfc::blake2b::Blake2b;
use byteorder::{BigEndian, ByteOrder};
use grin_core::ser::{self, Readable, Reader, Writeable, Writer};
use rand::rngs::mock::StepRng;
use thiserror::Error;
/// A generalized Schnorr signature with a pedersen commitment value & blinding factors as the keys
#[derive(Clone, Debug)]
pub struct ComSignature {
pub_nonce: Commitment,
s: SecretKey,
t: SecretKey,
}
/// Error types for Commitment Signatures
#[derive(Error, Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum ComSigError {
/// Invalid commitment signature
#[error("Commitment signature is invalid")]
InvalidSig,
/// Secp256k1zkp error
#[error("Secp256k1zkp error: {0:?}")]
Secp256k1zkp(secp256k1zkp::Error),
}
impl From<secp256k1zkp::Error> for ComSigError {
fn from(err: secp256k1zkp::Error) -> ComSigError {
ComSigError::Secp256k1zkp(err)
}
}
impl ComSignature {
/// Create a new ComSignature
pub fn new(pub_nonce: &Commitment, s: &SecretKey, t: &SecretKey) -> ComSignature {
ComSignature {
pub_nonce: pub_nonce.to_owned(),
s: s.to_owned(),
t: t.to_owned(),
}
}
/// Sign commitment with amount, blinding factor, and message
pub fn sign(
amount: u64,
blind: &SecretKey,
msg: &Vec<u8>,
use_test_rng: bool,
) -> Result<ComSignature, ComSigError> {
let secp = Secp256k1::with_caps(ContextFlag::Commit);
let mut amt_bytes = [0; 32];
BigEndian::write_u64(&mut amt_bytes[24..32], amount);
let k_amt = SecretKey::from_slice(&secp, &amt_bytes)?;
let k_1;
let k_2;
if use_test_rng {
// allow for consistent test results
let mut test_rng = StepRng::new(1_234_567_890_u64, 1);
k_1 = SecretKey::new(&secp, &mut test_rng);
k_2 = SecretKey::new(&secp, &mut test_rng);
} else {
k_1 = SecretKey::new(&secp, &mut thread_rng());
k_2 = SecretKey::new(&secp, &mut thread_rng());
}
let commitment = secp.commit(amount, blind.clone())?;
let nonce_commitment = secp.commit_blind(k_1.clone(), k_2.clone())?;
let e = ComSignature::calc_challenge(
&secp,
&commitment,
&nonce_commitment,
&msg,
use_test_rng,
)?;
// s = k_1 + (e * amount)
let mut s = k_amt.clone();
s.mul_assign(&secp, &e)?;
s.add_assign(&secp, &k_1)?;
// t = k_2 + (e * blind)
let mut t = blind.clone();
t.mul_assign(&secp, &e)?;
t.add_assign(&secp, &k_2)?;
Ok(ComSignature::new(&nonce_commitment, &s, &t))
}
/// Verify the commitment signature
pub fn verify(&self, commit: &Commitment, msg: &Vec<u8>) -> Result<(), ComSigError> {
let secp = Secp256k1::with_caps(ContextFlag::Commit);
let s1 = secp.commit_blind(self.s.clone(), self.t.clone())?;
let mut ce = commit.to_pubkey(&secp)?;
let e = ComSignature::calc_challenge(&secp, &commit, &self.pub_nonce, &msg, false)?;
ce.mul_assign(&secp, &e)?;
let commits = vec![Commitment::from_pubkey(&secp, &ce)?, self.pub_nonce.clone()];
let s2 = secp.commit_sum(commits, Vec::new())?;
if s1 != s2 {
return Err(ComSigError::InvalidSig);
}
Ok(())
}
fn calc_challenge(
secp: &Secp256k1,
commit: &Commitment,
nonce_commit: &Commitment,
msg: &Vec<u8>,
use_test_rng: bool,
) -> Result<SecretKey, ComSigError> {
let mut challenge_hasher = Blake2b::new(32);
if use_test_rng {
return Ok(super::secp::random_secret(use_test_rng));
}
challenge_hasher.update(&commit.0);
challenge_hasher.update(&nonce_commit.0);
challenge_hasher.update(msg);
let mut challenge = [0; 32];
challenge.copy_from_slice(challenge_hasher.finalize().as_bytes());
Ok(SecretKey::from_slice(&secp, &challenge)?)
}
}
/// Serializes a ComSignature to and from hex
pub mod comsig_serde {
use super::ComSignature;
use grin_core::ser::{self, ProtocolVersion};
use grin_util::ToHex;
use serde::{Deserialize, Serializer};
/// Serializes a ComSignature as a hex string
pub fn serialize<S>(comsig: &ComSignature, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
use serde::ser::Error;
let bytes = ser::ser_vec(&comsig, ProtocolVersion::local()).map_err(Error::custom)?;
serializer.serialize_str(&bytes.to_hex())
}
/// Creates a ComSignature from a hex string
pub fn deserialize<'de, D>(deserializer: D) -> Result<ComSignature, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
let bytes = String::deserialize(deserializer)
.and_then(|string| grin_util::from_hex(&string).map_err(Error::custom))?;
let sig: ComSignature = ser::deserialize_default(&mut &bytes[..]).map_err(Error::custom)?;
Ok(sig)
}
}
#[allow(non_snake_case)]
impl Readable for ComSignature {
fn read<R: Reader>(reader: &mut R) -> Result<Self, ser::Error> {
let R = Commitment::read(reader)?;
let s = super::secp::read_secret_key(reader)?;
let t = super::secp::read_secret_key(reader)?;
Ok(ComSignature::new(&R, &s, &t))
}
}
impl Writeable for ComSignature {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ser::Error> {
writer.write_fixed_bytes(self.pub_nonce.0)?;
writer.write_fixed_bytes(self.s.0)?;
writer.write_fixed_bytes(self.t.0)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::{ComSigError, ComSignature, ContextFlag, Secp256k1, SecretKey};
use grin_util::secp::rand::{thread_rng, RngCore};
use rand::Rng;
/// Test signing and verification of ComSignatures
#[test]
fn verify_comsig() -> Result<(), ComSigError> {
let secp = Secp256k1::with_caps(ContextFlag::Commit);
let amount = thread_rng().next_u64();
let blind = SecretKey::new(&secp, &mut thread_rng());
let msg: [u8; 16] = rand::thread_rng().gen();
let comsig = ComSignature::sign(amount, &blind, &msg.to_vec(), false)?;
let commit = secp.commit(amount, blind.clone())?;
assert!(comsig.verify(&commit, &msg.to_vec()).is_ok());
let wrong_msg: [u8; 16] = rand::thread_rng().gen();
assert!(comsig.verify(&commit, &wrong_msg.to_vec()).is_err());
let wrong_commit = secp.commit(amount, SecretKey::new(&secp, &mut thread_rng()))?;
assert!(comsig.verify(&wrong_commit, &msg.to_vec()).is_err());
Ok(())
}
}
-297
View File
@@ -1,297 +0,0 @@
// Copyright 2023 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Dalek key wrapper for mwixnet primitives
use grin_util::secp::key::SecretKey;
use ed25519_dalek::{PublicKey, Signature, Verifier};
use grin_core::ser::{self, Readable, Reader, Writeable, Writer};
use grin_util::ToHex;
use thiserror::Error;
/// Error types for Dalek structures and logic
#[derive(Clone, Error, Debug, PartialEq)]
pub enum DalekError {
/// Hex deser error
#[error("Hex error {0:?}")]
HexError(String),
/// Key parsing error
#[error("Failed to parse secret key")]
KeyParseError,
/// Error validating signature
#[error("Failed to verify signature")]
SigVerifyFailed,
}
/// Encapsulates an ed25519_dalek::PublicKey and provides (de-)serialization
#[derive(Clone, Debug, PartialEq)]
pub struct DalekPublicKey(PublicKey);
impl DalekPublicKey {
/// Convert DalekPublicKey to hex string
pub fn to_hex(&self) -> String {
self.0.to_hex()
}
/// Convert hex string to DalekPublicKey.
pub fn from_hex(hex: &str) -> Result<Self, DalekError> {
let bytes = grin_util::from_hex(hex)
.map_err(|_| DalekError::HexError(format!("failed to decode {}", hex)))?;
let pk = PublicKey::from_bytes(bytes.as_ref())
.map_err(|_| DalekError::HexError(format!("failed to decode {}", hex)))?;
Ok(DalekPublicKey(pk))
}
/// Compute DalekPublicKey from a SecretKey
pub fn from_secret(key: &SecretKey) -> Self {
let secret = ed25519_dalek::SecretKey::from_bytes(&key.0).unwrap();
let pk: PublicKey = (&secret).into();
DalekPublicKey(pk)
}
}
impl AsRef<PublicKey> for DalekPublicKey {
fn as_ref(&self) -> &PublicKey {
&self.0
}
}
#[cfg(test)]
/// Serializes an Option<DalekPublicKey> to and from hex
pub mod option_dalek_pubkey_serde {
use super::DalekPublicKey;
use grin_util::ToHex;
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serializer};
///
pub fn serialize<S>(pk: &Option<DalekPublicKey>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match pk {
Some(pk) => serializer.serialize_str(&pk.0.to_hex()),
None => serializer.serialize_none(),
}
}
///
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<DalekPublicKey>, D::Error>
where
D: Deserializer<'de>,
{
Option::<String>::deserialize(deserializer).and_then(|res| match res {
Some(string) => DalekPublicKey::from_hex(&string)
.map_err(|e| Error::custom(e.to_string()))
.and_then(|pk: DalekPublicKey| Ok(Some(pk))),
None => Ok(None),
})
}
}
impl Readable for DalekPublicKey {
fn read<R: Reader>(reader: &mut R) -> Result<Self, ser::Error> {
let pk = PublicKey::from_bytes(&reader.read_fixed_bytes(32)?)
.map_err(|_| ser::Error::CorruptedData)?;
Ok(DalekPublicKey(pk))
}
}
impl Writeable for DalekPublicKey {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ser::Error> {
writer.write_fixed_bytes(self.0.to_bytes())?;
Ok(())
}
}
/// Encapsulates an ed25519_dalek::Signature and provides (de-)serialization
#[derive(Clone, Debug, PartialEq)]
pub struct DalekSignature(Signature);
impl DalekSignature {
/// Convert hex string to DalekSignature.
pub fn from_hex(hex: &str) -> Result<Self, DalekError> {
let bytes = grin_util::from_hex(hex)
.map_err(|_| DalekError::HexError(format!("failed to decode {}", hex)))?;
let sig = Signature::from_bytes(bytes.as_ref())
.map_err(|_| DalekError::HexError(format!("failed to decode {}", hex)))?;
Ok(DalekSignature(sig))
}
/// Verifies DalekSignature
pub fn verify(&self, pk: &DalekPublicKey, msg: &[u8]) -> Result<(), DalekError> {
pk.as_ref()
.verify(&msg, &self.0)
.map_err(|_| DalekError::SigVerifyFailed)
}
}
impl AsRef<Signature> for DalekSignature {
fn as_ref(&self) -> &Signature {
&self.0
}
}
/// Serializes a DalekSignature to and from hex
#[cfg(test)]
pub mod dalek_sig_serde {
use super::DalekSignature;
use grin_util::ToHex;
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serializer};
///
pub fn serialize<S>(sig: &DalekSignature, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&sig.0.to_hex())
}
///
pub fn deserialize<'de, D>(deserializer: D) -> Result<DalekSignature, D::Error>
where
D: Deserializer<'de>,
{
let str = String::deserialize(deserializer)?;
let sig = DalekSignature::from_hex(&str).map_err(|e| Error::custom(e.to_string()))?;
Ok(sig)
}
}
/// Dalek signature sign wrapper
// TODO: This is likely duplicated throughout crate, check
#[cfg(test)]
pub fn sign(sk: &SecretKey, message: &[u8]) -> Result<DalekSignature, DalekError> {
use ed25519_dalek::{Keypair, Signer};
let secret =
ed25519_dalek::SecretKey::from_bytes(&sk.0).map_err(|_| DalekError::KeyParseError)?;
let public: PublicKey = (&secret).into();
let keypair = Keypair { secret, public };
let sig = keypair.sign(&message);
Ok(DalekSignature(sig))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mwixnet::onion::test_util::rand_keypair;
use grin_core::ser::{self, ProtocolVersion};
use grin_util::ToHex;
use rand::Rng;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Serialize, Deserialize, PartialEq, Clone, Debug)]
struct TestPubKeySerde {
#[serde(with = "option_dalek_pubkey_serde", default)]
pk: Option<DalekPublicKey>,
}
#[test]
fn pubkey_test() -> Result<(), Box<dyn std::error::Error>> {
// Test from_hex
let rand_pk = rand_keypair().1;
let pk_from_hex = DalekPublicKey::from_hex(rand_pk.0.to_hex().as_str()).unwrap();
assert_eq!(rand_pk.0, pk_from_hex.0);
// Test ser (de-)serialization
let bytes = ser::ser_vec(&rand_pk, ProtocolVersion::local()).unwrap();
assert_eq!(bytes.len(), 32);
let pk_from_deser: DalekPublicKey = ser::deserialize_default(&mut &bytes[..]).unwrap();
assert_eq!(rand_pk.0, pk_from_deser.0);
// Test serde with Some(rand_pk)
let some = TestPubKeySerde {
pk: Some(rand_pk.clone()),
};
let val = serde_json::to_value(some.clone()).unwrap();
if let Value::Object(o) = &val {
if let Value::String(s) = o.get("pk").unwrap() {
assert_eq!(s, &rand_pk.0.to_hex());
} else {
panic!("Invalid type");
}
} else {
panic!("Invalid type")
}
assert_eq!(some, serde_json::from_value(val).unwrap());
// Test serde with empty pk field
let none = TestPubKeySerde { pk: None };
let val = serde_json::to_value(none.clone()).unwrap();
if let Value::Object(o) = &val {
if let Value::Null = o.get("pk").unwrap() {
// ok
} else {
panic!("Invalid type");
}
} else {
panic!("Invalid type")
}
assert_eq!(none, serde_json::from_value(val).unwrap());
// Test serde with no pk field
let none2 = serde_json::from_str::<TestPubKeySerde>("{}").unwrap();
assert_eq!(none, none2);
Ok(())
}
#[derive(Serialize, Deserialize, PartialEq, Clone, Debug)]
struct TestSigSerde {
#[serde(with = "dalek_sig_serde")]
sig: DalekSignature,
}
#[test]
fn sig_test() -> Result<(), Box<dyn std::error::Error>> {
// Sign a message
let (sk, pk) = rand_keypair();
let msg: [u8; 16] = rand::thread_rng().gen();
let sig = sign(&sk, &msg).unwrap();
// Verify signature
assert!(sig.verify(&pk, &msg).is_ok());
// Wrong message
let wrong_msg: [u8; 16] = rand::thread_rng().gen();
assert!(sig.verify(&pk, &wrong_msg).is_err());
// Wrong pubkey
let wrong_pk = rand_keypair().1;
assert!(sig.verify(&wrong_pk, &msg).is_err());
// Test from_hex
let sig_from_hex = DalekSignature::from_hex(sig.0.to_hex().as_str()).unwrap();
assert_eq!(sig.0, sig_from_hex.0);
// Test serde (de-)serialization
let serde_test = TestSigSerde { sig: sig.clone() };
let val = serde_json::to_value(serde_test.clone()).unwrap();
if let Value::Object(o) = &val {
if let Value::String(s) = o.get("sig").unwrap() {
assert_eq!(s, &sig.0.to_hex());
} else {
panic!("Invalid type");
}
} else {
panic!("Invalid type")
}
assert_eq!(serde_test, serde_json::from_value(val).unwrap());
Ok(())
}
}
-21
View File
@@ -1,21 +0,0 @@
// Copyright 2024 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Onion and comsig modules for mxmixnet
pub mod comsig;
pub mod dalek;
pub mod secp;
pub use comsig::{comsig_serde, ComSigError, ComSignature};
@@ -1,98 +0,0 @@
// Copyright 2024 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! SECP operations for comsig
pub use grin_util::secp::{
self as secp256k1zkp,
constants::SECRET_KEY_SIZE,
key::{SecretKey, ZERO_KEY},
pedersen::Commitment,
rand::thread_rng,
ContextFlag, Secp256k1,
};
use grin_core::ser::{self, Reader};
use rand::rngs::mock::StepRng;
/// Generate a random SecretKey.
pub fn random_secret(use_test_rng: bool) -> SecretKey {
let secp = Secp256k1::new();
if use_test_rng {
// allow for consistent test results
let mut test_rng = StepRng::new(1_234_567_890_u64, 1);
SecretKey::new(&secp, &mut test_rng)
} else {
SecretKey::new(&secp, &mut thread_rng())
}
}
/// Deserialize a SecretKey from a Reader
pub fn read_secret_key<R: Reader>(reader: &mut R) -> Result<SecretKey, ser::Error> {
let buf = reader.read_fixed_bytes(SECRET_KEY_SIZE)?;
let secp = Secp256k1::with_caps(ContextFlag::None);
let pk = SecretKey::from_slice(&secp, &buf).map_err(|_| ser::Error::CorruptedData)?;
Ok(pk)
}
/// Build a Pedersen Commitment using the provided value and blinding factor
#[cfg(test)]
pub fn commit(value: u64, blind: &SecretKey) -> Result<Commitment, secp256k1zkp::Error> {
let secp = Secp256k1::with_caps(ContextFlag::Commit);
let commit = secp.commit(value, blind.clone())?;
Ok(commit)
}
/// Add a blinding factor to an existing Commitment
pub fn add_excess(
commitment: &Commitment,
excess: &SecretKey,
) -> Result<Commitment, secp256k1zkp::Error> {
let secp = Secp256k1::with_caps(ContextFlag::Commit);
let excess_commit: Commitment = secp.commit(0, excess.clone())?;
let commits = vec![commitment.clone(), excess_commit.clone()];
let sum = secp.commit_sum(commits, Vec::new())?;
Ok(sum)
}
/// Subtracts a value (v*H) from an existing commitment
pub fn sub_value(commitment: &Commitment, value: u64) -> Result<Commitment, secp256k1zkp::Error> {
let secp = Secp256k1::with_caps(ContextFlag::Commit);
let neg_commit: Commitment = secp.commit(value, ZERO_KEY)?;
let sum = secp.commit_sum(vec![commitment.clone()], vec![neg_commit.clone()])?;
Ok(sum)
}
/// Signs the message with the provided SecretKey
#[cfg(test)]
#[allow(dead_code)]
pub fn sign(
sk: &SecretKey,
msg: &grin_util::secp::Message,
) -> Result<grin_util::secp::Signature, secp256k1zkp::Error> {
let secp = Secp256k1::with_caps(ContextFlag::Full);
let pubkey = grin_util::secp::PublicKey::from_secret_key(&secp, &sk)?;
let sig = grin_util::secp::aggsig::sign_single(
&secp,
&msg,
&sk,
None,
None,
None,
Some(&pubkey),
None,
)?;
Ok(sig)
}
-207
View File
@@ -1,207 +0,0 @@
// Copyright 2024 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Onion module definition
mod crypto;
pub mod onion;
pub mod util;
pub use crypto::{
comsig_serde, dalek::DalekPublicKey as MwixnetPublicKey, ComSigError, ComSignature,
};
use chacha20::cipher::StreamCipher;
use grin_core::core::FeeFields;
use grin_util::secp::{
pedersen::{Commitment, RangeProof},
SecretKey,
};
use x25519_dalek::PublicKey as xPublicKey;
use x25519_dalek::{SharedSecret, StaticSecret};
use crypto::secp::random_secret;
use onion::{new_stream_cipher, Onion, OnionError, Payload, RawBytes};
/// Onion hop struct
#[derive(Clone)]
pub struct Hop {
/// Comsig server public key
pub server_pubkey: xPublicKey,
/// Kernel excess
pub excess: SecretKey,
/// Fee
pub fee: FeeFields,
/// Rangeproof
pub rangeproof: Option<RangeProof>,
}
/// Crate a new hop
#[cfg(test)]
pub fn new_hop(
server_key: &SecretKey,
hop_excess: &SecretKey,
fee: u32,
proof: Option<RangeProof>,
) -> Hop {
Hop {
server_pubkey: xPublicKey::from(&StaticSecret::from(server_key.0.clone())),
excess: hop_excess.clone(),
fee: FeeFields::from(fee as u32),
rangeproof: proof,
}
}
/// Create an Onion for the Commitment, encrypting the payload for each hop
pub fn create_onion(
commitment: &Commitment,
hops: &Vec<Hop>,
use_test_rng: bool,
) -> Result<Onion, OnionError> {
if hops.is_empty() {
return Ok(Onion {
ephemeral_pubkey: xPublicKey::from([0u8; 32]),
commit: commitment.clone(),
enc_payloads: vec![],
});
}
let mut shared_secrets: Vec<SharedSecret> = Vec::new();
let mut enc_payloads: Vec<RawBytes> = Vec::new();
let mut ephemeral_sk = StaticSecret::from(random_secret(use_test_rng).0);
let onion_ephemeral_pk = xPublicKey::from(&ephemeral_sk);
for i in 0..hops.len() {
let hop = &hops[i];
let shared_secret = ephemeral_sk.diffie_hellman(&hop.server_pubkey);
shared_secrets.push(shared_secret);
ephemeral_sk = StaticSecret::from(random_secret(use_test_rng).0);
let next_ephemeral_pk = if i < (hops.len() - 1) {
xPublicKey::from(&ephemeral_sk)
} else {
xPublicKey::from([0u8; 32])
};
let payload = Payload {
next_ephemeral_pk,
excess: hop.excess.clone(),
fee: hop.fee.clone(),
rangeproof: hop.rangeproof.clone(),
};
enc_payloads.push(payload.serialize()?);
}
for i in (0..shared_secrets.len()).rev() {
let mut cipher = new_stream_cipher(&shared_secrets[i])?;
for j in i..shared_secrets.len() {
cipher.apply_keystream(&mut enc_payloads[j]);
}
}
let onion = Onion {
ephemeral_pubkey: onion_ephemeral_pk,
commit: commitment.clone(),
enc_payloads,
};
Ok(onion)
}
/// Internal tests
#[allow(missing_docs, dead_code)]
#[cfg(test)]
pub mod test_util {
use super::*;
use crypto::dalek::DalekPublicKey;
use crypto::secp;
use grin_core::core::hash::Hash;
use grin_util::secp::Secp256k1;
use grin_util::ToHex;
use rand::{thread_rng, RngCore};
pub fn rand_onion() -> Onion {
let commit = rand_commit();
let mut hops = Vec::new();
let k = (thread_rng().next_u64() % 5) + 1;
for i in 0..k {
let rangeproof = if i == (k - 1) {
Some(rand_proof())
} else {
None
};
let hop = new_hop(
&random_secret(false),
&random_secret(false),
thread_rng().next_u32(),
rangeproof,
);
hops.push(hop);
}
create_onion(&commit, &hops, false).unwrap()
}
pub fn rand_commit() -> Commitment {
secp::commit(rand::thread_rng().next_u64(), &secp::random_secret(false)).unwrap()
}
pub fn rand_hash() -> Hash {
Hash::from_hex(secp::random_secret(false).to_hex().as_str()).unwrap()
}
pub fn rand_proof() -> RangeProof {
let secp = Secp256k1::new();
secp.bullet_proof(
rand::thread_rng().next_u64(),
secp::random_secret(false),
secp::random_secret(false),
secp::random_secret(false),
None,
None,
)
}
pub fn proof(
value: u64,
fee: u32,
input_blind: &SecretKey,
hop_excesses: &Vec<&SecretKey>,
) -> (Commitment, RangeProof) {
let secp = Secp256k1::new();
let mut blind = input_blind.clone();
for hop_excess in hop_excesses {
blind.add_assign(&secp, &hop_excess).unwrap();
}
let out_value = value - (fee as u64);
let rp = secp.bullet_proof(
out_value,
blind.clone(),
secp::random_secret(false),
secp::random_secret(false),
None,
None,
);
(secp::commit(out_value, &blind).unwrap(), rp)
}
pub fn rand_keypair() -> (SecretKey, DalekPublicKey) {
let sk = random_secret(false);
let pk = DalekPublicKey::from_secret(&sk);
(sk, pk)
}
}
-438
View File
@@ -1,438 +0,0 @@
// Copyright 2023 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Onion defn for mwixnet
use super::util::{read_optional, vec_to_array, write_optional};
use std::convert::TryFrom;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::result::Result;
use chacha20::cipher::{NewCipher, StreamCipher};
use chacha20::{ChaCha20, Key, Nonce};
use grin_core::core::FeeFields;
use grin_core::ser::{self, Readable, Reader, Writeable, Writer};
use grin_util::secp::{
self as secp256k1zkp,
key::SecretKey,
pedersen::{Commitment, RangeProof},
};
use grin_util::{self, ToHex};
use hmac::digest::InvalidLength;
use hmac::{Hmac, Mac};
use serde::ser::SerializeStruct;
use serde::Deserialize;
use sha2::Sha256;
use thiserror::Error;
use x25519_dalek::{PublicKey as xPublicKey, SharedSecret, StaticSecret};
use super::crypto::secp;
type HmacSha256 = Hmac<Sha256>;
/// Raw bytes alias
pub type RawBytes = Vec<u8>;
const CURRENT_ONION_VERSION: u8 = 0;
/// A data packet with layers of encryption
#[derive(Clone, Debug)]
pub struct Onion {
/// The onion originator's portion of the shared secret
pub ephemeral_pubkey: xPublicKey,
/// The pedersen commitment before adjusting the excess and subtracting the fee
pub commit: Commitment,
/// The encrypted payloads which represent the layers of the onion
pub enc_payloads: Vec<RawBytes>,
}
impl PartialEq for Onion {
fn eq(&self, other: &Onion) -> bool {
*self.ephemeral_pubkey.as_bytes() == *other.ephemeral_pubkey.as_bytes()
&& self.commit == other.commit
&& self.enc_payloads == other.enc_payloads
}
}
impl Eq for Onion {}
impl Hash for Onion {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write(self.ephemeral_pubkey.as_bytes());
state.write(self.commit.as_ref());
state.write_usize(self.enc_payloads.len());
for p in &self.enc_payloads {
state.write(p.as_slice());
}
}
}
/// A single, decrypted/peeled layer of an Onion.
#[derive(Debug, Clone)]
pub struct Payload {
/// PK of next server
pub next_ephemeral_pk: xPublicKey,
/// Excess calculation
pub excess: SecretKey,
/// Fee
pub fee: FeeFields,
/// Rangeproof
pub rangeproof: Option<RangeProof>,
}
impl Payload {
/// Deserialize
pub fn deserialize(bytes: &Vec<u8>) -> Result<Payload, ser::Error> {
let payload: Payload = ser::deserialize_default(&mut &bytes[..])?;
Ok(payload)
}
/// Serialize
pub fn serialize(&self) -> Result<Vec<u8>, ser::Error> {
let mut vec = vec![];
ser::serialize_default(&mut vec, &self)?;
Ok(vec)
}
}
impl Readable for Payload {
fn read<R: Reader>(reader: &mut R) -> Result<Payload, ser::Error> {
let version = reader.read_u8()?;
if version != CURRENT_ONION_VERSION {
return Err(ser::Error::UnsupportedProtocolVersion);
}
let next_ephemeral_pk =
xPublicKey::from(vec_to_array::<32>(&reader.read_fixed_bytes(32)?)?);
let excess = secp::read_secret_key(reader)?;
let fee = FeeFields::try_from(reader.read_u64()?).map_err(|_| ser::Error::CorruptedData)?;
let rangeproof = read_optional(reader)?;
Ok(Payload {
next_ephemeral_pk,
excess,
fee,
rangeproof,
})
}
}
impl Writeable for Payload {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ser::Error> {
writer.write_u8(CURRENT_ONION_VERSION)?;
writer.write_fixed_bytes(&self.next_ephemeral_pk.as_bytes())?;
writer.write_fixed_bytes(&self.excess)?;
writer.write_u64(self.fee.into())?;
write_optional(writer, &self.rangeproof)?;
Ok(())
}
}
/// An onion with a layer decrypted
#[derive(Clone, Debug)]
pub struct PeeledOnion {
/// The payload from the peeled layer
pub payload: Payload,
/// The onion remaining after a layer was peeled
pub onion: Onion,
}
impl Onion {
/// Serialize to binary
pub fn serialize(&self) -> Result<Vec<u8>, ser::Error> {
let mut vec = vec![];
ser::serialize_default(&mut vec, &self)?;
Ok(vec)
}
/// Peel a single layer off of the Onion, returning the peeled Onion and decrypted Payload
pub fn peel_layer(&self, server_key: &SecretKey) -> Result<PeeledOnion, OnionError> {
let shared_secret = StaticSecret::from(server_key.0).diffie_hellman(&self.ephemeral_pubkey);
let mut cipher = new_stream_cipher(&shared_secret)?;
let mut decrypted_bytes = self.enc_payloads[0].clone();
cipher.apply_keystream(&mut decrypted_bytes);
let decrypted_payload = Payload::deserialize(&decrypted_bytes)
.map_err(|e| OnionError::DeserializationError(e))?;
let enc_payloads: Vec<RawBytes> = self
.enc_payloads
.iter()
.enumerate()
.filter(|&(i, _)| i != 0)
.map(|(_, enc_payload)| {
let mut p = enc_payload.clone();
cipher.apply_keystream(&mut p);
p
})
.collect();
let mut commitment = self.commit.clone();
commitment = secp::add_excess(&commitment, &decrypted_payload.excess)
.map_err(|e| OnionError::CalcCommitError(e))?;
commitment = secp::sub_value(&commitment, decrypted_payload.fee.into())
.map_err(|e| OnionError::CalcCommitError(e))?;
let peeled_onion = Onion {
ephemeral_pubkey: decrypted_payload.next_ephemeral_pk,
commit: commitment.clone(),
enc_payloads,
};
Ok(PeeledOnion {
payload: decrypted_payload,
onion: peeled_onion,
})
}
}
/// Create a new stream cipher
pub fn new_stream_cipher(shared_secret: &SharedSecret) -> Result<ChaCha20, OnionError> {
let mut mu_hmac = HmacSha256::new_from_slice(b"MWIXNET")?;
mu_hmac.update(shared_secret.as_bytes());
let mukey = mu_hmac.finalize().into_bytes();
let key = Key::from_slice(&mukey[0..32]);
let nonce = Nonce::from_slice(b"NONCE1234567");
Ok(ChaCha20::new(&key, &nonce))
}
impl Writeable for Onion {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ser::Error> {
writer.write_fixed_bytes(self.ephemeral_pubkey.as_bytes())?;
writer.write_fixed_bytes(&self.commit)?;
writer.write_u64(self.enc_payloads.len() as u64)?;
for p in &self.enc_payloads {
writer.write_u64(p.len() as u64)?;
p.write(writer)?;
}
Ok(())
}
}
impl Readable for Onion {
fn read<R: Reader>(reader: &mut R) -> Result<Onion, ser::Error> {
let pubkey_bytes: [u8; 32] = vec_to_array(&reader.read_fixed_bytes(32)?)?;
let ephemeral_pubkey = xPublicKey::from(pubkey_bytes);
let commit = Commitment::read(reader)?;
let mut enc_payloads: Vec<RawBytes> = Vec::new();
let len = reader.read_u64()?;
for _ in 0..len {
let size = reader.read_u64()?;
let bytes = reader.read_fixed_bytes(size as usize)?;
enc_payloads.push(bytes);
}
Ok(Onion {
ephemeral_pubkey,
commit,
enc_payloads,
})
}
}
impl serde::ser::Serialize for Onion {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
let mut state = serializer.serialize_struct("Onion", 3)?;
state.serialize_field("pubkey", &self.ephemeral_pubkey.as_bytes().to_hex())?;
state.serialize_field("commit", &self.commit.to_hex())?;
let hex_payloads: Vec<String> = self.enc_payloads.iter().map(|v| v.to_hex()).collect();
state.serialize_field("data", &hex_payloads)?;
state.end()
}
}
impl<'de> serde::de::Deserialize<'de> for Onion {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(field_identifier, rename_all = "snake_case")]
enum Field {
Pubkey,
Commit,
Data,
}
struct OnionVisitor;
impl<'de> serde::de::Visitor<'de> for OnionVisitor {
type Value = Onion;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("an Onion")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: serde::de::MapAccess<'de>,
{
let mut pubkey = None;
let mut commit = None;
let mut data = None;
while let Some(key) = map.next_key()? {
match key {
Field::Pubkey => {
let val: String = map.next_value()?;
let vec =
grin_util::from_hex(&val).map_err(serde::de::Error::custom)?;
pubkey =
Some(xPublicKey::from(vec_to_array::<32>(&vec).map_err(
|_| serde::de::Error::custom("Invalid length pubkey"),
)?));
}
Field::Commit => {
let val: String = map.next_value()?;
let vec =
grin_util::from_hex(&val).map_err(serde::de::Error::custom)?;
commit = Some(Commitment::from_vec(vec));
}
Field::Data => {
let val: Vec<String> = map.next_value()?;
let mut vec: Vec<Vec<u8>> = Vec::new();
for hex in val {
vec.push(
grin_util::from_hex(&hex).map_err(serde::de::Error::custom)?,
);
}
data = Some(vec);
}
}
}
Ok(Onion {
ephemeral_pubkey: pubkey.unwrap(),
commit: commit.unwrap(),
enc_payloads: data.unwrap(),
})
}
}
const FIELDS: &[&str] = &["pubkey", "commit", "data"];
deserializer.deserialize_struct("Onion", &FIELDS, OnionVisitor)
}
}
/// Error types for creating and peeling Onions
#[derive(Clone, Error, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum OnionError {
/// Invalid Key Length
#[error("Invalid key length for MAC initialization")]
InvalidKeyLength,
/// Serialization Error
#[error("Serialization error occurred: {0:?}")]
SerializationError(ser::Error),
/// Deserialization Error
#[error("Deserialization error occurred: {0:?}")]
DeserializationError(ser::Error),
/// Error calculating blinding factor
#[error("Error calculating blinding factor: {0:?}")]
CalcBlindError(secp256k1zkp::Error),
/// Error calculating ephemeral pubkey
#[error("Error calculating ephemeral pubkey: {0:?}")]
CalcPubKeyError(secp256k1zkp::Error),
/// Error calculating commit
#[error("Error calculating commitment: {0:?}")]
CalcCommitError(secp256k1zkp::Error),
}
impl From<InvalidLength> for OnionError {
fn from(_err: InvalidLength) -> OnionError {
OnionError::InvalidKeyLength
}
}
impl From<ser::Error> for OnionError {
fn from(err: ser::Error) -> OnionError {
OnionError::SerializationError(err)
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::mwixnet::onion::crypto::secp::random_secret;
use crate::mwixnet::onion::{new_hop, Hop};
use grin_core::core::FeeFields;
/// Test end-to-end Onion creation and unwrapping logic.
#[test]
fn onion() {
let total_fee: u64 = 10;
let fee_per_hop: u32 = 2;
let in_value: u64 = 1000;
let out_value: u64 = in_value - total_fee;
let blind = random_secret(false);
let commitment = secp::commit(in_value, &blind).unwrap();
let mut hops: Vec<Hop> = Vec::new();
let mut keys: Vec<SecretKey> = Vec::new();
let mut final_commit = secp::commit(out_value, &blind).unwrap();
let mut final_blind = blind.clone();
for i in 0..5 {
keys.push(random_secret(false));
let excess = random_secret(false);
let secp = secp256k1zkp::Secp256k1::with_caps(secp256k1zkp::ContextFlag::Commit);
final_blind.add_assign(&secp, &excess).unwrap();
final_commit = secp::add_excess(&final_commit, &excess).unwrap();
let proof = if i == 4 {
let n1 = random_secret(false);
let rp = secp.bullet_proof(
out_value,
final_blind.clone(),
n1.clone(),
n1.clone(),
None,
None,
);
assert!(secp.verify_bullet_proof(final_commit, rp, None).is_ok());
Some(rp)
} else {
None
};
let hop = new_hop(&keys[i], &excess, fee_per_hop, proof);
hops.push(hop);
}
let mut onion_packet =
crate::mwixnet::onion::create_onion(&commitment, &hops, false).unwrap();
let mut payload = Payload {
next_ephemeral_pk: onion_packet.ephemeral_pubkey.clone(),
excess: random_secret(false),
fee: FeeFields::from(fee_per_hop),
rangeproof: None,
};
for i in 0..5 {
let peeled = onion_packet.peel_layer(&keys[i]).unwrap();
payload = peeled.payload;
onion_packet = peeled.onion;
}
assert!(payload.rangeproof.is_some());
assert_eq!(payload.rangeproof.unwrap(), hops[4].rangeproof.unwrap());
assert_eq!(secp::commit(out_value, &final_blind).unwrap(), final_commit);
assert_eq!(payload.fee, FeeFields::from(fee_per_hop));
}
}
-185
View File
@@ -1,185 +0,0 @@
// Copyright 2023 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Util fns for mwixnet
//! TODO: possibly redundant, check or move elsewhere
use grin_core::ser::{self, Readable, Reader, Writeable, Writer};
use std::convert::TryInto;
/// Writes an optional value as '1' + value if Some, or '0' if None
///
/// This function is used to serialize an optional value into a Writer. If the option
/// contains Some value, it writes '1' followed by the serialized value. If the option
/// is None, it just writes '0'.
///
/// # Arguments
///
/// * `writer` - A Writer instance where the data will be written.
/// * `o` - The Optional value that will be written.
///
/// # Returns
///
/// * If successful, returns Ok with nothing.
/// * If an error occurs during writing, returns Err wrapping the error.
///
/// # Example
///
/// ```
/// use grin_wallet_libwallet::mwixnet::onion_util::write_optional;
/// let mut writer:Vec<u8> = vec![];
/// let optional_value: Option<u32> = Some(10);
/// //write_optional(&mut writer, &optional_value);
/// ```
pub fn write_optional<O: Writeable, W: Writer>(
writer: &mut W,
o: &Option<O>,
) -> Result<(), ser::Error> {
match &o {
Some(o) => {
writer.write_u8(1)?;
o.write(writer)?;
}
None => writer.write_u8(0)?,
};
Ok(())
}
/// Reads an optional value as '1' + value if Some, or '0' if None
///
/// This function is used to deserialize an optional value from a Reader. If the first byte
/// read is '0', it returns None. If the first byte is '1', it reads the next value and
/// returns Some(value).
///
/// # Arguments
///
/// * `reader` - A Reader instance from where the data will be read.
///
/// # Returns
///
/// * If successful, returns Ok wrapping an optional value. If the first byte read was '0',
/// returns None. If it was '1', returns Some(value).
/// * If an error occurs during reading, returns Err wrapping the error.
///
/// # Example
///
/// ```
/// use grin_wallet_libwallet::mwixnet::onion_util::read_optional;
/// use grin_core::ser::{BinReader, ProtocolVersion, DeserializationMode};
/// let mut buf: &[u8] = &[1, 0, 0, 0, 10];
/// let mut reader = BinReader::new(&mut buf, ProtocolVersion::local(), DeserializationMode::default());
/// let optional_value: Option<u32> = read_optional(&mut reader).unwrap();
/// assert_eq!(optional_value, Some(10));
/// ```
pub fn read_optional<O: Readable, R: Reader>(reader: &mut R) -> Result<Option<O>, ser::Error> {
let o = if reader.read_u8()? == 0 {
None
} else {
Some(O::read(reader)?)
};
Ok(o)
}
/// Convert a vector to an array of size `S`.
///
/// # Arguments
///
/// * `vec` - The input vector.
///
/// # Returns
///
/// * If successful, returns an `Ok` wrapping an array of size `S` containing
/// the first `S` bytes of `vec`.
/// * If `vec` is smaller than `S`, returns an `Err` indicating a count error.
///
/// # Example
///
/// ```
/// use grin_wallet_libwallet::mwixnet::onion_util::vec_to_array;
/// let v = vec![0, 1, 2, 3, 4, 5];
/// let a = vec_to_array::<4>(&v).unwrap();
/// assert_eq!(a, [0, 1, 2, 3]);
/// ```
pub fn vec_to_array<const S: usize>(vec: &Vec<u8>) -> Result<[u8; S], ser::Error> {
if vec.len() < S {
return Err(ser::Error::CountError);
}
let arr: [u8; S] = vec[0..S].try_into().unwrap();
Ok(arr)
}
#[cfg(test)]
mod tests {
use super::*;
use grin_core::ser::{BinReader, BinWriter, DeserializationMode, ProtocolVersion};
#[test]
fn test_write_optional() {
// Test with Some value
let mut buf: Vec<u8> = vec![];
let val: Option<u32> = Some(10);
write_optional(&mut BinWriter::default(&mut buf), &val).unwrap();
assert_eq!(buf, &[1, 0, 0, 0, 10]); // 1 for Some, then 10 as a little-endian u32
// Test with None value
buf.clear();
let val: Option<u32> = None;
write_optional(&mut BinWriter::default(&mut buf), &val).unwrap();
assert_eq!(buf, &[0]); // 0 for None
}
#[test]
fn test_read_optional() {
// Test with Some value
let mut buf: &[u8] = &[1, 0, 0, 0, 10]; // 1 for Some, then 10 as a little-endian u32
let val: Option<u32> = read_optional(&mut BinReader::new(
&mut buf,
ProtocolVersion::local(),
DeserializationMode::default(),
))
.unwrap();
assert_eq!(val, Some(10));
// Test with None value
buf = &[0]; // 0 for None
let val: Option<u32> = read_optional(&mut BinReader::new(
&mut buf,
ProtocolVersion::local(),
DeserializationMode::default(),
))
.unwrap();
assert_eq!(val, None);
}
#[test]
fn test_vec_to_array_success() {
let v = vec![1, 2, 3, 4, 5, 6, 7, 8];
let a = vec_to_array::<4>(&v).unwrap();
assert_eq!(a, [1, 2, 3, 4]);
}
#[test]
fn test_vec_to_array_too_small() {
let v = vec![1, 2, 3];
let res = vec_to_array::<4>(&v);
assert!(res.is_err());
}
#[test]
fn test_vec_to_array_empty() {
let v = vec![];
let res = vec_to_array::<4>(&v);
assert!(res.is_err());
}
}
-43
View File
@@ -1,43 +0,0 @@
// Copyright 2024 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Types related to mwixnet requests required by rest of lib crate apis
//! Should rexport all needed types here
use super::onion::comsig_serde;
use grin_core::libtx::secp_ser::string_or_u64;
use grin_util::secp::key::SecretKey;
use serde::{Deserialize, Serialize};
pub use super::onion::{onion::Onion, ComSignature, Hop};
/// A Swap request
#[derive(Serialize, Deserialize, Debug)]
pub struct SwapReq {
/// Com signature
#[serde(with = "comsig_serde")]
pub comsig: ComSignature,
/// Onion
pub onion: Onion,
}
/// mwixnetRequest Creation Params
#[derive(Serialize, Deserialize, Debug)]
pub struct MixnetReqCreationParams {
/// List of all the server keys
pub server_keys: Vec<SecretKey>,
/// Fees per hop
#[serde(with = "string_or_u64")]
pub fee_per_hop: u64,
}
File diff suppressed because it is too large Load Diff
-122
View File
@@ -1,122 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! This module contains old slate versions and conversions to the newest slate version
//! Used for serialization and deserialization of slates in a backwards compatible way.
//! Versions earlier than V3 are removed for the 4.0.0 release, but versioning code
//! remains for future needs
use crate::slate::Slate;
use crate::slate_versions::v4::{CoinbaseV4, SlateV4};
use crate::slate_versions::v4_bin::SlateV4Bin;
use crate::types::CbData;
use crate::Error;
use std::convert::TryFrom;
pub mod ser;
#[allow(missing_docs)]
pub mod v4;
#[allow(missing_docs)]
pub mod v4_bin;
/// The most recent version of the slate
pub const CURRENT_SLATE_VERSION: u16 = 4;
/// The grin block header this slate is intended to be compatible with
pub const GRIN_BLOCK_HEADER_VERSION: u16 = 3;
/// Existing versions of the slate
#[derive(EnumIter, Serialize, Deserialize, Clone, Debug, PartialEq, PartialOrd, Eq, Ord)]
pub enum SlateVersion {
/// V4 (most current)
V4,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
/// Versions are ordered newest to oldest so serde attempts to
/// deserialize newer versions first, then falls back to older versions.
pub enum VersionedSlate {
/// Current (4.0.0 Onwards )
V4(SlateV4),
}
impl VersionedSlate {
/// Return slate version
pub fn version(&self) -> SlateVersion {
match *self {
VersionedSlate::V4(_) => SlateVersion::V4,
}
}
/// convert this slate type to a specified older version
pub fn into_version(slate: Slate, version: SlateVersion) -> Result<VersionedSlate, Error> {
match version {
SlateVersion::V4 => Ok(VersionedSlate::V4(slate.into())),
}
}
}
impl From<VersionedSlate> for Slate {
fn from(slate: VersionedSlate) -> Slate {
match slate {
VersionedSlate::V4(s) => Slate::from(s),
}
}
}
#[derive(Deserialize, Serialize)]
#[serde(untagged)]
/// Binary versions, can only be parsed 1:1 into the appropriate
/// version, and VersionedSlate can up/downgrade from there
pub enum VersionedBinSlate {
/// Version 4, binary
V4(SlateV4Bin),
}
impl TryFrom<VersionedSlate> for VersionedBinSlate {
type Error = Error;
fn try_from(slate: VersionedSlate) -> Result<VersionedBinSlate, Error> {
match slate {
VersionedSlate::V4(s) => Ok(VersionedBinSlate::V4(SlateV4Bin(s))),
}
}
}
impl From<VersionedBinSlate> for VersionedSlate {
fn from(slate: VersionedBinSlate) -> VersionedSlate {
match slate {
VersionedBinSlate::V4(s) => VersionedSlate::V4(s.0),
}
}
}
#[derive(Deserialize, Serialize)]
#[serde(untagged)]
/// Versions are ordered newest to oldest so serde attempts to
/// deserialize newer versions first, then falls back to older versions.
pub enum VersionedCoinbase {
/// Current supported coinbase version.
V4(CoinbaseV4),
}
impl VersionedCoinbase {
/// convert this coinbase data to a specific versioned representation for the json api.
pub fn into_version(cb: CbData, version: SlateVersion) -> VersionedCoinbase {
match version {
SlateVersion::V4 => VersionedCoinbase::V4(cb.into()),
}
}
}
-660
View File
@@ -1,660 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Sane serialization & deserialization of cryptographic structs into hex
use serde::{Deserialize, Deserializer, Serializer};
/// Seralizes a byte string into base64
pub fn as_base64<T, S>(bytes: T, serializer: S) -> Result<S::Ok, S::Error>
where
T: AsRef<[u8]>,
S: Serializer,
{
serializer.serialize_str(&base64::encode(&bytes))
}
/// Creates a Vec from a base string
pub fn bytes_from_base64<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
where
D: Deserializer<'de>,
{
use serde::de::Error;
String::deserialize(deserializer)
.and_then(|string| base64::decode(&string).map_err(|err| Error::custom(err.to_string())))
}
/// Serializes an Option<secp::Signature> to and from hex
pub mod option_rangeproof_hex {
use crate::grin_util::secp::pedersen::RangeProof;
use crate::grin_util::{from_hex, ToHex};
use serde::de::{Error, IntoDeserializer};
use serde::{Deserialize, Deserializer, Serializer};
///
pub fn serialize<S>(proof: &Option<RangeProof>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match proof {
Some(p) => serializer.serialize_str(&p.to_hex()),
None => serializer.serialize_none(),
}
}
///
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<RangeProof>, D::Error>
where
D: Deserializer<'de>,
{
Option::<String>::deserialize(deserializer).and_then(|res| match res {
Some(string) => from_hex(&string)
.map_err(|err| Error::custom(err.to_string()))
.and_then(|val| Ok(Some(RangeProof::deserialize(val.into_deserializer())?))),
None => Ok(None),
})
}
}
/// Serializes an OnionV3Address to and from hex
pub mod option_ov3_serde {
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serializer};
use std::convert::TryFrom;
use crate::util::{OnionV3Address, OnionV3AddressError};
///
pub fn serialize<S>(addr: &Option<OnionV3Address>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match addr {
Some(a) => serializer.serialize_str(&a.to_string()),
None => serializer.serialize_none(),
}
}
///
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<OnionV3Address>, D::Error>
where
D: Deserializer<'de>,
{
Option::<String>::deserialize(deserializer).and_then(|res| match res {
Some(s) => OnionV3Address::try_from(s.as_str())
.map_err(|err: OnionV3AddressError| Error::custom(format!("{:?}", err)))
.and_then(|a| Ok(Some(a))),
None => Ok(None),
})
}
}
/// Serializes an OnionV3Address to and from hex
pub mod ov3_serde {
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serializer};
use std::convert::TryFrom;
use crate::util::{OnionV3Address, OnionV3AddressError};
///
pub fn serialize<S>(addr: &OnionV3Address, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&addr.to_string())
}
///
pub fn deserialize<'de, D>(deserializer: D) -> Result<OnionV3Address, D::Error>
where
D: Deserializer<'de>,
{
String::deserialize(deserializer).and_then(|s| {
OnionV3Address::try_from(s.as_str())
.map_err(|err: OnionV3AddressError| Error::custom(format!("{:?}", err)))
.and_then(Ok)
})
}
}
/// Serializes an ed25519 PublicKey to and from hex
pub mod dalek_seckey_serde {
use crate::grin_util::{from_hex, ToHex};
use ed25519_dalek::SecretKey as DalekSecretKey;
use serde::{Deserialize, Deserializer, Serializer};
///
pub fn serialize<S>(key: &DalekSecretKey, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&key.to_bytes().to_hex())
}
///
pub fn deserialize<'de, D>(deserializer: D) -> Result<DalekSecretKey, D::Error>
where
D: Deserializer<'de>,
{
use serde::de::Error;
String::deserialize(deserializer)
.and_then(|string| from_hex(&string).map_err(|err| Error::custom(err.to_string())))
.and_then(|bytes: Vec<u8>| {
DalekSecretKey::from_bytes(&bytes).map_err(|err| Error::custom(err.to_string()))
})
}
}
/// Serializes an ed25519 PublicKey to and from hex
pub mod dalek_pubkey_serde {
use crate::grin_util::{from_hex, ToHex};
use ed25519_dalek::PublicKey as DalekPublicKey;
use serde::{Deserialize, Deserializer, Serializer};
///
pub fn serialize<S>(key: &DalekPublicKey, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&key.to_bytes().to_hex())
}
///
pub fn deserialize<'de, D>(deserializer: D) -> Result<DalekPublicKey, D::Error>
where
D: Deserializer<'de>,
{
use serde::de::Error;
String::deserialize(deserializer)
.and_then(|string| from_hex(&string).map_err(|err| Error::custom(err.to_string())))
.and_then(|bytes: Vec<u8>| {
DalekPublicKey::from_bytes(&bytes).map_err(|err| Error::custom(err.to_string()))
})
}
}
/// Serializes an x25519 PublicKey to and from hex
pub mod dalek_xpubkey_serde {
use crate::grin_util::{from_hex, ToHex};
use serde::{Deserialize, Deserializer, Serializer};
use x25519_dalek::PublicKey as xDalekPublicKey;
///
pub fn serialize<S>(key: &xDalekPublicKey, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&key.as_bytes().to_hex())
}
///
pub fn deserialize<'de, D>(deserializer: D) -> Result<xDalekPublicKey, D::Error>
where
D: Deserializer<'de>,
{
use serde::de::Error;
String::deserialize(deserializer)
.and_then(|string| from_hex(&string).map_err(|err| Error::custom(err.to_string())))
.and_then(|bytes: Vec<u8>| {
let mut b = [0u8; 32];
b.copy_from_slice(&bytes[0..32]);
Ok(xDalekPublicKey::from(b))
})
}
}
/// Serializes an ed25519 PublicKey to and from base64
pub mod dalek_pubkey_base64 {
use base64;
use ed25519_dalek::PublicKey as DalekPublicKey;
use serde::{Deserialize, Deserializer, Serializer};
///
pub fn serialize<S>(key: &DalekPublicKey, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&base64::encode(&key.to_bytes()))
}
///
pub fn deserialize<'de, D>(deserializer: D) -> Result<DalekPublicKey, D::Error>
where
D: Deserializer<'de>,
{
use serde::de::Error;
String::deserialize(deserializer)
.and_then(|string| {
base64::decode(&string).map_err(|err| Error::custom(err.to_string()))
})
.and_then(|bytes: Vec<u8>| {
DalekPublicKey::from_bytes(&bytes).map_err(|err| Error::custom(err.to_string()))
})
}
}
/// Serializes an Option<ed25519_dalek::PublicKey> to and from hex
pub mod option_dalek_pubkey_base64 {
use base64;
use ed25519_dalek::PublicKey as DalekPublicKey;
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serializer};
///
pub fn serialize<S>(key: &Option<DalekPublicKey>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match key {
Some(key) => serializer.serialize_str(&base64::encode(&key.to_bytes())),
None => serializer.serialize_none(),
}
}
///
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<DalekPublicKey>, D::Error>
where
D: Deserializer<'de>,
{
Option::<String>::deserialize(deserializer).and_then(|res| match res {
Some(string) => base64::decode(&string)
.map_err(|err| Error::custom(err.to_string()))
.and_then(|bytes: Vec<u8>| {
let mut b = [0u8; 32];
b.copy_from_slice(&bytes[0..32]);
DalekPublicKey::from_bytes(&b)
.map(Some)
.map_err(|err| Error::custom(err.to_string()))
}),
None => {
println!("None fine");
Ok(None)
}
})
}
}
/// Serializes an Option<ed25519_dalek::PublicKey> to and from hex
pub mod option_dalek_pubkey_serde {
use ed25519_dalek::PublicKey as DalekPublicKey;
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serializer};
use crate::grin_util::{from_hex, ToHex};
///
pub fn serialize<S>(key: &Option<DalekPublicKey>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match key {
Some(key) => serializer.serialize_str(&key.to_bytes().to_hex()),
None => serializer.serialize_none(),
}
}
///
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<DalekPublicKey>, D::Error>
where
D: Deserializer<'de>,
{
Option::<String>::deserialize(deserializer).and_then(|res| match res {
Some(string) => from_hex(&string)
.map_err(|err| Error::custom(err.to_string()))
.and_then(|bytes: Vec<u8>| {
let mut b = [0u8; 32];
b.copy_from_slice(&bytes[0..32]);
DalekPublicKey::from_bytes(&b)
.map(Some)
.map_err(|err| Error::custom(err.to_string()))
}),
None => Ok(None),
})
}
}
/// Serializes an Option<x25519_dalek::PublicKey> to and from hex
pub mod option_xdalek_pubkey_serde {
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serializer};
use x25519_dalek::PublicKey as xDalekPublicKey;
use crate::grin_util::{from_hex, ToHex};
///
pub fn serialize<S>(key: &Option<xDalekPublicKey>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match key {
Some(key) => serializer.serialize_str(&key.as_bytes().to_hex()),
None => serializer.serialize_none(),
}
}
///
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<xDalekPublicKey>, D::Error>
where
D: Deserializer<'de>,
{
Option::<String>::deserialize(deserializer).and_then(|res| match res {
Some(string) => from_hex(&string)
.map_err(|err| Error::custom(err.to_string()))
.and_then(|bytes: Vec<u8>| {
let mut b = [0u8; 32];
b.copy_from_slice(&bytes[0..32]);
Ok(Some(xDalekPublicKey::from(b)))
}),
None => Ok(None),
})
}
}
/// Serializes an ed25519_dalek::Signature to and from hex
pub mod dalek_sig_serde {
use ed25519_dalek::Signature as DalekSignature;
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serializer};
use std::convert::TryFrom;
use crate::grin_util::{from_hex, ToHex};
///
pub fn serialize<S>(sig: &DalekSignature, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&sig.to_bytes().as_ref().to_hex())
}
///
pub fn deserialize<'de, D>(deserializer: D) -> Result<DalekSignature, D::Error>
where
D: Deserializer<'de>,
{
String::deserialize(deserializer)
.and_then(|string| from_hex(&string).map_err(|err| Error::custom(err.to_string())))
.and_then(|bytes: Vec<u8>| {
let mut b = [0u8; 64];
b.copy_from_slice(&bytes[0..64]);
DalekSignature::try_from(b).map_err(|err| Error::custom(err.to_string()))
})
}
}
/// Serializes an Option<ed25519_dalek::PublicKey> to and from hex
pub mod option_dalek_sig_serde {
use ed25519_dalek::Signature as DalekSignature;
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serializer};
use std::convert::TryFrom;
use crate::grin_util::{from_hex, ToHex};
///
pub fn serialize<S>(sig: &Option<DalekSignature>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match sig {
Some(s) => serializer.serialize_str(&s.to_bytes().as_ref().to_hex()),
None => serializer.serialize_none(),
}
}
///
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<DalekSignature>, D::Error>
where
D: Deserializer<'de>,
{
Option::<String>::deserialize(deserializer).and_then(|res| match res {
Some(string) => from_hex(&string)
.map_err(|err| Error::custom(err.to_string()))
.and_then(|bytes: Vec<u8>| {
let mut b = [0u8; 64];
b.copy_from_slice(&bytes[0..64]);
DalekSignature::try_from(b)
.map(Some)
.map_err(|err| Error::custom(err.to_string()))
}),
None => Ok(None),
})
}
}
/// Serializes an Option<ed25519_dalek::PublicKey> to and from base64
pub mod option_dalek_sig_base64 {
use base64;
use ed25519_dalek::Signature as DalekSignature;
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serializer};
use std::convert::TryFrom;
///
pub fn serialize<S>(sig: &Option<DalekSignature>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match sig {
Some(s) => serializer.serialize_str(&base64::encode(&s.to_bytes().to_vec())),
None => serializer.serialize_none(),
}
}
///
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<DalekSignature>, D::Error>
where
D: Deserializer<'de>,
{
Option::<String>::deserialize(deserializer).and_then(|res| match res {
Some(string) => base64::decode(&string)
.map_err(|err| Error::custom(err.to_string()))
.and_then(|bytes: Vec<u8>| {
let mut b = [0u8; 64];
b.copy_from_slice(&bytes[0..64]);
DalekSignature::try_from(b)
.map(Some)
.map_err(|err| Error::custom(err.to_string()))
}),
None => Ok(None),
})
}
}
/// Serializes slates 'version_info' field
pub mod version_info_v4 {
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serializer};
use crate::slate_versions::v4::VersionCompatInfoV4;
///
pub fn serialize<S>(v: &VersionCompatInfoV4, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&format!("{}:{}", v.version, v.block_header_version))
}
///
pub fn deserialize<'de, D>(deserializer: D) -> Result<VersionCompatInfoV4, D::Error>
where
D: Deserializer<'de>,
{
String::deserialize(deserializer).and_then(|s| {
let mut retval = VersionCompatInfoV4 {
version: 0,
block_header_version: 0,
};
let v: Vec<&str> = s.split(':').collect();
if v.len() != 2 {
return Err(Error::custom("Cannot parse version"));
}
match u16::from_str_radix(v[0], 10) {
Ok(u) => retval.version = u,
Err(e) => return Err(Error::custom(format!("Cannot parse version: {}", e))),
}
match u16::from_str_radix(v[1], 10) {
Ok(u) => retval.block_header_version = u,
Err(e) => return Err(Error::custom(format!("Cannot parse version: {}", e))),
}
Ok(retval)
})
}
}
/// Serializes slates 'state' field
pub mod slate_state_v4 {
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serializer};
use crate::slate_versions::v4::SlateStateV4;
///
pub fn serialize<S>(st: &SlateStateV4, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let label = match st {
SlateStateV4::Unknown => "NA",
SlateStateV4::Standard1 => "S1",
SlateStateV4::Standard2 => "S2",
SlateStateV4::Standard3 => "S3",
SlateStateV4::Invoice1 => "I1",
SlateStateV4::Invoice2 => "I2",
SlateStateV4::Invoice3 => "I3",
};
serializer.serialize_str(label)
}
///
pub fn deserialize<'de, D>(deserializer: D) -> Result<SlateStateV4, D::Error>
where
D: Deserializer<'de>,
{
String::deserialize(deserializer).and_then(|s| {
let retval = match s.as_str() {
"NA" => SlateStateV4::Unknown,
"S1" => SlateStateV4::Standard1,
"S2" => SlateStateV4::Standard2,
"S3" => SlateStateV4::Standard3,
"I1" => SlateStateV4::Invoice1,
"I2" => SlateStateV4::Invoice2,
"I3" => SlateStateV4::Invoice3,
_ => return Err(Error::custom("Invalid Slate state")),
};
Ok(retval)
})
}
}
/// Serializes an secp256k1 pubkey to base64
pub mod uuid_base64 {
use base64;
use serde::{Deserialize, Deserializer, Serializer};
use uuid::Uuid;
///
pub fn serialize<S>(id: &Uuid, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&base64::encode(&id.as_bytes()))
}
///
pub fn deserialize<'de, D>(deserializer: D) -> Result<Uuid, D::Error>
where
D: Deserializer<'de>,
{
use serde::de::Error;
String::deserialize(deserializer)
.and_then(|string| {
base64::decode(&string).map_err(|err| Error::custom(err.to_string()))
})
.and_then(|bytes: Vec<u8>| {
let mut b = [0u8; 16];
b.copy_from_slice(&bytes[0..16]);
Ok(Uuid::from_bytes(b))
})
}
}
// Test serialization methods of components that are being used
#[cfg(test)]
mod test {
use super::*;
use rand::rngs::mock::StepRng;
use crate::grin_util::{secp, static_secp_instance};
use ed25519_dalek::Keypair;
use ed25519_dalek::PublicKey as DalekPublicKey;
use ed25519_dalek::SecretKey as DalekSecretKey;
use ed25519_dalek::Signature as DalekSignature;
use ed25519_dalek::Signer;
use serde::Deserialize;
use serde_json;
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
struct SerTest {
#[serde(with = "dalek_pubkey_serde")]
pub pub_key: DalekPublicKey,
#[serde(with = "option_dalek_pubkey_serde")]
pub pub_key_opt: Option<DalekPublicKey>,
#[serde(with = "dalek_sig_serde")]
pub sig: DalekSignature,
#[serde(with = "option_dalek_sig_serde")]
pub sig_opt: Option<DalekSignature>,
}
impl SerTest {
pub fn random() -> SerTest {
let secp_inst = static_secp_instance();
let secp = secp_inst.lock();
let mut test_rng = StepRng::new(1234567890u64, 1);
let sec_key = secp::key::SecretKey::new(&secp, &mut test_rng);
let d_skey = DalekSecretKey::from_bytes(&sec_key.0).unwrap();
let d_pub_key: DalekPublicKey = (&d_skey).into();
let keypair = Keypair {
public: d_pub_key,
secret: d_skey,
};
let d_sig = keypair.sign("test sig".as_bytes());
println!("D sig: {:?}", d_sig);
SerTest {
pub_key: d_pub_key.clone(),
pub_key_opt: Some(d_pub_key),
sig: d_sig.clone(),
sig_opt: Some(d_sig),
}
}
}
#[test]
fn ser_dalek_primitives() {
for _ in 0..10 {
let s = SerTest::random();
println!("Before Serialization: {:?}", s);
let serialized = serde_json::to_string_pretty(&s).unwrap();
println!("JSON: {}", serialized);
let deserialized: SerTest = serde_json::from_str(&serialized).unwrap();
println!("After Serialization: {:?}", deserialized);
println!();
assert_eq!(s, deserialized);
}
}
}
-387
View File
@@ -1,387 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Contains V4 of the slate (grin-wallet 4.0.0)
//! Changes from V3:
//! /#### Top-Level Slate Struct
//! * The `version_info` struct is removed, and is replaced with `ver`, which has the format "[version]:[block header version]"
//! * `sta` is added, with possible values S1|S2|S3|I1|I2|I3|NA
//! * `num_participants` is renamed to `num_parts`
//! * `num_parts` may be omitted from the slate. If omitted its value is assumed to be 2.
//! * `amount` is renamed to `amt`
//! * `amt` may be removed from the slate on the S2 phase of a transaction.
//! * `fee` may be removed from the slate on the S2 phase of a transaction. It may also be ommited when intiating an I1 transaction, and added during the I2 phase.
//! * `lock_height` is removed
//! * `feat` is added to the slate denoting the Kernel feature set. May be omitted from the slate if kernel is plain (0)
//! * `ttl_cutoff_height` is renamed to `ttl`
//! * `ttl` may be omitted from the slate. If omitted its value is assumed to be 0 (no TTL).
//! * The `participant_data` struct is renamed to `sigs`
//! * `tx` is removed
//! * The `coms` (commitments) array is added, from which the final transaction object can be reconstructed
//! * The `payment_proof` struct is renamed to `proof`
//! * The feat_args struct is added, which may be populated for non-Plain kernels
//! * `proof` may be omitted from the slate if it is None (null),
//! * `off` (offset) is added, and will be modified by every participant in the transaction with a random
//! value - the value of their inputs' blinding factors
//!
//! #### Participant Data (`sigs`)
//!
//! * `public_blind_excess` is renamed to `xs`
//! * `public_nonce` is renamed to `nonce`
//! * `part_sig` is renamed to `part`
//! * `part` may be omitted if it has not yet been filled out
//! * `message` is removed
//! * `message_sig` is removed
//! * `id` is removed. Parties can identify themselves via the keys stored in their transaction context
//!
//! #### Payment Proof Data (`proof`)
//!
//! * The `sender_address` field is renamed to `saddr`
//! * The `receiver_address` field is renamed to `raddr`
//! * The `receiver_signature` field is renamed to `rsig`
//! * `rsig` may be omitted if it has not yet been filled out
use crate::grin_core::core::FeeFields;
use crate::grin_core::core::{Input, Output, TxKernel};
use crate::grin_core::libtx::secp_ser;
use crate::grin_keychain::{BlindingFactor, Identifier};
use crate::grin_util::secp;
use crate::grin_util::secp::key::PublicKey;
use crate::grin_util::secp::pedersen::{Commitment, RangeProof};
use crate::grin_util::secp::Signature;
use crate::{slate_versions::ser, CbData};
use ed25519_dalek::PublicKey as DalekPublicKey;
use ed25519_dalek::Signature as DalekSignature;
use uuid::Uuid;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SlateV4 {
// Required Fields
/// Versioning info
#[serde(with = "ser::version_info_v4")]
pub ver: VersionCompatInfoV4,
/// Unique transaction ID, selected by sender
pub id: Uuid,
/// Slate state
#[serde(with = "ser::slate_state_v4")]
pub sta: SlateStateV4,
/// Offset, modified by each participant inserting inputs
/// as the transaction progresses
#[serde(
serialize_with = "secp_ser::as_hex",
deserialize_with = "secp_ser::blind_from_hex"
)]
#[serde(default = "default_offset_zero")]
#[serde(skip_serializing_if = "offset_is_zero")]
pub off: BlindingFactor,
// Optional fields depending on state
/// The number of participants intended to take part in this transaction
#[serde(default = "default_num_participants_2")]
#[serde(skip_serializing_if = "num_parts_is_2")]
pub num_parts: u8,
/// base amount (excluding fee)
#[serde(with = "secp_ser::string_or_u64")]
#[serde(skip_serializing_if = "u64_is_blank")]
#[serde(default = "default_u64_0")]
pub amt: u64,
/// fee
#[serde(skip_serializing_if = "fee_is_zero")]
#[serde(default = "default_fee")]
pub fee: FeeFields,
/// kernel features, if any
#[serde(skip_serializing_if = "u8_is_blank")]
#[serde(default = "default_u8_0")]
pub feat: u8,
/// TTL, the block height at which wallets
/// should refuse to process the transaction and unlock all
#[serde(with = "secp_ser::string_or_u64")]
#[serde(skip_serializing_if = "u64_is_blank")]
#[serde(default = "default_u64_0")]
pub ttl: u64,
// Structs always required
/// Participant data, each participant in the transaction will
/// insert their public data here. For now, 0 is sender and 1
/// is receiver, though this will change for multi-party
pub sigs: Vec<ParticipantDataV4>,
// Situational, but required at some point in the tx
/// Inputs/Output commits added to slate
#[serde(default = "default_coms_none")]
#[serde(skip_serializing_if = "Option::is_none")]
pub coms: Option<Vec<CommitsV4>>,
// Optional Structs
/// Payment Proof
#[serde(default = "default_payment_none")]
#[serde(skip_serializing_if = "Option::is_none")]
pub proof: Option<PaymentInfoV4>,
/// Kernel features arguments
#[serde(default = "default_kernel_features_none")]
#[serde(skip_serializing_if = "Option::is_none")]
pub feat_args: Option<KernelFeaturesArgsV4>,
}
fn default_payment_none() -> Option<PaymentInfoV4> {
None
}
fn default_offset_zero() -> BlindingFactor {
BlindingFactor::zero()
}
fn offset_is_zero(o: &BlindingFactor) -> bool {
*o == BlindingFactor::zero()
}
fn default_coms_none() -> Option<Vec<CommitsV4>> {
None
}
fn default_u64_0() -> u64 {
0
}
fn num_parts_is_2(n: &u8) -> bool {
*n == 2
}
fn default_num_participants_2() -> u8 {
2
}
fn default_kernel_features_none() -> Option<KernelFeaturesArgsV4> {
None
}
/// Slate state definition
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum SlateStateV4 {
/// Unknown, coming from earlier versions of the slate
Unknown,
/// Standard flow, freshly init
Standard1,
/// Standard flow, return journey
Standard2,
/// Standard flow, ready for transaction posting
Standard3,
/// Invoice flow, freshly init
Invoice1,
///Invoice flow, return journey
Invoice2,
/// Invoice flow, ready for tranasction posting
Invoice3,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
/// Kernel features arguments definition
pub struct KernelFeaturesArgsV4 {
/// Lock height, for HeightLocked
pub lock_hgt: u64,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct VersionCompatInfoV4 {
/// The current version of the slate format
pub version: u16,
/// Version of grin block header this slate is compatible with
pub block_header_version: u16,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct ParticipantDataV4 {
/// Public key corresponding to private blinding factor
#[serde(with = "secp_ser::pubkey_serde")]
pub xs: PublicKey,
/// Public key corresponding to private nonce
#[serde(with = "secp_ser::pubkey_serde")]
pub nonce: PublicKey,
/// Public partial signature
#[serde(default = "default_part_sig_none")]
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(with = "secp_ser::option_sig_serde")]
pub part: Option<Signature>,
}
fn default_part_sig_none() -> Option<Signature> {
None
}
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct PaymentInfoV4 {
#[serde(with = "ser::dalek_pubkey_serde")]
pub saddr: DalekPublicKey,
#[serde(with = "ser::dalek_pubkey_serde")]
pub raddr: DalekPublicKey,
#[serde(default = "default_receiver_signature_none")]
#[serde(with = "ser::option_dalek_sig_serde")]
#[serde(skip_serializing_if = "Option::is_none")]
pub rsig: Option<DalekSignature>,
}
fn default_receiver_signature_none() -> Option<DalekSignature> {
None
}
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
pub struct CommitsV4 {
/// Options for an output's structure or use
#[serde(default = "default_output_feature")]
#[serde(skip_serializing_if = "output_feature_is_plain")]
pub f: OutputFeaturesV4,
/// The homomorphic commitment representing the output amount
#[serde(
serialize_with = "secp_ser::as_hex",
deserialize_with = "secp_ser::commitment_from_hex"
)]
pub c: Commitment,
/// A proof that the commitment is in the right range
/// Only applies for transaction outputs
#[serde(with = "ser::option_rangeproof_hex")]
#[serde(default = "default_range_proof")]
#[serde(skip_serializing_if = "Option::is_none")]
pub p: Option<RangeProof>,
}
impl From<&Output> for CommitsV4 {
fn from(out: &Output) -> CommitsV4 {
CommitsV4 {
f: out.features().into(),
c: out.commitment(),
p: Some(out.proof()),
}
}
}
// This will need to be reworked once we no longer support input features with "commit only" inputs.
impl From<&Input> for CommitsV4 {
fn from(input: &Input) -> CommitsV4 {
CommitsV4 {
f: input.features.into(),
c: input.commitment(),
p: None,
}
}
}
fn default_output_feature() -> OutputFeaturesV4 {
OutputFeaturesV4(0)
}
fn output_feature_is_plain(o: &OutputFeaturesV4) -> bool {
o.0 == 0
}
#[derive(Serialize, Deserialize, Copy, Debug, Clone, PartialEq, Eq)]
pub struct OutputFeaturesV4(pub u8);
pub fn sig_is_blank(s: &secp::Signature) -> bool {
for b in s.to_raw_data().iter() {
if *b != 0 {
return false;
}
}
true
}
fn default_range_proof() -> Option<RangeProof> {
None
}
fn u64_is_blank(u: &u64) -> bool {
*u == 0
}
fn default_u8_0() -> u8 {
0
}
fn u8_is_blank(u: &u8) -> bool {
*u == 0
}
fn fee_is_zero(f: &FeeFields) -> bool {
f.is_zero()
}
fn default_fee() -> FeeFields {
FeeFields::zero()
}
/// A mining node requests new coinbase via the foreign api every time a new candidate block is built.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CoinbaseV4 {
/// Output
output: CbOutputV4,
/// Kernel
kernel: CbKernelV4,
/// Key Id
key_id: Option<Identifier>,
}
impl From<CbData> for CoinbaseV4 {
fn from(cb: CbData) -> CoinbaseV4 {
CoinbaseV4 {
output: CbOutputV4::from(&cb.output),
kernel: CbKernelV4::from(&cb.kernel),
key_id: cb.key_id,
}
}
}
impl From<&Output> for CbOutputV4 {
fn from(output: &Output) -> CbOutputV4 {
CbOutputV4 {
features: CbOutputFeatures::Coinbase,
commit: output.commitment(),
proof: output.proof(),
}
}
}
impl From<&TxKernel> for CbKernelV4 {
fn from(kernel: &TxKernel) -> CbKernelV4 {
CbKernelV4 {
features: CbKernelFeatures::Coinbase,
excess: kernel.excess,
excess_sig: kernel.excess_sig,
}
}
}
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
enum CbOutputFeatures {
Coinbase,
}
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
enum CbKernelFeatures {
Coinbase,
}
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
struct CbOutputV4 {
features: CbOutputFeatures,
#[serde(serialize_with = "secp_ser::as_hex")]
commit: Commitment,
#[serde(serialize_with = "secp_ser::as_hex")]
proof: RangeProof,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct CbKernelV4 {
features: CbKernelFeatures,
#[serde(serialize_with = "secp_ser::as_hex")]
excess: Commitment,
#[serde(with = "secp_ser::sig_serde")]
excess_sig: secp::Signature,
}
-592
View File
@@ -1,592 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Wraps a V4 Slate into a V4 Binary slate
use crate::grin_core::core::transaction::{FeeFields, OutputFeatures};
use crate::grin_core::ser as grin_ser;
use crate::grin_core::ser::{Readable, Reader, Writeable, Writer};
use crate::grin_keychain::BlindingFactor;
use crate::grin_util::secp::key::PublicKey;
use crate::grin_util::secp::pedersen::{Commitment, RangeProof};
use crate::grin_util::secp::Signature;
use ed25519_dalek::PublicKey as DalekPublicKey;
use ed25519_dalek::Signature as DalekSignature;
use std::convert::TryFrom;
use uuid::Uuid;
use crate::slate_versions::v4::{
CommitsV4, KernelFeaturesArgsV4, ParticipantDataV4, PaymentInfoV4, SlateStateV4, SlateV4,
VersionCompatInfoV4,
};
impl Writeable for SlateStateV4 {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), grin_ser::Error> {
let b = match self {
SlateStateV4::Unknown => 0,
SlateStateV4::Standard1 => 1,
SlateStateV4::Standard2 => 2,
SlateStateV4::Standard3 => 3,
SlateStateV4::Invoice1 => 4,
SlateStateV4::Invoice2 => 5,
SlateStateV4::Invoice3 => 6,
};
writer.write_u8(b)
}
}
impl Readable for SlateStateV4 {
fn read<R: Reader>(reader: &mut R) -> Result<SlateStateV4, grin_ser::Error> {
let b = reader.read_u8()?;
let sta = match b {
0 => SlateStateV4::Unknown,
1 => SlateStateV4::Standard1,
2 => SlateStateV4::Standard2,
3 => SlateStateV4::Standard3,
4 => SlateStateV4::Invoice1,
5 => SlateStateV4::Invoice2,
6 => SlateStateV4::Invoice3,
_ => SlateStateV4::Unknown,
};
Ok(sta)
}
}
/// Allow serializing of Uuids not defined in crate
struct UuidWrap(Uuid);
impl Writeable for UuidWrap {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), grin_ser::Error> {
writer.write_fixed_bytes(&self.0.as_bytes())
}
}
impl Readable for UuidWrap {
fn read<R: Reader>(reader: &mut R) -> Result<UuidWrap, grin_ser::Error> {
let bytes = reader.read_fixed_bytes(16)?;
let mut b = [0u8; 16];
b.copy_from_slice(&bytes[0..16]);
Ok(UuidWrap(Uuid::from_bytes(b)))
}
}
/// Helper struct to serialize optional fields efficiently
struct SlateOptFields {
/// num parts, default 2
pub num_parts: u8,
/// amt, default 0
pub amt: u64,
/// fee_fields, default FeeFields::zero()
pub fee: FeeFields,
/// kernel features, default 0
pub feat: u8,
/// ttl, default 0
pub ttl: u64,
}
impl Writeable for SlateOptFields {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), grin_ser::Error> {
// Status byte, bits determing which optional fields are serialized
// 0 0 0 1 1 1 1 1
// t f f a n
let mut status = 0u8;
if self.num_parts != 2 {
status |= 0x01;
}
if self.amt > 0 {
status |= 0x02;
}
if self.fee.fee() > 0 {
// apply fee mask past HF4
status |= 0x04;
}
if self.feat > 0 {
status |= 0x08;
}
if self.ttl > 0 {
status |= 0x10;
}
writer.write_u8(status)?;
if status & 0x01 > 0 {
writer.write_u8(self.num_parts)?;
}
if status & 0x02 > 0 {
writer.write_u64(self.amt)?;
}
if status & 0x04 > 0 {
self.fee.write(writer)?;
}
if status & 0x08 > 0 {
writer.write_u8(self.feat)?;
}
if status & 0x10 > 0 {
writer.write_u64(self.ttl)?;
}
Ok(())
}
}
impl Readable for SlateOptFields {
fn read<R: Reader>(reader: &mut R) -> Result<SlateOptFields, grin_ser::Error> {
let status = reader.read_u8()?;
let num_parts = if status & 0x01 > 0 {
reader.read_u8()?
} else {
2
};
let amt = if status & 0x02 > 0 {
reader.read_u64()?
} else {
0
};
let fee = if status & 0x04 > 0 {
FeeFields::read(reader)?
} else {
FeeFields::zero()
};
let feat = if status & 0x08 > 0 {
reader.read_u8()?
} else {
0
};
let ttl = if status & 0x10 > 0 {
reader.read_u64()?
} else {
0
};
Ok(SlateOptFields {
num_parts,
amt,
fee,
feat,
ttl,
})
}
}
struct SigsWrap(Vec<ParticipantDataV4>);
struct SigsWrapRef<'a>(&'a Vec<ParticipantDataV4>);
impl<'a> Writeable for SigsWrapRef<'a> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), grin_ser::Error> {
writer.write_u8(self.0.len() as u8)?;
for s in self.0.iter() {
//0 means part sig is not yet included
//1 means part sig included
if s.part.is_some() {
writer.write_u8(1)?;
} else {
writer.write_u8(0)?;
}
s.xs.write(writer)?;
s.nonce.write(writer)?;
if let Some(s) = s.part {
s.write(writer)?;
}
}
Ok(())
}
}
impl Readable for SigsWrap {
fn read<R: Reader>(reader: &mut R) -> Result<SigsWrap, grin_ser::Error> {
let sigs_len = reader.read_u8()?;
let sigs = {
let mut ret = vec![];
for _ in 0..sigs_len as usize {
let has_partial = reader.read_u8()?;
let c = ParticipantDataV4 {
xs: PublicKey::read(reader)?,
nonce: PublicKey::read(reader)?,
part: match has_partial {
1 => Some(Signature::read(reader)?),
0 | _ => None,
},
};
ret.push(c);
}
ret
};
Ok(SigsWrap(sigs))
}
}
/// Serialization of optional structs
struct SlateOptStructsRef<'a> {
/// coms, default none
pub coms: &'a Option<Vec<CommitsV4>>,
///// proof, default none
pub proof: &'a Option<PaymentInfoV4>,
}
/// Serialization of optional structs
struct SlateOptStructs {
/// coms, default none
pub coms: Option<Vec<CommitsV4>>,
/// proof, default none
pub proof: Option<PaymentInfoV4>,
}
impl<'a> Writeable for SlateOptStructsRef<'a> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), grin_ser::Error> {
// Status byte, bits determing which optional structs are serialized
// 0 0 0 0 0 0 1 1
// p c
let mut status = 0u8;
if self.coms.is_some() {
status |= 0x01
};
if self.proof.is_some() {
status |= 0x02
};
writer.write_u8(status)?;
if let Some(c) = self.coms {
ComsWrapRef(&c).write(writer)?;
}
if let Some(p) = self.proof {
ProofWrapRef(&p).write(writer)?;
}
Ok(())
}
}
impl Readable for SlateOptStructs {
fn read<R: Reader>(reader: &mut R) -> Result<SlateOptStructs, grin_ser::Error> {
let status = reader.read_u8()?;
let coms = if status & 0x01 > 0 {
Some(ComsWrap::read(reader)?.0)
} else {
None
};
let proof = if status & 0x02 > 0 {
Some(ProofWrap::read(reader)?.0)
} else {
None
};
Ok(SlateOptStructs { coms, proof })
}
}
struct ComsWrap(Vec<CommitsV4>);
struct ComsWrapRef<'a>(&'a Vec<CommitsV4>);
impl<'a> Writeable for ComsWrapRef<'a> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), grin_ser::Error> {
writer.write_u16(self.0.len() as u16)?;
for o in self.0.iter() {
//0 means input
//1 means output with proof
if o.p.is_some() {
writer.write_u8(1)?;
} else {
writer.write_u8(0)?;
}
OutputFeatures::from(o.f).write(writer)?;
o.c.write(writer)?;
if let Some(p) = o.p {
p.write(writer)?;
}
}
Ok(())
}
}
impl Readable for ComsWrap {
fn read<R: Reader>(reader: &mut R) -> Result<ComsWrap, grin_ser::Error> {
let coms_len = reader.read_u16()?;
let coms = {
let mut ret = vec![];
for _ in 0..coms_len as usize {
let is_output = reader.read_u8()?;
let c = CommitsV4 {
f: OutputFeatures::read(reader)?.into(),
c: Commitment::read(reader)?,
p: match is_output {
1 => Some(RangeProof::read(reader)?),
0 | _ => None,
},
};
ret.push(c);
}
ret
};
Ok(ComsWrap(coms))
}
}
struct ProofWrap(PaymentInfoV4);
struct ProofWrapRef<'a>(&'a PaymentInfoV4);
impl<'a> Writeable for ProofWrapRef<'a> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), grin_ser::Error> {
writer.write_fixed_bytes(self.0.saddr.to_bytes())?;
writer.write_fixed_bytes(self.0.raddr.to_bytes())?;
match self.0.rsig {
Some(s) => {
writer.write_u8(1)?;
writer.write_fixed_bytes(&s.to_bytes().to_vec())?;
}
None => writer.write_u8(0)?,
}
Ok(())
}
}
impl Readable for ProofWrap {
fn read<R: Reader>(reader: &mut R) -> Result<ProofWrap, grin_ser::Error> {
let saddr = DalekPublicKey::from_bytes(&reader.read_fixed_bytes(32)?).unwrap();
let raddr = DalekPublicKey::from_bytes(&reader.read_fixed_bytes(32)?).unwrap();
let rsig = match reader.read_u8()? {
0 => None,
1 | _ => Some(DalekSignature::try_from(&reader.read_fixed_bytes(64)?[..]).unwrap()),
};
Ok(ProofWrap(PaymentInfoV4 { saddr, raddr, rsig }))
}
}
#[derive(Debug, Clone)]
pub struct SlateV4Bin(pub SlateV4);
impl From<SlateV4> for SlateV4Bin {
fn from(slate: SlateV4) -> SlateV4Bin {
SlateV4Bin(slate)
}
}
impl From<SlateV4Bin> for SlateV4 {
fn from(slate: SlateV4Bin) -> SlateV4 {
slate.0
}
}
impl serde::Serialize for SlateV4Bin {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut vec = vec![];
grin_ser::serialize(&mut vec, grin_ser::ProtocolVersion(4), self)
.map_err(|err| serde::ser::Error::custom(err.to_string()))?;
serializer.serialize_bytes(&vec)
}
}
impl<'de> serde::Deserialize<'de> for SlateV4Bin {
fn deserialize<D>(deserializer: D) -> Result<SlateV4Bin, D::Error>
where
D: serde::Deserializer<'de>,
{
struct SlateV4BinVisitor;
impl<'de> serde::de::Visitor<'de> for SlateV4BinVisitor {
type Value = SlateV4Bin;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(formatter, "a serialised binary V4 slate")
}
fn visit_bytes<E>(self, value: &[u8]) -> Result<SlateV4Bin, E>
where
E: serde::de::Error,
{
let mut reader = std::io::Cursor::new(value.to_vec());
let s = grin_ser::deserialize(
&mut reader,
grin_ser::ProtocolVersion(4),
grin_ser::DeserializationMode::default(),
)
.map_err(|err| serde::de::Error::custom(err.to_string()))?;
Ok(s)
}
}
deserializer.deserialize_bytes(SlateV4BinVisitor)
}
}
impl Writeable for SlateV4Bin {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), grin_ser::Error> {
let v4 = &self.0;
writer.write_u16(v4.ver.version)?;
writer.write_u16(v4.ver.block_header_version)?;
(UuidWrap(v4.id)).write(writer)?;
v4.sta.write(writer)?;
v4.off.write(writer)?;
SlateOptFields {
num_parts: v4.num_parts,
amt: v4.amt,
fee: v4.fee,
feat: v4.feat,
ttl: v4.ttl,
}
.write(writer)?;
(SigsWrapRef(&v4.sigs)).write(writer)?;
SlateOptStructsRef {
coms: &v4.coms,
proof: &v4.proof,
}
.write(writer)?;
// Write lock height for height locked kernels
if v4.feat == 2 {
let lock_hgt = match &v4.feat_args {
Some(l) => l.lock_hgt,
None => 0,
};
writer.write_u64(lock_hgt)?;
}
Ok(())
}
}
impl Readable for SlateV4Bin {
fn read<R: Reader>(reader: &mut R) -> Result<SlateV4Bin, grin_ser::Error> {
let ver = VersionCompatInfoV4 {
version: reader.read_u16()?,
block_header_version: reader.read_u16()?,
};
let id = UuidWrap::read(reader)?.0;
let sta = SlateStateV4::read(reader)?;
let off = BlindingFactor::read(reader)?;
let opts = SlateOptFields::read(reader)?;
let sigs = SigsWrap::read(reader)?.0;
let opt_structs = SlateOptStructs::read(reader)?;
let feat_args = if opts.feat == 2 {
Some(KernelFeaturesArgsV4 {
lock_hgt: reader.read_u64()?,
})
} else {
None
};
Ok(SlateV4Bin(SlateV4 {
ver,
id,
sta,
off,
num_parts: opts.num_parts,
amt: opts.amt,
fee: opts.fee,
feat: opts.feat,
ttl: opts.ttl,
sigs,
coms: opt_structs.coms,
proof: opt_structs.proof,
feat_args,
}))
}
}
#[test]
fn slate_v4_serialize_deserialize() {
use crate::grin_util::from_hex;
use crate::grin_util::secp::key::PublicKey;
use crate::Slate;
use grin_core::global::{set_local_chain_type, ChainTypes};
use grin_keychain::{ExtKeychain, Keychain, SwitchCommitmentType};
set_local_chain_type(ChainTypes::Mainnet);
let slate = Slate::blank(1, false);
let mut v4 = SlateV4::from(slate);
let keychain = ExtKeychain::from_random_seed(true).unwrap();
let switch = SwitchCommitmentType::Regular;
// add some sig data
let id1 = ExtKeychain::derive_key_id(1, 1, 0, 0, 0);
let id2 = ExtKeychain::derive_key_id(1, 1, 1, 0, 0);
let skey1 = keychain.derive_key(0, &id1, switch).unwrap();
let skey2 = keychain.derive_key(0, &id2, switch).unwrap();
let xs = PublicKey::from_secret_key(keychain.secp(), &skey1).unwrap();
let nonce = PublicKey::from_secret_key(keychain.secp(), &skey2).unwrap();
let part = ParticipantDataV4 {
xs,
nonce,
part: None,
};
let part2 = ParticipantDataV4 {
xs,
nonce,
part: Some(Signature::from_raw_data(&[11; 64]).unwrap()),
};
v4.sigs.push(part.clone());
v4.sigs.push(part2);
v4.sigs.push(part);
// add some random commit data
let com1 = CommitsV4 {
f: OutputFeatures::Plain.into(),
c: Commitment::from_vec([3u8; 1].to_vec()),
p: None,
};
let com2 = CommitsV4 {
f: OutputFeatures::Plain.into(),
c: Commitment::from_vec([4u8; 1].to_vec()),
p: Some(RangeProof::zero()),
};
let mut coms = vec![];
coms.push(com1.clone());
coms.push(com1.clone());
coms.push(com1.clone());
coms.push(com2);
v4.coms = Some(coms);
v4.amt = 234324899824;
v4.feat = 1;
v4.num_parts = 2;
v4.feat_args = Some(KernelFeaturesArgsV4 { lock_hgt: 23092039 });
let v4_1 = v4.clone();
let v4_1_copy = v4.clone();
let v4_bin = SlateV4Bin(v4);
let mut vec = Vec::new();
let _ = grin_ser::serialize_default(&mut vec, &v4_bin).expect("serialization failed");
let b4_bin_2: SlateV4Bin = grin_ser::deserialize_default(&mut &vec[..]).unwrap();
let v4_2 = b4_bin_2.0.clone();
assert_eq!(v4_1.ver, v4_2.ver);
assert_eq!(v4_1.id, v4_2.id);
assert_eq!(v4_1.amt, v4_2.amt);
assert_eq!(v4_1.fee, v4_2.fee);
let v4_2_coms = v4_2.coms.as_ref().unwrap().clone();
for (i, c) in v4_1.coms.unwrap().iter().enumerate() {
assert_eq!(c.f, v4_2_coms[i].f);
assert_eq!(c.c, v4_2_coms[i].c);
assert_eq!(c.p, v4_2_coms[i].p);
}
assert_eq!(v4_1.sigs, v4_2.sigs);
assert_eq!(v4_1.proof, v4_2.proof);
// Include Payment proof, remove coms to mix it up a bit
let mut v4 = v4_1_copy;
let raw_pubkey_str = "d03c09e9c19bb74aa9ea44e0fe5ae237a9bf40bddf0941064a80913a4459c8bb";
let b = from_hex(raw_pubkey_str).unwrap();
let d_pkey = DalekPublicKey::from_bytes(&b).unwrap();
v4.proof = Some(PaymentInfoV4 {
raddr: d_pkey.clone(),
saddr: d_pkey.clone(),
rsig: None,
});
v4.coms = None;
let v4_1 = v4.clone();
let v4_bin = SlateV4Bin(v4);
let mut vec = Vec::new();
let _ = grin_ser::serialize_default(&mut vec, &v4_bin).expect("serialization failed");
let b4_bin_2: SlateV4Bin = grin_ser::deserialize_default(&mut &vec[..]).unwrap();
let v4_2 = b4_bin_2.0.clone();
assert_eq!(v4_1.ver, v4_2.ver);
assert_eq!(v4_1.id, v4_2.id);
assert_eq!(v4_1.amt, v4_2.amt);
assert_eq!(v4_1.fee, v4_2.fee);
assert!(v4_1.coms.is_none());
assert_eq!(v4_1.sigs, v4_2.sigs);
assert_eq!(v4_1.proof, v4_2.proof);
}
-287
View File
@@ -1,287 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use bech32::{self, FromBase32, ToBase32};
/// Slatepack Address definition
use ed25519_dalek::PublicKey as edDalekPublicKey;
use ed25519_dalek::SecretKey as edDalekSecretKey;
use rand::{thread_rng, Rng};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use x25519_dalek::PublicKey as xDalekPublicKey;
use crate::grin_core::global;
use crate::grin_core::ser::{self, Readable, Reader, Writeable, Writer};
use crate::grin_util::secp::key::SecretKey;
use crate::util::OnionV3Address;
use crate::Error;
use std::convert::TryFrom;
use std::fmt::{self, Display};
/// Definition of a Slatepack address
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SlatepackAddress {
/// Human-readable prefix
pub hrp: String,
/// ed25519 Public key, to be bech32 encoded,
/// interpreted as tor address or converted
/// to an X25519 public key for encrypting
/// slatepacks
pub pub_key: edDalekPublicKey,
}
impl SlatepackAddress {
/// new with default hrp
pub fn new(pub_key: &edDalekPublicKey) -> Self {
let hrp = match global::get_chain_type() {
global::ChainTypes::Mainnet => "grin",
_ => "tgrin",
};
Self {
hrp: String::from(hrp),
pub_key: pub_key.clone(),
}
}
/// new with a random key
pub fn random() -> Self {
let bytes: [u8; 32] = thread_rng().gen();
let pub_key = edDalekPublicKey::from(&edDalekSecretKey::from_bytes(&bytes).unwrap());
SlatepackAddress::new(&pub_key)
}
/// calculate encoded length
pub fn encoded_len(&self) -> Result<usize, Error> {
let encoded = String::try_from(self)?;
// add length byte
Ok(encoded.as_bytes().len() + 1)
}
/// utility to construct a public key that can be read by age 0.5+,
/// for some reason the author decided the library can no longer accept
/// x25519 keys to construct its types even though it uses them under the hood
pub fn to_age_pubkey_str(&self) -> Result<String, Error> {
let x_key = xDalekPublicKey::try_from(self)?;
Ok(bech32::encode("age", x_key.as_bytes().to_base32())?.to_string())
}
}
impl Display for SlatepackAddress {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str(&String::try_from(self).unwrap())
}
}
impl TryFrom<&str> for SlatepackAddress {
type Error = Error;
fn try_from(encoded: &str) -> Result<Self, Self::Error> {
let (hrp, data) = bech32::decode(&encoded)?;
let bytes = Vec::<u8>::from_base32(&data)?;
let pub_key = match edDalekPublicKey::from_bytes(&bytes) {
Ok(k) => k,
Err(e) => {
return Err(Error::ED25519Key(format!("{}", e)));
}
};
Ok(SlatepackAddress { hrp, pub_key })
}
}
impl TryFrom<&SlatepackAddress> for String {
type Error = Error;
fn try_from(addr: &SlatepackAddress) -> Result<Self, Self::Error> {
let encoded = bech32::encode(&addr.hrp, addr.pub_key.to_bytes().to_base32())?;
Ok(encoded.to_string())
}
}
impl From<&SlatepackAddress> for OnionV3Address {
fn from(addr: &SlatepackAddress) -> Self {
OnionV3Address::from_bytes(addr.pub_key.to_bytes())
}
}
impl TryFrom<OnionV3Address> for SlatepackAddress {
type Error = Error;
fn try_from(addr: OnionV3Address) -> Result<SlatepackAddress, Error> {
Ok(SlatepackAddress::new(&addr.to_ed25519()?))
}
}
impl TryFrom<&SlatepackAddress> for xDalekPublicKey {
type Error = Error;
fn try_from(addr: &SlatepackAddress) -> Result<Self, Self::Error> {
let cep =
curve25519_dalek::edwards::CompressedEdwardsY::from_slice(addr.pub_key.as_bytes());
let ep = match cep.decompress() {
Some(p) => p,
None => {
return Err(Error::ED25519Key(
"Can't decompress ed25519 Edwards Point".into(),
));
}
};
let res = xDalekPublicKey::from(ep.to_montgomery().to_bytes());
Ok(res)
}
}
impl TryFrom<&SecretKey> for SlatepackAddress {
type Error = Error;
fn try_from(key: &SecretKey) -> Result<Self, Self::Error> {
let d_skey = match edDalekSecretKey::from_bytes(&key.0) {
Ok(k) => k,
Err(e) => {
return Err(Error::ED25519Key(format!(
"Can't create slatepack address from SecretKey: {}",
e
)));
}
};
let d_pub_key: edDalekPublicKey = (&d_skey).into();
Ok(Self::new(&d_pub_key))
}
}
/// Serializes a SlatepackAddress to a bech32 string
impl Serialize for SlatepackAddress {
///
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(
&String::try_from(self).map_err(|err| serde::ser::Error::custom(err.to_string()))?,
)
}
}
/// Deserialize from a bech32 string
impl<'de> Deserialize<'de> for SlatepackAddress {
fn deserialize<D>(deserializer: D) -> Result<SlatepackAddress, D::Error>
where
D: Deserializer<'de>,
{
struct SlatepackAddressVisitor;
impl<'de> serde::de::Visitor<'de> for SlatepackAddressVisitor {
type Value = SlatepackAddress;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(formatter, "a SlatepackAddress")
}
fn visit_str<E>(self, value: &str) -> Result<SlatepackAddress, E>
where
E: serde::de::Error,
{
let s = SlatepackAddress::try_from(value)
.map_err(|err| serde::de::Error::custom(err.to_string()))?;
Ok(s)
}
}
deserializer.deserialize_str(SlatepackAddressVisitor)
}
}
/// write binary trait
impl Writeable for SlatepackAddress {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ser::Error> {
// We're actually going to encode the bech32 address as opposed to
// the binary serialization
let encoded = match String::try_from(self) {
Ok(e) => e,
Err(e) => {
error!("Cannot parse Slatepack address: {:?}, {}", self, e);
return Err(ser::Error::CorruptedData);
}
};
// write length, max 255
let bytes = encoded.as_bytes();
if bytes.len() > 255 {
error!(
"Cannot encode Slatepackaddress: {:?}, Too Long (Max 255)",
self
);
return Err(ser::Error::CorruptedData);
}
writer.write_u8(bytes.len() as u8)?;
writer.write_fixed_bytes(&bytes)
}
}
impl Readable for SlatepackAddress {
fn read<R: Reader>(reader: &mut R) -> Result<SlatepackAddress, ser::Error> {
// read length as u8
let len = reader.read_u8()?;
// and bech32 string
let encoded = match String::from_utf8(reader.read_fixed_bytes(len as usize)?) {
Ok(a) => a,
Err(e) => {
error!("Cannot parse Slatepack address from utf8: {}", e);
return Err(ser::Error::CorruptedData);
}
};
let parsed_addr = match SlatepackAddress::try_from(encoded.as_str()) {
Ok(a) => a,
Err(e) => {
error!("Cannot parse Slatepack address: {}, {}", encoded, e);
return Err(ser::Error::CorruptedData);
}
};
Ok(parsed_addr)
}
}
#[test]
fn slatepack_address() -> Result<(), Error> {
use rand::{thread_rng, Rng};
global::set_local_chain_type(global::ChainTypes::AutomatedTesting);
let sec_key_bytes: [u8; 32] = thread_rng().gen();
let ed_sec_key = edDalekSecretKey::from_bytes(&sec_key_bytes).unwrap();
let ed_pub_key = edDalekPublicKey::from(&ed_sec_key);
let addr = SlatepackAddress::new(&ed_pub_key);
let x_pub_key = xDalekPublicKey::try_from(&addr)?;
let x_dec_secret = x25519_dalek::StaticSecret::from(sec_key_bytes);
let x_pub_key_direct = xDalekPublicKey::from(&x_dec_secret);
println!("ed sec key: {:?}", ed_sec_key);
println!("ed pub key: {:?}", ed_pub_key);
println!("x pub key from addr: {:?}", x_pub_key);
println!("x pub key direct: {:?}", x_pub_key_direct);
let encoded = String::try_from(&addr).unwrap();
println!("Encoded bech32: {}", encoded);
let parsed_addr = SlatepackAddress::try_from(encoded.as_str()).unwrap();
assert_eq!(addr, parsed_addr);
// ensure ed25519 pub keys and x25519 pubkeys are equivalent on decryption
let mut slatepack = super::Slatepack::default();
let mut payload: Vec<u8> = Vec::with_capacity(243);
for _ in 0..payload.capacity() {
payload.push(rand::random());
}
slatepack.payload = payload;
let orig_sp = slatepack.clone();
slatepack.try_encrypt_payload(vec![addr.clone()])?;
slatepack.try_decrypt_payload(Some(&ed_sec_key))?;
assert_eq!(orig_sp.payload, slatepack.payload);
Ok(())
}
-198
View File
@@ -1,198 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// A note on encoding efficiency: 0.75 for Base64, 0.744 for Base62, 0.732 for Base58
// slatepack uses a modified Base58Check encoding to create armored slate payloads:
// 1. Take first four bytes of SHA256(SHA256(slate.as_bytes()))
// 2. Concatenate result of step 1 and slate.as_bytes()
// 3. Base58 encode bytes from step 2
// Finally add armor framing and space/newline formatting as desired
use crate::Error;
use grin_core::global::max_tx_weight;
use grin_wallet_util::byte_ser;
use regex::Regex;
use sha2::{Digest, Sha256};
use std::str;
use super::types::{Slatepack, SlatepackBin};
// Framing and formatting for slate armor
pub static HEADER: &str = "BEGINSLATEPACK.";
static FOOTER: &str = ". ENDSLATEPACK.";
const WORD_LENGTH: usize = 15;
const WORDS_PER_LINE: usize = 200;
const WEIGHT_RATIO: u64 = 32;
/// Maximum size for an armored Slatepack file
pub fn max_size() -> u64 {
max_tx_weight()
.saturating_mul(WEIGHT_RATIO)
.saturating_add(HEADER.len() as u64)
.saturating_add(FOOTER.len() as u64)
}
/// Minimum size for an armored Slatepack file or stream
pub fn min_size() -> u64 {
HEADER.len() as u64
}
lazy_static! {
static ref HEADER_REGEX: Regex =
Regex::new(concat!(r"^[>\n\r\t ]*BEGINSLATEPACK[>\n\r\t ]*$")).unwrap();
static ref FOOTER_REGEX: Regex =
Regex::new(concat!(r"^[>\n\r\t ]*ENDSLATEPACK[>\n\r\t ]*$")).unwrap();
static ref WHITESPACE_LIST: [u8; 5] = [b'>', b'\n', b'\r', b'\t', b' '];
}
/// Wrapper for associated functions
pub struct SlatepackArmor;
impl SlatepackArmor {
/// Decode an armored Slatepack
pub fn decode(armor_bytes: &[u8]) -> Result<Vec<u8>, Error> {
// Collect the bytes up to the first period, this is the header
let header_bytes = armor_bytes
.iter()
.take_while(|byte| **byte != b'.')
.cloned()
.collect::<Vec<u8>>();
// Verify the header...
check_header(&header_bytes)?;
// Get the length of the header
let header_len = header_bytes.len() + 1;
// Skip the length of the header to read for the payload until the next period
let payload_bytes = armor_bytes[header_len as usize..]
.iter()
.take_while(|byte| **byte != b'.')
.cloned()
.collect::<Vec<u8>>();
// Get length of the payload to check the footer framing
let payload_len = payload_bytes.len();
// Get footer bytes and verify them
let consumed_bytes = header_len + payload_len + 1;
let footer_bytes = armor_bytes[consumed_bytes as usize..]
.iter()
.take_while(|byte| **byte != b'.')
.cloned()
.collect::<Vec<u8>>();
check_footer(&footer_bytes)?;
// Clean up the payload bytes to be deserialized
let clean_payload = payload_bytes
.iter()
.filter(|byte| !WHITESPACE_LIST.contains(byte))
.cloned()
.collect::<Vec<u8>>();
// Decode payload from base58
let base_decode = bs58::decode(&clean_payload)
.into_vec()
.map_err(|_| Error::SlatepackDeser("Bad bytes".into()))?;
let error_code = &base_decode[0..4];
let slatepack_bytes = &base_decode[4..];
// Make sure the error check code is valid for the slate data
error_check(error_code, slatepack_bytes)?;
// Return slate as binary or string
Ok(slatepack_bytes.to_vec())
}
/// Encode an armored slatepack
pub fn encode(slatepack: &Slatepack) -> Result<String, Error> {
let slatepack_bytes = byte_ser::to_bytes(&SlatepackBin(slatepack.clone()))
.map_err(|_| Error::SlatepackSer)?;
let encoded_slatepack = base58check(&slatepack_bytes)?;
let formatted_slatepack = format_slatepack(&format!("{}{}", HEADER, encoded_slatepack))?;
Ok(format!("{}{}\n", formatted_slatepack, FOOTER))
}
}
// Takes an error check code and a slate binary and verifies that the code was generated from slate
fn error_check(error_code: &[u8], slate_bytes: &[u8]) -> Result<(), Error> {
let new_check = generate_check(slate_bytes)?;
if error_code.iter().eq(new_check.iter()) {
Ok(())
} else {
Err(Error::InvalidSlatepackData(
"Bad slate error code- some data was corrupted".to_string(),
))
}
}
// Checks header framing bytes and returns an error if they are invalid
fn check_header(header: &[u8]) -> Result<(), Error> {
let framing = str::from_utf8(header).map_err(|_| Error::SlatepackDeser("Bad bytes".into()))?;
if HEADER_REGEX.is_match(framing) {
Ok(())
} else {
Err(Error::InvalidSlatepackData("Bad armor header".to_string()))
}
}
// Checks footer framing bytes and returns an error if they are invalid
fn check_footer(footer: &[u8]) -> Result<(), Error> {
let framing = str::from_utf8(footer).map_err(|_| Error::SlatepackDeser("Bad bytes".into()))?;
if FOOTER_REGEX.is_match(framing) {
Ok(())
} else {
Err(Error::InvalidSlatepackData("Bad armor footer".to_string()))
}
}
// MODIFIED Base58Check encoding for slate bytes
fn base58check(slate: &[u8]) -> Result<String, Error> {
// Serialize the slate json string to a vector of bytes
let mut slate_bytes: Vec<u8> = slate.to_vec();
// Get the four byte checksum for the slate binary
let mut check_bytes: Vec<u8> = generate_check(&slate_bytes)?;
// Make a new buffer and concatenate checksum bytes and slate bytes
let mut slate_buf = Vec::new();
slate_buf.append(&mut check_bytes);
slate_buf.append(&mut slate_bytes);
// Encode the slate buffer containing the slate binary and checksum bytes as Base58
let b58_slate = bs58::encode(slate_buf).into_string();
Ok(b58_slate)
}
// Adds human readable formatting to the slate payload for armoring
fn format_slatepack(slatepack: &str) -> Result<String, Error> {
let formatter = slatepack
.chars()
.enumerate()
.flat_map(|(i, c)| {
if i != 0 && i % WORD_LENGTH == 0 {
if WORDS_PER_LINE != 0 && i % (WORD_LENGTH * WORDS_PER_LINE) == 0 {
Some('\n')
} else {
Some(' ')
}
} else {
None
}
.into_iter()
.chain(std::iter::once(c))
})
.collect::<String>();
Ok(formatter)
}
// Returns the first four bytes of a double sha256 hash of some bytes
fn generate_check(payload: &[u8]) -> Result<Vec<u8>, Error> {
let mut first_hasher = Sha256::new();
first_hasher.update(payload);
let mut second_hasher = Sha256::new();
second_hasher.update(first_hasher.finalize());
let checksum = second_hasher.finalize();
let check_bytes: Vec<u8> = checksum[0..4].to_vec();
Ok(check_bytes)
}
-25
View File
@@ -1,25 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Functions and types for handling Slatepack transactions
mod address;
mod armor;
mod packer;
mod types;
pub use self::address::SlatepackAddress;
pub use self::armor::{max_size, min_size, SlatepackArmor};
pub use self::packer::{Slatepacker, SlatepackerArgs};
pub use self::types::{Slatepack, SlatepackBin};
-121
View File
@@ -1,121 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::convert::TryFrom;
use std::str;
use super::armor::HEADER;
use crate::Error;
use crate::{
slatepack, Slate, SlateVersion, Slatepack, SlatepackAddress, SlatepackArmor, SlatepackBin,
VersionedBinSlate, VersionedSlate,
};
use grin_wallet_util::byte_ser;
use ed25519_dalek::SecretKey as edSecretKey;
#[derive(Clone)]
/// Arguments, mostly for encrypting decrypting a slatepack
pub struct SlatepackerArgs<'a> {
/// Optional sender to include in slatepack
pub sender: Option<SlatepackAddress>,
/// Optional list of recipients, for encryption
pub recipients: Vec<SlatepackAddress>,
/// Optional decryption key
pub dec_key: Option<&'a edSecretKey>,
}
/// Helper struct to pack and unpack slatepacks
#[derive(Clone)]
pub struct Slatepacker<'a>(SlatepackerArgs<'a>);
impl<'a> Slatepacker<'a> {
/// Create with pathbuf and recipients
pub fn new(args: SlatepackerArgs<'a>) -> Self {
Self(args)
}
/// return slatepack
pub fn deser_slatepack(&self, data: &[u8], decrypt: bool) -> Result<Slatepack, Error> {
// check if data is armored, if so, remove and continue
let data_len = data.len() as u64;
if data_len < slatepack::min_size() || data_len > slatepack::max_size() {
let msg = format!("Data invalid length");
return Err(Error::SlatepackDeser(msg));
}
let test_header = &data[..HEADER.len()];
let data = match str::from_utf8(test_header) {
Ok(s) => {
if s == HEADER {
SlatepackArmor::decode(data)?
} else {
data.to_vec()
}
}
Err(_) => data.to_vec(),
};
// try as bin first, then as json
let mut slatepack = match byte_ser::from_bytes::<SlatepackBin>(&data) {
Ok(s) => s.0,
Err(e) => {
debug!("Not a valid binary slatepack: {} - Will try JSON", e);
let content = String::from_utf8(data).map_err(|e| {
let msg = format!("{}", e);
Error::SlatepackDeser(msg)
})?;
serde_json::from_str(&content).map_err(|e| {
let msg = format!("Error reading JSON slatepack: {}", e);
Error::SlatepackDeser(msg)
})?
}
};
slatepack.ver_check_warn();
if decrypt {
slatepack.try_decrypt_payload(self.0.dec_key)?;
}
Ok(slatepack)
}
/// Create slatepack from slate and args
pub fn create_slatepack(&self, slate: &Slate) -> Result<Slatepack, Error> {
let out_slate = VersionedSlate::into_version(slate.clone(), SlateVersion::V4)?;
let bin_slate = VersionedBinSlate::try_from(out_slate).map_err(|_| Error::SlatepackSer)?;
let mut slatepack = Slatepack::default();
slatepack.payload = byte_ser::to_bytes(&bin_slate).map_err(|_| Error::SlatepackSer)?;
slatepack.sender = self.0.sender.clone();
slatepack.try_encrypt_payload(self.0.recipients.clone())?;
Ok(slatepack)
}
/// Armor a slatepack
pub fn armor_slatepack(&self, slatepack: &Slatepack) -> Result<String, Error> {
SlatepackArmor::encode(&slatepack)
}
/// Return/upgrade slate from slatepack
pub fn get_slate(&self, slatepack: &Slatepack) -> Result<Slate, Error> {
let slate_bin =
byte_ser::from_bytes::<VersionedBinSlate>(&slatepack.payload).map_err(|e| {
error!("Error reading slate from armored slatepack: {}", e);
let msg = format!("{}", e);
Error::SlatepackDeser(msg)
})?;
Ok(Slate::upgrade(slate_bin.into())?)
}
}
-850
View File
@@ -1,850 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use bech32::{self, ToBase32};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
/// Slatepack Types + Serialization implementation
use ed25519_dalek::SecretKey as edSecretKey;
use sha2::{Digest, Sha512};
use x25519_dalek::StaticSecret;
use crate::dalek_ser;
use crate::grin_core::ser::{self, Readable, Reader, Writeable, Writer};
use crate::Error;
use grin_wallet_util::byte_ser;
use super::SlatepackAddress;
use std::fmt;
use std::io::{Cursor, Read, Write};
pub const SLATEPACK_MAJOR_VERSION: u8 = 1;
pub const SLATEPACK_MINOR_VERSION: u8 = 0;
/// Basic Slatepack definition
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct Slatepack {
// Required Fields
/// Versioning info
#[serde(with = "slatepack_version")]
pub slatepack: SlatepackVersion,
/// Delivery Mode, 0 = plain_text, 1 = age encrypted
pub mode: u8,
// Optional Fields
/// Optional Sender address
#[serde(default = "default_sender_none")]
#[serde(skip_serializing_if = "Option::is_none")]
pub sender: Option<SlatepackAddress>,
// Encrypted metadata, to be serialized into payload only
// shouldn't be accessed directly
/// Encrypted metadata
#[serde(default = "default_enc_metadata")]
#[serde(skip_serializing_if = "enc_metadata_is_empty")]
encrypted_meta: SlatepackEncMetadata,
// Payload (e.g. slate), including encrypted metadata, if present
/// Binary payload, can be encrypted or plaintext
#[serde(
serialize_with = "dalek_ser::as_base64",
deserialize_with = "dalek_ser::bytes_from_base64"
)]
pub payload: Vec<u8>,
/// Test mode
#[serde(default = "default_future_test_mode")]
#[serde(skip)]
pub future_test_mode: bool,
}
fn default_sender_none() -> Option<SlatepackAddress> {
None
}
fn default_enc_metadata() -> SlatepackEncMetadata {
SlatepackEncMetadata {
sender: None,
recipients: vec![],
}
}
fn default_future_test_mode() -> bool {
false
}
fn enc_metadata_is_empty(data: &SlatepackEncMetadata) -> bool {
data.sender.is_none() && data.recipients.is_empty()
}
impl fmt::Display for Slatepack {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", serde_json::to_string_pretty(&self).unwrap())
}
}
impl Default for Slatepack {
fn default() -> Self {
Self {
slatepack: SlatepackVersion {
major: SLATEPACK_MAJOR_VERSION,
minor: SLATEPACK_MINOR_VERSION,
},
mode: 0,
sender: None,
encrypted_meta: default_enc_metadata(),
payload: vec![],
future_test_mode: false,
}
}
}
impl Slatepack {
/// return length of optional fields
pub fn opt_fields_len(&self) -> Result<usize, ser::Error> {
let mut retval = 0;
if let Some(s) = self.sender.as_ref() {
retval += s.encoded_len().unwrap();
}
Ok(retval)
}
// test function that pads the encrypted meta payload with unknown data
fn pad_test_data(data: &mut Vec<u8>) {
let extra_bytes = 139;
let mut len_bytes = [0u8; 4];
len_bytes.copy_from_slice(&data[0..4]);
let mut meta_len = Cursor::new(len_bytes).read_u32::<BigEndian>().unwrap();
meta_len += extra_bytes;
let mut len_bytes = vec![];
len_bytes.write_u32::<BigEndian>(meta_len).unwrap();
data[..4].clone_from_slice(&len_bytes[..4]);
for _ in 0..extra_bytes {
data.push(rand::random())
}
}
/// age encrypt the payload with the given public key
pub fn try_encrypt_payload(&mut self, recipients: Vec<SlatepackAddress>) -> Result<(), Error> {
if recipients.is_empty() {
return Ok(());
}
// Move our sender to the encrypted metadata field
self.encrypted_meta.sender = self.sender.clone();
self.sender = None;
// Create encrypted metadata, which will be length prefixed
let bin_meta = SlatepackEncMetadataBin(self.encrypted_meta.clone());
let mut to_encrypt = byte_ser::to_bytes(&bin_meta).map_err(|_| Error::SlatepackSer)?;
if self.future_test_mode {
Slatepack::pad_test_data(&mut to_encrypt);
}
to_encrypt.append(&mut self.payload);
let rec_keys: Result<Vec<_>, _> = recipients
.into_iter()
.map(|addr| {
let recp_key: age::x25519::Recipient = addr.to_age_pubkey_str()?.parse()?;
Ok(Box::new(recp_key) as Box<dyn age::Recipient>)
})
.collect();
let keys = match rec_keys {
Ok(k) => k,
Err(e) => return Err(e),
};
let encryptor = age::Encryptor::with_recipients(keys);
let mut encrypted = vec![];
let mut writer = encryptor.wrap_output(&mut encrypted)?;
writer.write_all(&to_encrypt)?;
writer.finish()?;
self.payload = encrypted.to_vec();
self.mode = 1;
Ok(())
}
/// As above, decrypt if needed
pub fn try_decrypt_payload(&mut self, dec_key: Option<&edSecretKey>) -> Result<(), Error> {
if self.mode == 0 {
return Ok(());
}
let dec_key = match dec_key {
Some(k) => k,
None => return Ok(()),
};
let mut b = [0u8; 32];
b.copy_from_slice(&dec_key.as_bytes()[0..32]);
let mut hasher = Sha512::new();
hasher.update(b);
let result = hasher.finalize();
b.copy_from_slice(&result[0..32]);
let x_dec_secret = StaticSecret::from(b);
let x_dec_secret_bech32 =
bech32::encode("age-secret-key-", (&x_dec_secret).to_bytes().to_base32())?;
let key: age::x25519::Identity = x_dec_secret_bech32.parse()?;
let decryptor = match age::Decryptor::new(&self.payload[..])? {
age::Decryptor::Recipients(d) => d,
_ => unreachable!(),
};
let mut decrypted = vec![];
let mut reader = decryptor.decrypt(std::iter::once(&key as &dyn age::Identity))?;
reader.read_to_end(&mut decrypted)?;
// Parse encrypted metadata from payload, first 4 bytes of decrypted payload
// will be encrypted metadata length
let mut len_bytes = [0u8; 4];
len_bytes.copy_from_slice(&decrypted[0..4]);
let meta_len = Cursor::new(len_bytes).read_u32::<BigEndian>()?;
self.payload = decrypted.split_off(meta_len as usize + 4);
let meta = byte_ser::from_bytes::<SlatepackEncMetadataBin>(&decrypted)
.map_err(|_| Error::SlatepackSer)?
.0;
self.sender = meta.sender;
self.encrypted_meta.recipients = meta.recipients;
self.mode = 0;
Ok(())
}
/// add a recipient to encrypted metadata
pub fn add_recipient(&mut self, address: SlatepackAddress) {
self.encrypted_meta.recipients.push(address)
}
/// retrieve recipients
pub fn recipients(&self) -> &[SlatepackAddress] {
&self.encrypted_meta.recipients
}
/// version check warning
// TODO: API?
pub fn ver_check_warn(&self) {
if self.slatepack.major > SLATEPACK_MAJOR_VERSION
|| (self.slatepack.major == SLATEPACK_MAJOR_VERSION
&& self.slatepack.minor > SLATEPACK_MINOR_VERSION)
{
warn!("Incoming Slatepack's version is greater than what this wallet recognizes");
warn!("You may need to upgrade if it contains unsupported features");
warn!(
"Incoming: {}.{}, This wallet: {}.{}",
self.slatepack.major,
self.slatepack.minor,
SLATEPACK_MAJOR_VERSION,
SLATEPACK_MINOR_VERSION
);
}
}
}
/// Wrapper for outputting slate as binary
#[derive(Debug, Clone)]
pub struct SlatepackBin(pub Slatepack);
impl serde::Serialize for SlatepackBin {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut vec = vec![];
ser::serialize(&mut vec, ser::ProtocolVersion(4), self)
.map_err(|err| serde::ser::Error::custom(err.to_string()))?;
serializer.serialize_bytes(&vec)
}
}
impl<'de> serde::Deserialize<'de> for SlatepackBin {
fn deserialize<D>(deserializer: D) -> Result<SlatepackBin, D::Error>
where
D: serde::Deserializer<'de>,
{
struct SlatepackBinVisitor;
impl<'de> serde::de::Visitor<'de> for SlatepackBinVisitor {
type Value = SlatepackBin;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(formatter, "a serialised binary Slatepack")
}
fn visit_bytes<E>(self, value: &[u8]) -> Result<SlatepackBin, E>
where
E: serde::de::Error,
{
let mut reader = std::io::Cursor::new(value.to_vec());
let s = ser::deserialize(
&mut reader,
ser::ProtocolVersion(4),
ser::DeserializationMode::default(),
)
.map_err(|err| serde::de::Error::custom(err.to_string()))?;
Ok(s)
}
}
deserializer.deserialize_bytes(SlatepackBinVisitor)
}
}
impl Writeable for SlatepackBin {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ser::Error> {
let sp = self.0.clone();
// Version (2)
sp.slatepack.write(writer)?;
// Mode (1)
writer.write_u8(sp.mode)?;
// 16 bits of optional content flags (2), most reserved for future use
let mut opt_flags: u16 = 0;
if sp.sender.is_some() {
opt_flags |= 0x01;
}
writer.write_u16(opt_flags)?;
// Bytes to skip from here (Start of optional fields) to get to payload
writer.write_u32(sp.opt_fields_len()? as u32)?;
// write optional fields
if let Some(s) = sp.sender {
s.write(writer)?;
};
// encrypted metadata is only included in the payload
// on encryption, and is not serialised here
// Now write payload (length prefixed)
writer.write_bytes(sp.payload.clone())
}
}
impl Readable for SlatepackBin {
fn read<R: Reader>(reader: &mut R) -> Result<SlatepackBin, ser::Error> {
// Version (2)
let slatepack = SlatepackVersion::read(reader)?;
// Mode (1)
let mode = reader.read_u8()?;
if mode > 1 {
return Err(ser::Error::UnexpectedData {
expected: vec![0, 1],
received: vec![mode],
});
}
// optional content flags (2)
let opt_flags = reader.read_u16()?;
// start of header
let mut bytes_to_payload = reader.read_u32()?;
let sender = if opt_flags & 0x01 > 0 {
let addr = SlatepackAddress::read(reader)?;
let len = match addr.encoded_len() {
Ok(e) => e as u32,
Err(e) => {
error!("Cannot parse Slatepack address: {}", e);
return Err(ser::Error::CorruptedData);
}
};
bytes_to_payload -= len;
Some(addr)
} else {
None
};
// skip over any unknown future fields until header
while bytes_to_payload > 0 {
let _ = reader.read_u8()?;
bytes_to_payload -= 1;
}
let payload = reader.read_bytes_len_prefix()?;
Ok(SlatepackBin(Slatepack {
slatepack,
mode,
sender,
encrypted_meta: default_enc_metadata(),
payload,
future_test_mode: false,
}))
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct SlatepackVersion {
/// Major
pub major: u8,
/// Minor
pub minor: u8,
}
impl Writeable for SlatepackVersion {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ser::Error> {
writer.write_u8(self.major)?;
writer.write_u8(self.minor)
}
}
impl Readable for SlatepackVersion {
fn read<R: Reader>(reader: &mut R) -> Result<SlatepackVersion, ser::Error> {
let major = reader.read_u8()?;
let minor = reader.read_u8()?;
Ok(SlatepackVersion { major, minor })
}
}
/// Serializes version field JSON
pub mod slatepack_version {
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serializer};
use super::SlatepackVersion;
///
pub fn serialize<S>(v: &SlatepackVersion, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&format!("{}.{}", v.major, v.minor))
}
///
pub fn deserialize<'de, D>(deserializer: D) -> Result<SlatepackVersion, D::Error>
where
D: Deserializer<'de>,
{
String::deserialize(deserializer).and_then(|s| {
let mut retval = SlatepackVersion { major: 0, minor: 0 };
let v: Vec<&str> = s.split('.').collect();
if v.len() != 2 {
return Err(Error::custom("Cannot parse version"));
}
match u8::from_str_radix(v[0], 10) {
Ok(u) => retval.major = u,
Err(e) => return Err(Error::custom(format!("Cannot parse version: {}", e))),
}
match u8::from_str_radix(v[1], 10) {
Ok(u) => retval.minor = u,
Err(e) => return Err(Error::custom(format!("Cannot parse version: {}", e))),
}
Ok(retval)
})
}
}
/// Encapsulates encrypted metadata fields
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct SlatepackEncMetadata {
/// Encrypted Sender address, if desired
#[serde(default = "default_sender_none")]
#[serde(skip_serializing_if = "Option::is_none")]
sender: Option<SlatepackAddress>,
/// Recipients list, if desired (mostly for future multiparty needs)
#[serde(default = "default_recipients_empty")]
#[serde(skip_serializing_if = "recipients_empty")]
recipients: Vec<SlatepackAddress>,
}
fn recipients_empty(value: &[SlatepackAddress]) -> bool {
value.is_empty()
}
fn default_recipients_empty() -> Vec<SlatepackAddress> {
vec![]
}
impl SlatepackEncMetadata {
// return length in bytes for encoding (without the 4 byte length header)
pub fn encoded_len(&self) -> Result<usize, Error> {
let mut length = 2; //opt flags
if let Some(s) = &self.sender {
length += s.encoded_len()?;
}
if !self.recipients.is_empty() {
length += 2;
for r in self.recipients.iter() {
length += r.encoded_len()?;
}
}
Ok(length)
}
}
/// Wrapper for outputting encrypted metadata as binary
#[derive(Debug, Clone)]
pub struct SlatepackEncMetadataBin(pub SlatepackEncMetadata);
impl serde::Serialize for SlatepackEncMetadataBin {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut vec = vec![];
ser::serialize(&mut vec, ser::ProtocolVersion(4), self)
.map_err(|err| serde::ser::Error::custom(err.to_string()))?;
serializer.serialize_bytes(&vec)
}
}
impl<'de> serde::Deserialize<'de> for SlatepackEncMetadataBin {
fn deserialize<D>(deserializer: D) -> Result<SlatepackEncMetadataBin, D::Error>
where
D: serde::Deserializer<'de>,
{
struct SlatepackEncMetadataBinVisitor;
impl<'de> serde::de::Visitor<'de> for SlatepackEncMetadataBinVisitor {
type Value = SlatepackEncMetadataBin;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(formatter, "a serialised binary Slatepack Metadata")
}
fn visit_bytes<E>(self, value: &[u8]) -> Result<SlatepackEncMetadataBin, E>
where
E: serde::de::Error,
{
let mut reader = std::io::Cursor::new(value.to_vec());
let s = ser::deserialize(
&mut reader,
ser::ProtocolVersion(4),
ser::DeserializationMode::default(),
)
.map_err(|err| serde::de::Error::custom(err.to_string()))?;
Ok(s)
}
}
deserializer.deserialize_bytes(SlatepackEncMetadataBinVisitor)
}
}
impl Writeable for SlatepackEncMetadataBin {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ser::Error> {
let inner = &self.0;
// write entire metadata length
writer.write_u32(inner.encoded_len().map_err(|e| {
error!("Cannot write encrypted metadata length: {}", e);
ser::Error::CorruptedData
})? as u32)?;
// 16 bits of optional content flags (2), most reserved for future use
let mut opt_flags: u16 = 0;
if inner.sender.is_some() {
opt_flags |= 0x01;
}
if !inner.recipients.is_empty() {
opt_flags |= 0x02;
}
writer.write_u16(opt_flags)?;
if let Some(s) = &inner.sender {
s.write(writer)?;
};
// Recipients List
if !inner.recipients.is_empty() {
let len = inner.recipients.len();
// write number of recipients
if len as u16 > std::u16::MAX {
error!("Too many recipients: {}", len);
return Err(ser::Error::CorruptedData);
}
writer.write_u16(len as u16)?;
for r in inner.recipients.iter() {
r.write(writer)?;
}
}
Ok(())
}
}
impl Readable for SlatepackEncMetadataBin {
fn read<R: Reader>(reader: &mut R) -> Result<SlatepackEncMetadataBin, ser::Error> {
// length header, always present
let mut bytes_remaining = reader.read_u32()?;
// optional content flags (2)
let opt_flags = reader.read_u16()?;
bytes_remaining -= 2;
let sender = if opt_flags & 0x01 > 0 {
let addr = SlatepackAddress::read(reader)?;
let len = match addr.encoded_len() {
Ok(e) => e as u32,
Err(e) => {
error!("Cannot parse Slatepack address: {}", e);
return Err(ser::Error::CorruptedData);
}
};
bytes_remaining -= len;
Some(addr)
} else {
None
};
let mut recipients = vec![];
if opt_flags & 0x02 > 0 {
// number of recipients
let count = reader.read_u16()?;
bytes_remaining -= 2;
for _ in 0..count {
let addr = SlatepackAddress::read(reader)?;
let len = match addr.encoded_len() {
Ok(e) => e as u32,
Err(e) => {
error!("Cannot parse Slatepack address: {}", e);
return Err(ser::Error::CorruptedData);
}
};
bytes_remaining -= len;
recipients.push(addr);
}
}
// bleed off any unknown data beyond this
while bytes_remaining > 0 {
let _ = reader.read_u8()?;
bytes_remaining -= 1;
}
Ok(SlatepackEncMetadataBin(SlatepackEncMetadata {
sender,
recipients,
}))
}
}
#[test]
fn slatepack_bin_basic_ser() -> Result<(), grin_wallet_util::byte_ser::Error> {
use grin_wallet_util::byte_ser;
let mut payload: Vec<u8> = Vec::with_capacity(243);
for _ in 0..payload.capacity() {
payload.push(rand::random());
}
let sp = Slatepack {
payload,
..Slatepack::default()
};
let ser = byte_ser::to_bytes(&SlatepackBin(sp.clone()))?;
let deser = byte_ser::from_bytes::<SlatepackBin>(&ser)?.0;
assert_eq!(sp.slatepack, deser.slatepack);
assert_eq!(sp.mode, deser.mode);
assert!(sp.sender.is_none());
Ok(())
}
#[test]
fn slatepack_bin_opt_fields_ser() -> Result<(), grin_wallet_util::byte_ser::Error> {
use crate::grin_core::global;
use grin_wallet_util::byte_ser;
global::set_local_chain_type(global::ChainTypes::AutomatedTesting);
let mut payload: Vec<u8> = Vec::with_capacity(243);
for _ in 0..payload.capacity() {
payload.push(rand::random());
}
// includes optional fields
let sender = Some(SlatepackAddress::random());
let sp = Slatepack {
sender,
payload,
..Slatepack::default()
};
let ser = byte_ser::to_bytes(&SlatepackBin(sp.clone()))?;
let deser = byte_ser::from_bytes::<SlatepackBin>(&ser)?.0;
assert_eq!(sp, deser);
Ok(())
}
// ensure that a slatepack with unknown data in the optional fields can be read
#[test]
fn slatepack_bin_future() -> Result<(), grin_wallet_util::byte_ser::Error> {
use crate::grin_core::global;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use grin_wallet_util::byte_ser;
use rand::{thread_rng, Rng};
use std::io::Cursor;
global::set_local_chain_type(global::ChainTypes::AutomatedTesting);
let payload_size = 1234;
let mut payload: Vec<u8> = Vec::with_capacity(payload_size);
for _ in 0..payload.capacity() {
payload.push(rand::random());
}
let sender = Some(SlatepackAddress::random());
println!(
"sender len: {}",
sender.as_ref().unwrap().encoded_len().unwrap()
);
let sp = Slatepack {
sender,
payload: payload.clone(),
..Slatepack::default()
};
let ser = byte_ser::to_bytes(&SlatepackBin(sp.clone()))?;
// Add an amount of meaningless (to us) data
let num_extra_bytes = 248;
let mut new_bytes = vec![];
// Version 2
// mode 1
// opt flags 2
// opt fields len (bytes to payload) 4
// bytes 5-8 are opt fields len
// sender 64
let mut opt_fields_len_bytes = [0u8; 4];
opt_fields_len_bytes.copy_from_slice(&ser[5..9]);
let mut rdr = Cursor::new(opt_fields_len_bytes.to_vec());
let opt_fields_len = rdr.read_u32::<BigEndian>().unwrap();
// check this matches what we expect below
assert_eq!(opt_fields_len, 65);
let end_head_pos = opt_fields_len as usize + 8 + 1;
for i in 0..end_head_pos {
new_bytes.push(ser[i]);
}
for _ in 0..num_extra_bytes {
new_bytes.push(thread_rng().gen());
}
for i in 0..8 {
//push payload length prefix
new_bytes.push(ser[end_head_pos + i]);
}
for i in 0..payload_size {
new_bytes.push(ser[end_head_pos + 8 + i]);
}
assert_eq!(new_bytes.len(), ser.len() + num_extra_bytes as usize);
// and set new opt fields length
let mut wtr = vec![];
wtr.write_u32::<BigEndian>(opt_fields_len + num_extra_bytes as u32)
.unwrap();
for i in 0..wtr.len() {
new_bytes[5 + i] = wtr[i];
}
let deser = byte_ser::from_bytes::<SlatepackBin>(&new_bytes)?.0;
assert_eq!(sp, deser);
Ok(())
}
// test encryption and encrypted metadata, which only gets written
// if mode == 1
#[test]
fn slatepack_encrypted_meta() -> Result<(), Error> {
use crate::grin_core::global;
use crate::{Slate, SlateVersion, VersionedBinSlate, VersionedSlate};
use ed25519_dalek::PublicKey as edDalekPublicKey;
use ed25519_dalek::SecretKey as edDalekSecretKey;
use rand::{thread_rng, Rng};
use std::convert::TryFrom;
global::set_local_chain_type(global::ChainTypes::AutomatedTesting);
let sec_key_bytes: [u8; 32] = thread_rng().gen();
let ed_sec_key = edDalekSecretKey::from_bytes(&sec_key_bytes).unwrap();
let ed_pub_key = edDalekPublicKey::from(&ed_sec_key);
let addr = SlatepackAddress::new(&ed_pub_key);
let encoded = String::try_from(&addr).unwrap();
let parsed_addr = SlatepackAddress::try_from(encoded.as_str()).unwrap();
assert_eq!(addr, parsed_addr);
let mut slatepack = super::Slatepack::default();
slatepack.sender = Some(SlatepackAddress::random());
slatepack.add_recipient(SlatepackAddress::random());
slatepack.add_recipient(SlatepackAddress::random());
let v_slate = VersionedSlate::into_version(Slate::blank(2, false), SlateVersion::V4)?;
let bin_slate = VersionedBinSlate::try_from(v_slate).map_err(|_| Error::SlatepackSer)?;
slatepack.payload = byte_ser::to_bytes(&bin_slate).map_err(|_| Error::SlatepackSer)?;
let orig_sp = slatepack.clone();
slatepack.try_encrypt_payload(vec![addr.clone()])?;
// sender should have been moved to encrypted meta
assert!(slatepack.sender.is_none());
let ser = byte_ser::to_bytes(&SlatepackBin(slatepack)).unwrap();
let mut slatepack = byte_ser::from_bytes::<SlatepackBin>(&ser).unwrap().0;
slatepack.try_decrypt_payload(Some(&ed_sec_key))?;
assert!(slatepack.sender.is_some());
assert_eq!(orig_sp, slatepack);
Ok(())
}
// Ensure adding unknown (future) bytes to the encrypted
// metadata won't break parsing
#[test]
fn slatepack_encrypted_meta_future() -> Result<(), Error> {
use crate::grin_core::global;
use crate::{Slate, SlateVersion, VersionedBinSlate, VersionedSlate};
use ed25519_dalek::PublicKey as edDalekPublicKey;
use ed25519_dalek::SecretKey as edDalekSecretKey;
use rand::{thread_rng, Rng};
use std::convert::TryFrom;
global::set_local_chain_type(global::ChainTypes::AutomatedTesting);
let sec_key_bytes: [u8; 32] = thread_rng().gen();
let ed_sec_key = edDalekSecretKey::from_bytes(&sec_key_bytes).unwrap();
let ed_pub_key = edDalekPublicKey::from(&ed_sec_key);
let addr = SlatepackAddress::new(&ed_pub_key);
let encoded = String::try_from(&addr).unwrap();
let parsed_addr = SlatepackAddress::try_from(encoded.as_str()).unwrap();
assert_eq!(addr, parsed_addr);
let mut slatepack = Slatepack::default();
slatepack.sender = Some(SlatepackAddress::random());
slatepack.add_recipient(SlatepackAddress::random());
slatepack.add_recipient(SlatepackAddress::random());
let v_slate = VersionedSlate::into_version(Slate::blank(2, false), SlateVersion::V4)?;
let bin_slate = VersionedBinSlate::try_from(v_slate).map_err(|_| Error::SlatepackSer)?;
slatepack.payload = byte_ser::to_bytes(&bin_slate).map_err(|_| Error::SlatepackSer)?;
let orig_sp = slatepack.clone();
slatepack.future_test_mode = true;
slatepack.try_encrypt_payload(vec![addr.clone()])?;
// sender should have been moved to encrypted meta
assert!(slatepack.sender.is_none());
let ser = byte_ser::to_bytes(&SlatepackBin(slatepack)).unwrap();
let mut slatepack = byte_ser::from_bytes::<SlatepackBin>(&ser).unwrap().0;
slatepack.try_decrypt_payload(Some(&ed_sec_key))?;
assert!(slatepack.sender.is_some());
assert_eq!(orig_sp, slatepack);
Ok(())
}
File diff suppressed because it is too large Load Diff
-527
View File
@@ -1,527 +0,0 @@
// Copyright 2021 The Grin Developers
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! core::libtx specific tests
use grin_core::core::transaction;
use grin_core::core::FeeFields;
use grin_core::libtx::{aggsig, proof};
use grin_keychain::{
BlindSum, BlindingFactor, ExtKeychain, ExtKeychainPath, Keychain, SwitchCommitmentType,
};
use grin_util::secp;
use grin_util::secp::key::{PublicKey, SecretKey};
use grin_wallet_libwallet::Context;
use rand::thread_rng;
fn kernel_sig_msg() -> secp::Message {
transaction::KernelFeatures::Plain {
fee: FeeFields::zero(),
}
.kernel_sig_msg()
.unwrap()
}
#[test]
fn aggsig_sender_receiver_interaction() {
let parent = ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier();
let switch = SwitchCommitmentType::Regular;
let sender_keychain = ExtKeychain::from_random_seed(true).unwrap();
let receiver_keychain = ExtKeychain::from_random_seed(true).unwrap();
// Calculate the kernel excess here for convenience.
// Normally this would happen during transaction building.
let kernel_excess = {
let id1 = ExtKeychain::derive_key_id(1, 1, 0, 0, 0);
let skey1 = sender_keychain.derive_key(0, &id1, switch).unwrap();
let skey2 = receiver_keychain.derive_key(0, &id1, switch).unwrap();
let keychain = ExtKeychain::from_random_seed(true).unwrap();
let blinding_factor = keychain
.blind_sum(
&BlindSum::new()
.sub_blinding_factor(BlindingFactor::from_secret_key(skey1))
.add_blinding_factor(BlindingFactor::from_secret_key(skey2)),
)
.unwrap();
keychain
.secp()
.commit(0, blinding_factor.secret_key(&keychain.secp()).unwrap())
.unwrap()
};
let s_cx;
let mut rx_cx;
// sender starts the tx interaction
let (sender_pub_excess, _sender_pub_nonce) = {
let keychain = sender_keychain.clone();
let id1 = ExtKeychain::derive_key_id(1, 1, 0, 0, 0);
let skey = keychain.derive_key(0, &id1, switch).unwrap();
// dealing with an input here so we need to negate the blinding_factor
// rather than use it as is
let bs = BlindSum::new();
let blinding_factor = keychain
.blind_sum(&bs.sub_blinding_factor(BlindingFactor::from_secret_key(skey)))
.unwrap();
let blind = blinding_factor.secret_key(&keychain.secp()).unwrap();
s_cx = Context::with_excess(&keychain.secp(), blind, &parent, false);
s_cx.get_public_keys(&keychain.secp())
};
let pub_nonce_sum;
let pub_key_sum;
// receiver receives partial tx
let (receiver_pub_excess, _receiver_pub_nonce, rx_sig_part) = {
let keychain = receiver_keychain.clone();
let key_id = ExtKeychain::derive_key_id(1, 1, 0, 0, 0);
// let blind = blind_sum.secret_key(&keychain.secp())?;
let blind = keychain.derive_key(0, &key_id, switch).unwrap();
rx_cx = Context::with_excess(&keychain.secp(), blind, &parent, false);
let (pub_excess, pub_nonce) = rx_cx.get_public_keys(&keychain.secp());
rx_cx.add_output(&key_id, &None, 0);
pub_nonce_sum = PublicKey::from_combination(
keychain.secp(),
vec![
&s_cx.get_public_keys(keychain.secp()).1,
&rx_cx.get_public_keys(keychain.secp()).1,
],
)
.unwrap();
pub_key_sum = PublicKey::from_combination(
keychain.secp(),
vec![
&s_cx.get_public_keys(keychain.secp()).0,
&rx_cx.get_public_keys(keychain.secp()).0,
],
)
.unwrap();
let msg = kernel_sig_msg();
let sig_part = aggsig::calculate_partial_sig(
&keychain.secp(),
&rx_cx.sec_key,
&rx_cx.sec_nonce,
&pub_nonce_sum,
Some(&pub_key_sum),
&msg,
)
.unwrap();
(pub_excess, pub_nonce, sig_part)
};
// check the sender can verify the partial signature
// received in the response back from the receiver
{
let keychain = sender_keychain.clone();
let msg = kernel_sig_msg();
let sig_verifies = aggsig::verify_partial_sig(
&keychain.secp(),
&rx_sig_part,
&pub_nonce_sum,
&receiver_pub_excess,
Some(&pub_key_sum),
&msg,
);
assert!(!sig_verifies.is_err());
}
// now sender signs with their key
let sender_sig_part = {
let keychain = sender_keychain.clone();
let msg = kernel_sig_msg();
let sig_part = aggsig::calculate_partial_sig(
&keychain.secp(),
&s_cx.sec_key,
&s_cx.sec_nonce,
&pub_nonce_sum,
Some(&pub_key_sum),
&msg,
)
.unwrap();
sig_part
};
// check the receiver can verify the partial signature
// received by the sender
{
let keychain = receiver_keychain.clone();
let msg = kernel_sig_msg();
let sig_verifies = aggsig::verify_partial_sig(
&keychain.secp(),
&sender_sig_part,
&pub_nonce_sum,
&sender_pub_excess,
Some(&pub_key_sum),
&msg,
);
assert!(!sig_verifies.is_err());
}
// Receiver now builds final signature from sender and receiver parts
let (final_sig, final_pubkey) = {
let keychain = receiver_keychain.clone();
let msg = kernel_sig_msg();
let our_sig_part = aggsig::calculate_partial_sig(
&keychain.secp(),
&rx_cx.sec_key,
&rx_cx.sec_nonce,
&pub_nonce_sum,
Some(&pub_key_sum),
&msg,
)
.unwrap();
// Receiver now generates final signature from the two parts
let final_sig = aggsig::add_signatures(
&keychain.secp(),
vec![&sender_sig_part, &our_sig_part],
&pub_nonce_sum,
)
.unwrap();
// Receiver calculates the final public key (to verify sig later)
let final_pubkey = PublicKey::from_combination(
keychain.secp(),
vec![
&s_cx.get_public_keys(keychain.secp()).0,
&rx_cx.get_public_keys(keychain.secp()).0,
],
)
.unwrap();
(final_sig, final_pubkey)
};
// Receiver checks the final signature verifies
{
let keychain = receiver_keychain.clone();
let msg = kernel_sig_msg();
// Receiver check the final signature verifies
let sig_verifies = aggsig::verify_completed_sig(
&keychain.secp(),
&final_sig,
&final_pubkey,
Some(&final_pubkey),
&msg,
);
assert!(!sig_verifies.is_err());
}
// Check we can verify the sig using the kernel excess
{
let keychain = ExtKeychain::from_random_seed(true).unwrap();
let msg = kernel_sig_msg();
let sig_verifies =
aggsig::verify_single_from_commit(&keychain.secp(), &final_sig, &msg, &kernel_excess);
assert!(!sig_verifies.is_err());
}
}
#[test]
fn aggsig_sender_receiver_interaction_offset() {
let parent = ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier();
let switch = SwitchCommitmentType::Regular;
let sender_keychain = ExtKeychain::from_random_seed(true).unwrap();
let receiver_keychain = ExtKeychain::from_random_seed(true).unwrap();
// This is the kernel offset that we use to split the key
// Summing these at the block level prevents the
// kernels from being used to reconstruct (or identify) individual transactions
let kernel_offset = SecretKey::new(&sender_keychain.secp(), &mut thread_rng());
// Calculate the kernel excess here for convenience.
// Normally this would happen during transaction building.
let kernel_excess = {
let id1 = ExtKeychain::derive_key_id(1, 1, 0, 0, 0);
let skey1 = sender_keychain.derive_key(0, &id1, switch).unwrap();
let skey2 = receiver_keychain.derive_key(0, &id1, switch).unwrap();
let keychain = ExtKeychain::from_random_seed(true).unwrap();
let blinding_factor = keychain
.blind_sum(
&BlindSum::new()
.sub_blinding_factor(BlindingFactor::from_secret_key(skey1))
.add_blinding_factor(BlindingFactor::from_secret_key(skey2))
// subtract the kernel offset here like as would when
// verifying a kernel signature
.sub_blinding_factor(BlindingFactor::from_secret_key(kernel_offset.clone())),
)
.unwrap();
keychain
.secp()
.commit(0, blinding_factor.secret_key(&keychain.secp()).unwrap())
.unwrap()
};
let s_cx;
let mut rx_cx;
// sender starts the tx interaction
let (sender_pub_excess, _sender_pub_nonce) = {
let keychain = sender_keychain.clone();
let id1 = ExtKeychain::derive_key_id(1, 1, 0, 0, 0);
let skey = keychain.derive_key(0, &id1, switch).unwrap();
// dealing with an input here so we need to negate the blinding_factor
// rather than use it as is
let blinding_factor = keychain
.blind_sum(
&BlindSum::new()
.sub_blinding_factor(BlindingFactor::from_secret_key(skey))
// subtract the kernel offset to create an aggsig context
// with our "split" key
.sub_blinding_factor(BlindingFactor::from_secret_key(kernel_offset)),
)
.unwrap();
let blind = blinding_factor.secret_key(&keychain.secp()).unwrap();
s_cx = Context::with_excess(&keychain.secp(), blind, &parent, false);
s_cx.get_public_keys(&keychain.secp())
};
// receiver receives partial tx
let pub_nonce_sum;
let pub_key_sum;
let (receiver_pub_excess, _receiver_pub_nonce, sig_part) = {
let keychain = receiver_keychain.clone();
let key_id = ExtKeychain::derive_key_id(1, 1, 0, 0, 0);
let blind = keychain.derive_key(0, &key_id, switch).unwrap();
rx_cx = Context::with_excess(&keychain.secp(), blind, &parent, false);
let (pub_excess, pub_nonce) = rx_cx.get_public_keys(&keychain.secp());
rx_cx.add_output(&key_id, &None, 0);
pub_nonce_sum = PublicKey::from_combination(
keychain.secp(),
vec![
&s_cx.get_public_keys(keychain.secp()).1,
&rx_cx.get_public_keys(keychain.secp()).1,
],
)
.unwrap();
pub_key_sum = PublicKey::from_combination(
keychain.secp(),
vec![
&s_cx.get_public_keys(keychain.secp()).0,
&rx_cx.get_public_keys(keychain.secp()).0,
],
)
.unwrap();
let msg = kernel_sig_msg();
let sig_part = aggsig::calculate_partial_sig(
&keychain.secp(),
&rx_cx.sec_key,
&rx_cx.sec_nonce,
&pub_nonce_sum,
Some(&pub_key_sum),
&msg,
)
.unwrap();
(pub_excess, pub_nonce, sig_part)
};
// check the sender can verify the partial signature
// received in the response back from the receiver
{
let keychain = sender_keychain.clone();
let msg = kernel_sig_msg();
let sig_verifies = aggsig::verify_partial_sig(
&keychain.secp(),
&sig_part,
&pub_nonce_sum,
&receiver_pub_excess,
Some(&pub_key_sum),
&msg,
);
assert!(!sig_verifies.is_err());
}
// now sender signs with their key
let sender_sig_part = {
let keychain = sender_keychain.clone();
let msg = kernel_sig_msg();
let sig_part = aggsig::calculate_partial_sig(
&keychain.secp(),
&s_cx.sec_key,
&s_cx.sec_nonce,
&pub_nonce_sum,
Some(&pub_key_sum),
&msg,
)
.unwrap();
sig_part
};
// check the receiver can verify the partial signature
// received by the sender
{
let keychain = receiver_keychain.clone();
let msg = kernel_sig_msg();
let sig_verifies = aggsig::verify_partial_sig(
&keychain.secp(),
&sender_sig_part,
&pub_nonce_sum,
&sender_pub_excess,
Some(&pub_key_sum),
&msg,
);
assert!(!sig_verifies.is_err());
}
// Receiver now builds final signature from sender and receiver parts
let (final_sig, final_pubkey) = {
let keychain = receiver_keychain.clone();
let msg = kernel_sig_msg();
let our_sig_part = aggsig::calculate_partial_sig(
&keychain.secp(),
&rx_cx.sec_key,
&rx_cx.sec_nonce,
&pub_nonce_sum,
Some(&pub_key_sum),
&msg,
)
.unwrap();
// Receiver now generates final signature from the two parts
let final_sig = aggsig::add_signatures(
&keychain.secp(),
vec![&sender_sig_part, &our_sig_part],
&pub_nonce_sum,
)
.unwrap();
// Receiver calculates the final public key (to verify sig later)
let final_pubkey = PublicKey::from_combination(
keychain.secp(),
vec![
&s_cx.get_public_keys(keychain.secp()).0,
&rx_cx.get_public_keys(keychain.secp()).0,
],
)
.unwrap();
(final_sig, final_pubkey)
};
// Receiver checks the final signature verifies
{
let keychain = receiver_keychain.clone();
let msg = kernel_sig_msg();
// Receiver check the final signature verifies
let sig_verifies = aggsig::verify_completed_sig(
&keychain.secp(),
&final_sig,
&final_pubkey,
Some(&final_pubkey),
&msg,
);
assert!(!sig_verifies.is_err());
}
// Check we can verify the sig using the kernel excess
{
let keychain = ExtKeychain::from_random_seed(true).unwrap();
let msg = kernel_sig_msg();
let sig_verifies =
aggsig::verify_single_from_commit(&keychain.secp(), &final_sig, &msg, &kernel_excess);
assert!(!sig_verifies.is_err());
}
}
#[test]
fn test_rewind_range_proof() {
let keychain = ExtKeychain::from_random_seed(true).unwrap();
let builder = proof::ProofBuilder::new(&keychain);
let key_id = ExtKeychain::derive_key_id(1, 1, 0, 0, 0);
let key_id2 = ExtKeychain::derive_key_id(1, 2, 0, 0, 0);
let switch = SwitchCommitmentType::Regular;
let commit = keychain.commit(5, &key_id, switch).unwrap();
let extra_data = [99u8; 64];
let proof = proof::create(
&keychain,
&builder,
5,
&key_id,
switch,
commit,
Some(extra_data.to_vec().clone()),
)
.unwrap();
let proof_info = proof::rewind(
keychain.secp(),
&builder,
commit,
Some(extra_data.to_vec().clone()),
proof,
)
.unwrap();
assert!(proof_info.is_some());
let (r_amount, r_key_id, r_switch) = proof_info.unwrap();
assert_eq!(r_amount, 5);
assert_eq!(r_key_id, key_id);
assert_eq!(r_switch, switch);
// cannot rewind with a different commit
let commit2 = keychain.commit(5, &key_id2, switch).unwrap();
let proof_info = proof::rewind(
keychain.secp(),
&builder,
commit2,
Some(extra_data.to_vec().clone()),
proof,
)
.unwrap();
assert!(proof_info.is_none());
// cannot rewind with a commitment to a different value
let commit3 = keychain.commit(4, &key_id, switch).unwrap();
let proof_info = proof::rewind(
keychain.secp(),
&builder,
commit3,
Some(extra_data.to_vec().clone()),
proof,
)
.unwrap();
assert!(proof_info.is_none());
// cannot rewind with wrong extra committed data
let wrong_extra_data = [98u8; 64];
let proof_info = proof::rewind(
keychain.secp(),
&builder,
commit,
Some(wrong_extra_data.to_vec().clone()),
proof,
)
.unwrap();
assert!(proof_info.is_none());
}
-96
View File
@@ -1,96 +0,0 @@
// Copyright 2021 The Grin Developers
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! core::libtx specific tests
//use grin_wallet_libwallet::Slate;
// test all slate conversions
/* TODO: Turn back on upon release of new slate version
#[test]
fn slate_conversions() {
// Test V0 to V2
let v0 = include_str!("slates/v0.slate");
let res = Slate::deserialize_upgrade(&v0);
assert!(res.is_ok());
// should serialize as latest
let mut res = res.unwrap();
assert_eq!(res.version_info.orig_version, 0);
res.version_info.orig_version = 2;
let s = serde_json::to_string(&res);
assert!(s.is_ok());
let s = s.unwrap();
let v = Slate::parse_slate_version(&s);
assert!(v.is_ok());
assert_eq!(v.unwrap(), 2);
println!("v0 -> v2: {}", s);
// Test V1 to V2
let v1 = include_str!("slates/v1.slate");
let res = Slate::deserialize_upgrade(&v1);
assert!(res.is_ok());
// should serialize as latest
let mut res = res.unwrap();
assert_eq!(res.version_info.orig_version, 1);
res.version_info.orig_version = 2;
let s = serde_json::to_string(&res);
assert!(s.is_ok());
let s = s.unwrap();
let v = Slate::parse_slate_version(&s);
assert!(v.is_ok());
assert_eq!(v.unwrap(), 2);
println!("v1 -> v2: {}", s);
// V2 -> V2, check version
let v2 = include_str!("slates/v2.slate");
let res = Slate::deserialize_upgrade(&v2);
assert!(res.is_ok());
let res = res.unwrap();
assert_eq!(res.version_info.orig_version, 2);
let s = serde_json::to_string(&res);
assert!(s.is_ok());
let s = s.unwrap();
let v = Slate::parse_slate_version(&s);
assert!(v.is_ok());
assert_eq!(v.unwrap(), 2);
// Downgrade to V1
let v2 = include_str!("slates/v2.slate");
let res = Slate::deserialize_upgrade(&v2);
assert!(res.is_ok());
let mut res = res.unwrap();
// downgrade
res.version_info.orig_version = 1;
let s = serde_json::to_string(&res);
assert!(s.is_ok());
let s = s.unwrap();
let v = Slate::parse_slate_version(&s);
assert!(v.is_ok());
assert_eq!(v.unwrap(), 1);
println!("v2 -> v1: {}", s);
// Downgrade to V0
let v2 = include_str!("slates/v2.slate");
let res = Slate::deserialize_upgrade(&v2);
assert!(res.is_ok());
let mut res = res.unwrap();
// downgrade
res.version_info.orig_version = 0;
let s = serde_json::to_string(&res);
assert!(s.is_ok());
let s = s.unwrap();
let v = Slate::parse_slate_version(&s);
assert!(v.is_ok());
assert_eq!(v.unwrap(), 0);
println!("v2 -> v0: {}", s);
}
*/
-54
View File
@@ -1,54 +0,0 @@
{
"version_info": {
"version": 2,
"orig_version": 2,
"block_header_version": 1
},
"num_participants": 2,
"id": "e0c69803-db50-40d9-a968-496e86660cd4",
"tx": {
"offset": "a853afebf15d8c111f654059940945b4782c38660397257707b53ebfdb403a52",
"body": {
"inputs": [
{
"features": "Plain",
"commit": "09d304aed6300f8124eb8b2d46cc1e0a7b7a9b9042b9cb35e020dd9552df9c697c"
},
{
"features": "Plain",
"commit": "09d3cc915dc317485dc8bbf5ec4669a40bb9d3300c96df3384d116ddad498d0db1"
}
],
"outputs": [
{
"features": "Plain",
"commit": "08d3453eb5ce35a1b6bbc2a7a9afe32483774c011f9975f42393468fa5cd4349a7",
"proof": "db206834c022eec1f346a67b571941f1b6867ae4bd8189ca064b690b32367e454a4a5add51761c472b0e0994ce7f00578bc06ae7b9afdf8ce2118546771976d900464214d3b831fe74a94876980a928315afb5c2af018f5d595e56fd740658b0c4f2d4f463e401cbec2704b31005cd8d7d87458290a3668cc2e82c2b0867d991072544f9e8c805056c97ff66cc052cf2a9666768d0d68acdc6ea1fc80fb9b5e6e19366c7b49ada38b368c0c3e3f73977df003f0c6744737b31b058c7d4e2766e97ee04147ef04be22906f087842205813c7d817598c689c840087d35cc9ce9a98f52e68c66bdde0521acf814737efd072654728f418e6494a7eb7fa6305ec7d572abb91d3bfabf7215e77e0c9cf33769572ff9a8671a24e0a04302e6ac5cee9928ec11d7c9861ed18718142a1563967955e428e4134c6dde88bdbea11248ae99d784a56592a065122948b2c2fb8be25c119345b9fa7db2efbdfcf846e9ba47efff3d0024bdb998e93bcabe1a00222ba36b88ec4f7c2a2151bf00b225f6a14b4de66658daecaa219813f51a9239eec961c6713106b64c4f1ff851e54795220ee3cdc59531f0acc050e17c848b21b916b571b2f6b093fccec046587d0a1718c82bd7a78e22223fe1484dec841820139950dce84c97659b0eac1bfa5fce85d5602f480d714dcab1459c4f29e2746bccb4494d800935ddc630f53257649f1544702003a583d55422e957192faebffcb8d883ec6bb2132c86249d6b50edae84f3c06842b2714267249c8df58e2edc3aca69dff66ee32fb5d93db9156df373ab51df2c094742517b46ff95298caec3464151ea91c8a8fe74bb60ffb94c7c974aa6cb2e47dd1ee05f471e2d2f0b555efe17302769139760bc110c979453f7bfab43b3f3cba4d94c8a5eeb58264bb5c16de6acbbc9c56cb069e7e1ac1f7838d0a6424017b8d563"
}
],
"kernels": [
{
"features": "HeightLocked",
"fee": "7000000",
"lock_height": "70194",
"excess": "000000000000000000000000000000000000000000000000000000000000000000",
"excess_sig": "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
}
]
}
},
"amount": "84825921007",
"fee": "7000000",
"height": "70194",
"lock_height": "70194",
"participant_data": [
{
"id": "0",
"public_blind_excess": "0391f8fc74bb5ff4de373352e7dee00860d4fb78ed7a99765585af980d8a31c615",
"public_nonce": "0206562c21a7f3a003622722ee93c4ecbbecead4a6ad8ee5d930b51ca4a6ca6d01",
"part_sig": null,
"message": null,
"message_sig": null
}
]
}