Compact slate merge (#404)

* Add support for sending compact slates (#366)

* WIP add support for sending compact slates

* add repopulate_tx function to internal API

* first pass at compacted slate working

* move slate compaction to separate function

* test fixes

* support compact slate inits in invoice workflow

* add compress flags to send and invoice

* attempting to remove is_compact and assume all V4 slates begin as compact

* attempting to calculate offsets when full tx data isn't available

* update calc_commit to use participant blind data

* update doctests for compact slates

* start to remove unneeded fields from serialization

* make num_participants optional

* remove other_version from slate

* use grin master branch

* remove message field

* lock height assumed to be 0 if it doesn't exist

* don't serialise receiver signature when null

* don't serialize payment_info if not needed

* remove participant id from participant info

* add note on id field

* fix finalize and receive doctests

* finalize_tx tests, init_send_tx tests

* doctests for process_invoice_tx, retrieve_tx, tx_lock_outputs

* finished test changes

* update from grin master

* rebuild PR from diff (#380)

* recreate PR from diff (#381)

* serialize tx struct into top level coms object (#382)

* remove height (#383)

* Add State Slate (#384)

* add state field to slate and SlateV4

* set slate state at each transaction stage, add check to tests

* serialize slate status properly

* V4 Slate field tweaks (#386)

* various tweaks to V4 slate

* field renaming

* serialize slate v4 ID as base64 (#387)

* remove amount and fee where not needed (#388)

* Final Changes for compact Slate (#389)

* add tests for all types of file output, remove message args

* default range proof serialization

* shorten output features serialization

* rename payment proof fields in slate v4

* v4 payment proof serialization

* Binary Slates (#385)

* start test implementation

* add experimental binary serialization to slate

* serialize id

* serialize fields that can be skipped as a separate struct

* factor out sigs serialization

* clean up sigs and coms serialization

* completed v4 bin serialization

* add manual de/ser traits for V4 bin slate

* add simple byte array serializer

* complete wiring in of bin slate serialization

* clarify comment

* clarify comment

* update version

* test output dir name fix

* update slate v4 change description

* add binary output to command line

* Remove unneeded signature data during S2 and I2 stages (#390)

* remove unneeded return signature data during S2

* remove unneeded sig data from I2

* Doctest Fixes for compact slate branch (#392)

* begin to fix doctests

* more doctest fixes

* fix receive_tx

* update get_stored_tx to accept an UUID instead of a tx object, and operate on a raw Transaction object (#394)

* Fixes to async transaction posting (#395)

* unstash post_tx changes

* add offset during S3 and I3

* Revert slate id serialization to hex-string uuid (#396)

* update from master (#397)

* v3.x.x - v4.0.0 wallet compatibility fixes (#398)

* changes to support http sending to v3 wallets

* sending via http/tor TO 3.0.0 wallet works

* receiving FROM 3.0.0 wallets works over http/tor

* output converted V3 slate when needed

* paying invoices from 3.0.0 wallets working

* handle all participant info in slate states

* sending and receiving standard file transactions between v3 and 4 wallets confirmed working

* all file-based workflows working

* fixes resulting from tests

* remove reminder warnings

* remove lock_height, add kernel_features + arguments (#399)

* grin-wallet master now building against grin master (#402) (#403)

Co-authored-by: Antioch Peverell <apeverell@protonmail.com>

* Enhanced offset creation (#407)

* initial tests reworking offset creation

* invoice flow fixing + tests

* further test fixes

* change offset name in v4 slate, base64 serialize

* logic optimisation

* changes based on review feedback

Co-authored-by: Antioch Peverell <apeverell@protonmail.com>
This commit is contained in:
Yeastplume
2020-05-19 11:19:03 +01:00
committed by GitHub
co-authored by Antioch Peverell
parent 19da1e4aec
commit 9450d2a3b8
49 changed files with 5124 additions and 3800 deletions
+35 -27
View File
@@ -16,17 +16,17 @@
use strum::IntoEnumIterator;
use crate::api_impl::owner::check_ttl;
use crate::grin_core::core::transaction::Transaction;
use crate::grin_keychain::Keychain;
use crate::grin_util::secp::key::SecretKey;
use crate::internal::{tx, updater};
use crate::internal::{selection, tx, updater};
use crate::slate_versions::SlateVersion;
use crate::{
address, BlockFees, CbData, Error, ErrorKind, NodeClient, Slate, TxLogEntryType, VersionInfo,
WalletBackend,
address, BlockFees, CbData, Error, ErrorKind, NodeClient, Slate, SlateState, TxLogEntryType,
VersionInfo, WalletBackend,
};
const FOREIGN_API_VERSION: u16 = 2;
const USER_MESSAGE_MAX_LEN: usize = 256;
/// Return the version info
pub fn check_version() -> VersionInfo {
@@ -51,18 +51,12 @@ where
updater::build_coinbase(&mut *w, keychain_mask, block_fees, test_mode)
}
/// verify slate messages
pub fn verify_slate_messages(slate: &Slate) -> Result<(), Error> {
slate.verify_messages()
}
/// 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>,
message: Option<String>,
use_test_rng: bool,
) -> Result<Slate, Error>
where
@@ -96,28 +90,25 @@ where
}
}
let message = match message {
Some(mut m) => {
m.truncate(USER_MESSAGE_MAX_LEN);
Some(m)
}
None => None,
};
// if this is compact mode, we need to create the transaction now
if ret_slate.is_compact() {
ret_slate.tx = Some(Transaction::empty());
}
tx::add_output_to_slate(
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,
1,
message,
false,
use_test_rng,
)?;
tx::update_message(&mut *w, keychain_mask, &ret_slate)?;
let keychain = w.keychain(keychain_mask)?;
let excess = ret_slate.calc_excess(&keychain)?;
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(
@@ -129,7 +120,15 @@ where
p.receiver_signature = Some(sig);
}
// Can remove amount and fee now
// as well as sender's sig data
if ret_slate.is_compact() {
ret_slate.amount = 0;
ret_slate.fee = 0;
ret_slate.remove_other_sigdata(&keychain, &context.sec_nonce, &context.sec_key)?;
}
ret_slate.state = SlateState::Standard2;
Ok(ret_slate)
}
@@ -146,14 +145,23 @@ where
{
let mut sl = slate.clone();
check_ttl(w, &sl)?;
let context = w.get_private_context(keychain_mask, sl.id.as_bytes(), 1)?;
tx::complete_tx(&mut *w, keychain_mask, &mut sl, 1, &context)?;
let context = w.get_private_context(keychain_mask, sl.id.as_bytes())?;
if sl.is_compact() {
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)?;
tx::update_message(&mut *w, keychain_mask, &sl)?;
{
let mut batch = w.batch(keychain_mask)?;
batch.delete_private_context(sl.id.as_bytes(), 1)?;
batch.delete_private_context(sl.id.as_bytes())?;
batch.commit()?;
}
sl.state = SlateState::Invoice3;
if sl.is_compact() {
sl.amount = 0;
}
Ok(sl)
}
+136 -66
View File
@@ -25,7 +25,7 @@ use crate::util::OnionV3Address;
use crate::api_impl::owner_updater::StatusMessage;
use crate::grin_keychain::{Identifier, Keychain};
use crate::internal::{keys, scan, selection, tx, updater};
use crate::slate::{PaymentInfo, Slate};
use crate::slate::{PaymentInfo, Slate, SlateState};
use crate::types::{AcctPathMapping, NodeClient, TxLogEntry, WalletBackend, WalletInfo};
use crate::{
address, wallet_lock, InitTxArgs, IssueInvoiceTxArgs, NodeHeightResult, OutputCommitMapping,
@@ -38,8 +38,6 @@ use ed25519_dalek::SecretKey as DalekSecretKey;
use std::sync::mpsc::Sender;
use std::sync::Arc;
const USER_MESSAGE_MAX_LEN: usize = 256;
/// List of accounts
pub fn accounts<'a, T: ?Sized, C, K>(w: &mut T) -> Result<Vec<AcctPathMapping>, Error>
where
@@ -318,15 +316,18 @@ where
None => w.parent_key_id(),
};
let message = match args.message {
Some(mut m) => {
m.truncate(USER_MESSAGE_MAX_LEN);
Some(m)
}
None => None,
};
let mut slate = tx::new_tx_slate(
&mut *w,
args.amount,
false,
2,
use_test_rng,
args.ttl_blocks,
)?;
let mut slate = tx::new_tx_slate(&mut *w, args.amount, 2, use_test_rng, args.ttl_blocks)?;
if let Some(v) = args.target_slate_version {
slate.version_info.version = v;
};
// if we just want to estimate, don't save a context, just send the results
// back
@@ -346,17 +347,17 @@ where
return Ok(slate);
}
let height = w.w2n_client().get_chain_tip()?.0;
let mut context = tx::add_inputs_to_slate(
&mut *w,
keychain_mask,
&mut slate,
height,
args.minimum_confirmations,
args.max_outputs as usize,
args.num_change_outputs as usize,
args.selection_strategy_is_use_all,
&parent_key_id,
0,
message,
true,
use_test_rng,
)?;
@@ -385,11 +386,12 @@ where
// recieve the transaction back
{
let mut batch = w.batch(keychain_mask)?;
batch.save_private_context(slate.id.as_bytes(), 0, &context)?;
batch.save_private_context(slate.id.as_bytes(), &context)?;
batch.commit()?;
}
if let Some(v) = args.target_slate_version {
slate.version_info.orig_version = v;
if slate.is_compact() {
slate.compact()?;
}
Ok(slate)
@@ -418,36 +420,32 @@ where
None => w.parent_key_id(),
};
let message = match args.message {
Some(mut m) => {
m.truncate(USER_MESSAGE_MAX_LEN);
Some(m)
}
None => None,
};
let mut slate = tx::new_tx_slate(&mut *w, args.amount, 2, use_test_rng, None)?;
let mut slate = tx::new_tx_slate(&mut *w, args.amount, true, 2, use_test_rng, None)?;
let height = w.w2n_client().get_chain_tip()?.0;
let context = tx::add_output_to_slate(
&mut *w,
keychain_mask,
&mut slate,
height,
&parent_key_id,
1,
message,
true,
use_test_rng,
)?;
if let Some(v) = args.target_slate_version {
slate.version_info.version = v;
};
// Save the aggsig context in our DB for when we
// recieve the transaction back
{
let mut batch = w.batch(keychain_mask)?;
batch.save_private_context(slate.id.as_bytes(), 1, &context)?;
batch.save_private_context(slate.id.as_bytes(), &context)?;
batch.commit()?;
}
if let Some(v) = args.target_slate_version {
slate.version_info.orig_version = v;
if slate.is_compact() {
slate.compact()?;
}
Ok(slate)
@@ -493,49 +491,77 @@ where
}
}
let message = match args.message {
Some(mut m) => {
m.truncate(USER_MESSAGE_MAX_LEN);
Some(m)
}
None => None,
};
// update slate current height
ret_slate.height = w.w2n_client().get_chain_tip()?.0;
let height = w.w2n_client().get_chain_tip()?.0;
// update ttl if desired
if let Some(b) = args.ttl_blocks {
ret_slate.ttl_cutoff_height = Some(ret_slate.height + b);
ret_slate.ttl_cutoff_height = height + b;
}
let context = tx::add_inputs_to_slate(
// if this is compact mode, we need to create the transaction now
if ret_slate.is_compact() {
ret_slate.tx = Some(Transaction::empty());
}
// if self sending, make sure to store 'initiator' keys
let context_res = w.get_private_context(keychain_mask, slate.id.as_bytes());
let mut context = tx::add_inputs_to_slate(
&mut *w,
keychain_mask,
&mut ret_slate,
height,
args.minimum_confirmations,
args.max_outputs as usize,
args.num_change_outputs as usize,
args.selection_strategy_is_use_all,
&parent_key_id,
0,
message,
false,
use_test_rng,
)?;
let keychain = w.keychain(keychain_mask)?;
// needs to be stored as we're removing sig data for return trip. this needs to be present
// when locking transaction context and updating tx log with excess later
context.calculated_excess = Some(ret_slate.calc_excess(keychain.secp())?);
// if self-sending, merge contexts
if let Ok(c) = context_res {
context.initial_sec_key = c.initial_sec_key;
context.initial_sec_nonce = c.initial_sec_nonce;
context.is_invoice = c.is_invoice;
context.fee = c.fee;
context.amount = c.amount;
for o in c.output_ids.iter() {
context.output_ids.push(o.clone());
}
for i in c.input_ids.iter() {
context.input_ids.push(i.clone());
}
}
// adjust offset with inputs, repopulate inputs (initiator needs them for now)
// TODO: Revisit post-HF3
if ret_slate.is_compact() {
tx::sub_inputs_from_offset(&mut *w, keychain_mask, &context, &mut ret_slate)?;
selection::repopulate_tx(&mut *w, keychain_mask, &mut ret_slate, &context, false)?;
}
// Save the aggsig context in our DB for when we
// recieve the transaction back
{
let mut batch = w.batch(keychain_mask)?;
batch.save_private_context(slate.id.as_bytes(), 0, &context)?;
batch.save_private_context(slate.id.as_bytes(), &context)?;
batch.commit()?;
}
if let Some(v) = args.target_slate_version {
ret_slate.version_info.orig_version = v;
// Can remove amount as well as other sig data now
if ret_slate.is_compact() {
ret_slate.amount = 0;
ret_slate.remove_other_sigdata(&keychain, &context.sec_nonce, &context.sec_key)?;
}
ret_slate.state = SlateState::Invoice2;
Ok(ret_slate)
}
@@ -544,15 +570,32 @@ pub fn tx_lock_outputs<'a, T: ?Sized, C, K>(
w: &mut T,
keychain_mask: Option<&SecretKey>,
slate: &Slate,
participant_id: usize,
) -> Result<(), Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let context = w.get_private_context(keychain_mask, slate.id.as_bytes(), participant_id)?;
selection::lock_tx_context(&mut *w, keychain_mask, slate, &context)
let context = w.get_private_context(keychain_mask, slate.id.as_bytes())?;
let mut sl = slate.clone();
let mut excess_override = None;
if sl.is_compact() && sl.tx == None {
// attempt to repopulate if we're the initiator
sl.tx = Some(Transaction::empty());
selection::repopulate_tx(&mut *w, keychain_mask, &mut sl, &context, true)?;
} else if sl.participant_data.len() == 1 {
// purely for invoice workflow, payer needs the excess back temporarily for storage
excess_override = context.calculated_excess;
}
let height = w.w2n_client().get_chain_tip()?.0;
selection::lock_tx_context(
&mut *w,
keychain_mask,
&sl,
height,
&context,
excess_override,
)
}
/// Finalize slate
@@ -568,17 +611,32 @@ where
{
let mut sl = slate.clone();
check_ttl(w, &sl)?;
let context = w.get_private_context(keychain_mask, sl.id.as_bytes(), 0)?;
let context = w.get_private_context(keychain_mask, sl.id.as_bytes())?;
let parent_key_id = w.parent_key_id();
tx::complete_tx(&mut *w, keychain_mask, &mut sl, 0, &context)?;
// since we're now actually inserting our inputs, pick an offset and adjust
// our contribution to the excess by offset amount
// TODO: Post HF3, this should allow for inputs to be picked at this stage
// as opposed to locking them prior to this stage, as the excess to this point
// will just be the change output
if sl.is_compact() {
tx::sub_inputs_from_offset(&mut *w, keychain_mask, &context, &mut sl)?;
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)?;
tx::update_message(&mut *w, keychain_mask, &sl)?;
{
let mut batch = w.batch(keychain_mask)?;
batch.delete_private_context(sl.id.as_bytes(), 0)?;
batch.delete_private_context(sl.id.as_bytes())?;
batch.commit()?;
}
sl.state = SlateState::Standard3;
if sl.is_compact() {
sl.amount = 0;
}
Ok(sl)
}
@@ -612,16 +670,13 @@ where
}
/// get stored tx
pub fn get_stored_tx<'a, T: ?Sized, C, K>(
w: &T,
entry: &TxLogEntry,
) -> Result<Option<Transaction>, Error>
pub fn get_stored_tx<'a, T: ?Sized, C, K>(w: &T, id: &Uuid) -> Result<Option<Transaction>, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
w.get_stored_tx(entry)
w.get_stored_tx(&format!("{}", id))
}
/// Posts a transaction to the chain
@@ -644,11 +699,6 @@ where
}
}
/// verify slate messages
pub fn verify_slate_messages(slate: &Slate) -> Result<(), Error> {
slate.verify_messages()
}
/// check repair
/// Accepts a wallet inst instead of a raw wallet so it can
/// lock as little as possible
@@ -727,6 +777,26 @@ where
}
}
}
/// return whether slate was an invoice tx
pub fn context_is_invoice<'a, L, C, K>(
wallet_inst: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
keychain_mask: Option<&SecretKey>,
slate: &Slate,
) -> Result<bool, Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let context = {
wallet_lock!(wallet_inst, w);
let context = w.get_private_context(keychain_mask, slate.id.as_bytes())?;
context
};
Ok(context.is_invoice)
}
/// Experimental, wrap the entire definition of how a wallet's state is updated
pub fn update_wallet_state<'a, L, C, K>(
wallet_inst: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
@@ -873,8 +943,8 @@ where
{
// Refuse if TTL is expired
let last_confirmed_height = w.last_confirmed_height()?;
if let Some(e) = slate.ttl_cutoff_height {
if last_confirmed_height >= e {
if slate.ttl_cutoff_height != 0 {
if last_confirmed_height >= slate.ttl_cutoff_height {
return Err(ErrorKind::TransactionExpired.into());
}
}
-35
View File
@@ -24,31 +24,6 @@ use grin_wallet_util::OnionV3Address;
use ed25519_dalek::Signature as DalekSignature;
/// Send TX API Args
// TODO: This is here to ensure the legacy V1 API remains intact
// remove this when v1 api is removed
#[derive(Clone, Serialize, Deserialize)]
pub struct SendTXArgs {
/// amount to send
pub amount: u64,
/// minimum confirmations
pub minimum_confirmations: u64,
/// payment method
pub method: String,
/// destination url
pub dest: String,
/// Max number of outputs
pub max_outputs: usize,
/// Number of change outputs to generate
pub num_change_outputs: usize,
/// whether to use all outputs (combine)
pub selection_strategy_is_use_all: bool,
/// Optional message, that will be signed
pub message: Option<String>,
/// Optional slate version to target when sending
pub target_slate_version: Option<u16>,
}
/// V2 Init / Send TX API Args
#[derive(Clone, Serialize, Deserialize)]
pub struct InitTxArgs {
@@ -80,12 +55,6 @@ pub struct InitTxArgs {
/// 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,
/// An optional participant message to include alongside the sender's public
/// ParticipantData within the slate. This message will include a signature created with the
/// sender's private excess value, and will be publically verifiable. Note this message is for
/// the convenience of the participants during the exchange; it is not included in the final
/// transaction sent to the chain. The message will be truncated to 256 characters.
pub message: Option<String>,
/// 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.
@@ -133,7 +102,6 @@ impl Default for InitTxArgs {
max_outputs: 500,
num_change_outputs: 1,
selection_strategy_is_use_all: true,
message: None,
target_slate_version: None,
ttl_blocks: None,
estimate_only: Some(false),
@@ -153,8 +121,6 @@ pub struct IssueInvoiceTxArgs {
/// The invoice amount in nanogrins. (`1 G = 1_000_000_000nG`)
#[serde(with = "secp_ser::string_or_u64")]
pub amount: u64,
/// Optional message, that will be signed
pub message: Option<String>,
/// 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.
@@ -166,7 +132,6 @@ impl Default for IssueInvoiceTxArgs {
IssueInvoiceTxArgs {
dest_acct_name: None,
amount: 0,
message: None,
target_slate_version: None,
}
}