mirror of
https://github.com/jwinterm/grin-wallet.git
synced 2026-12-05 05:13:59 +01:00
[CONTRACTS] Contracts branch update for 1.80 (#718)
* Simple contracts restructured v3 (#675) * Add prototype contract implementation Lacks: - Payment proofs (add early payment proofs) - Tests - Better structure * Separate contract utilities * Simplify the main setup/sign code flow * Remove commented initial_sec_key assignment * Simplify sign::compute function * Add logic for "removal" of secret keys from the context * Further simplify a bit sign and setup * No need for mutable context when adding outputs * Refactor the commented code (lol) * Refactor a bit * tmp --------- Co-authored-by: oryhp <gtrphyro@gmail.com> * contract test fixes (#676) * [Contracts] Experimental Slate v5 (#677) * beginning to add and modify slate version 5 * completion of conversions from V5 to V4 Slate * timestamp and memo fields * upgrade/downgrade serialization of v5 slates * add v5 binary slate versions + start of tests * add bin slate ser/deser to tests * ensure serialization of timestamp always excludes milliseconds * start to update v5 tests, update v5 documentation * add fn to generate populated internal slate for conversion testing * add basic tests to convert all slate versions * update * commit cargo.lock * [WIP] [Contracts] Early payment proofs (#681) * add types and beginnings of signature utils * add proof serialization * serialisation of proof data + signature operation * add serialization type for invoice proof + separate bin wrapper version * add witness data + serializion to invoice payment proof, insert verfication functions in place in order to begin verification testing * tests and infrastructure in place for validation * verification of promise sig * added verification of promise signature, infrastructure up to the point where a signature must be subtracted * attempting to figure out differences between recipient nonce that's getting stored and calculated recipient nonce * implementation of witness verification function, retrieve relevant values and re-validate derived recipient partial signature * move stored portion of invoice proof into core types for storage, need to rename invoice proof * define/refine the stored portion of payment proofs type 2? * Folding all proof data into tx log entry storage * back to importing master * remove cargo files from diffs * remove a lot of extra debug output * return proof witness as part of proof retrieval, define json serialization of invoice proof + witness fields * finish adding verification steps to foreign API * remove redundant promise sig field * move lcation of sign/verify calls * Replace Azure Pipelines with Github Actions (#688) * Update CI Badge on README.MD (#690) * Trigger CI on push and pull request (#693) * Update versioning to 5.2.0-beta.1 against grin 5.2.0-beta.3 (#691) * update versioning to 5.2.0-beta.1 against grin 5.2.0-beta.3 * tweak for CI trigger --------- Co-authored-by: Quentin Le Sceller <q.lesceller@gmail.com> --------- Co-authored-by: Quentin Le Sceller <q.lesceller@gmail.com> * fix Cargo.lock * Contracts - Test fixes + warning cleanups (#694) * clean up warnings in libwallet crate * clean up warnings in controller crate * update all contract tests with awareness of new proof structure * added explicit payment proof tests for both rsr and srs (#695) * Basic mwmixnet send (#696) * integrating onion library * updates and changes to support newly included mwmixnet types * add (incorrect) owner api function * turn off test for now * switch working grin branch to master * fix doctests for build * update cargo lock in attempt to fix croaring build on CI server * update cargo lock with upstream thiserror crate * update test dependency for croaring * [Contracts] Add self spend transaction state (#697) * Add self spend transaction state * subtle errors with output states and tx lookups - fixes * [Contracts] Slatepack v5 Deserialization fix (#698) * add V5 deserialization test + fixes * clarify comment * upwrap fix during v4 deserialization * further unwrap removal * update cargo lock, use latest grin packages * addition of self-spend cancel + tests (#699) * add tests + legacy self send cancel (#702) * [Contracts] Cancel self-spend TX Pt. 2 (#703) * add tests + legacy self send cancel * add missing file * Update grin to latest master, change versioning label to include contracts (#712) * Add owner_api_listen_interface as hidden configuration field (#714) * updates for rust 1.80 * updates for rust 1.80 --------- Co-authored-by: oryhp <gtrphyro@gmail.com> Co-authored-by: Quentin Le Sceller <q.lesceller@gmail.com>
This commit is contained in:
co-authored by
oryhp
Quentin Le Sceller
parent
765f11b168
commit
cdd63fb565
@@ -0,0 +1,116 @@
|
||||
# Contract actions
|
||||
|
||||
### API endpoints
|
||||
|
||||
We introduce 3 new API endpoints `/new, /setup, /sign` each corresponding to a specific action on a contract. In the future we'll add the ability to also `view` a contract and to `revoke` it.
|
||||
|
||||
### Rust implementation
|
||||
|
||||
Every contract action on a slate is divided in 3 parts:
|
||||
1. compute the new state
|
||||
2. save the new state
|
||||
3. return slate
|
||||
|
||||
Putting this into code, it looks like the following:
|
||||
```rust
|
||||
// Compute the new state (both of the Slate and the Context)
|
||||
let (slate, context) = compute(slate, args);
|
||||
// Atomically commit the new state
|
||||
contract_utils::save_step(slate, context, ...);
|
||||
// Return the newly produced slate
|
||||
return slate;
|
||||
```
|
||||
|
||||
We only allow contribution of custom inputs/outputs when we're doing the setup phase. Once the setup phase is done,
|
||||
we no longer allow any customization of inputs. This means that the customization can only happen at contract setup phase which is the first time we see the contract.Additionally, if we customize output selection, we immediately pick the inputs/outputs which means it's an early lock. These are however not added to the slate until we reach the 'sign' phase of the contract. Counterparties don't need to see our inputs/outputs before that. This means we always add inputs/outputs only when we have to and never before.
|
||||
|
||||
Ideally we'd also separate side effects out of these functions e.g. computing the current_height
|
||||
or refreshing the outputs with updater::refresh_outputs(...). The current_height could be
|
||||
communicated through a &ChainState parameter which would collect these values before the call.
|
||||
Additionally, we could fetch the existing Context before the call to avoid doing db fetch.
|
||||
Separating side effects until the 'save_step' part would make these functions much easier to test.
|
||||
|
||||
#### TODOs
|
||||
|
||||
- for payjoins, instead of doing Some("any"), find an actual input and put the actual commitment in --use-inputs (only do that if none is added). Think about how to do that in a way that would be nice also for the API. Maybe the API should just take "any" which gets transformed into one of the random inputs. Maybe the "any" is ok. It seems to work fine, might be better if we selected the input though.
|
||||
- make sure to forget the Context when we sign or at least forget the secret keys for it to avoid signing with the same nonce twice
|
||||
- make_outputs api should receive nanogrins rather than grin. We have to make the conversion before calling the API
|
||||
- sometimes the slatepack outputs with a \n for some reason which makes pasting it register \n as the end of paste and crashes?
|
||||
- remove casting decimals, we should accept value in nanogrins (including --make-outputs option), never as 0.1 Grin through the interface. Casting should be left to the gui wallet logic
|
||||
- Check casts to/from i64/u64 etc. consider using saturating methods. Make sure conversions are safe.
|
||||
- separate side-effects out from the main computations
|
||||
- is keys::next_available_key(..) safe from race-conditions? (do we lock?)
|
||||
- function add_output_to_ctx has a comment around next_available_key
|
||||
- add support for different accounts not just main (check parent_id, parent_key_id, etc. usage)
|
||||
- ensure counterparty can't make you overpay fees through num_participants param
|
||||
- make sure the stored transaction is saved correctly at each step (TxLogEntry has stored_tx field, check other fields as well)
|
||||
- make sure the transaction log contains all the necessary data (check TODO comments on tx log entry functions)
|
||||
- graceful error handling
|
||||
- setup.rs# TODO: verify that the parent_key_id is consistent
|
||||
- replace mutable objects with immutable when possible
|
||||
- make sure we lock the wallet when needed (check wallet_lock!() macro that is used in api/owner.rs)
|
||||
- add support for more than 2 parties (includes a new 'setup' API endpoint and command)
|
||||
- do we avoid using "too recent" outputs? e.g. though with depth < 10
|
||||
- remove unneeded imports
|
||||
- think if Context.setup_args.net_change type should be u64. If you make it i64, you divide it's size by 2. Perhaps it would be
|
||||
better to have a u64 field and another field called 'positive' of type bool.
|
||||
- add --no-setup to 'new' command
|
||||
- add early-payment proofs. Make sure we have a symmetric variant of a payment proof to avoid having different proofs based on which position you are in the contract signing. Ideally, the position would be irrelevant.
|
||||
- what happens if you call contract sign on some slate that was not initiated as a contract slate and has different context values?
|
||||
- make sure you handle all the flows with coinbase outputs as well
|
||||
- check if they can trick you by providing a slate with different inputs/outputs that are yours
|
||||
- remove 'setup' API/CLI
|
||||
- move the contract test utilities to a separate contract_utilities file instead of having it in 'common/mod.rs'
|
||||
- we have --add-outputs, but we should also lock if we use the --use-inputs param
|
||||
- check if contract_accounts_switch.rs is a legit scenario. It might need to return an error if the wallet is trying to sign with a different account
|
||||
|
||||
#### Tests
|
||||
- test contract_fee (various test around fee contribution with 1 or 2 parties)
|
||||
- test save_step functionality (stored tx, context, logs,..)
|
||||
- test different output selection in step1 and step3
|
||||
- test foreign API for contract new and sign
|
||||
- test a case where the receiver doesn't have an input available (either not enough confirmations or no inputs)
|
||||
- contract_rsr.rs asserts that you get amount_credited=5, should it subtract the fees?
|
||||
- test using more than a single input
|
||||
- test that sending then again the same slatepack doesn't produce a new signature (to avoid leaking key)
|
||||
- test locking:
|
||||
* test that outputs are locked after you sign
|
||||
* test early locking when using --make-outputs or --use-inputs etc.
|
||||
- test --no-payjoin
|
||||
- test accounts
|
||||
- test 0-value outputs
|
||||
- test that if --no-payjoin is used, this doesn't mean that we early lock (we shouldn't). Same for --make-outputs
|
||||
- test slate content through steps
|
||||
- test negative cases (not enough funds, using input that doesn't exist, make outputs that go over the value, sign twice,...)
|
||||
|
||||
#### DONE
|
||||
- Always "late-add" inputs/outputs to the slate
|
||||
- _Always_ add a change output, even if the change output ends up being a 0-value output
|
||||
|
||||
|
||||
#### save_step
|
||||
|
||||
// TODO:
|
||||
// - is_signed should be derived from the slate
|
||||
// - Check what happens if the batch fails. Also think about possible race conditions because
|
||||
// of the time delay between the id was picked and saved.
|
||||
// - Consider taking ownership of Context here. It should not be used after this is called.
|
||||
|
||||
|
||||
### Side-effects
|
||||
|
||||
#### Setup
|
||||
// Side-effects:
|
||||
// - height = w.w2n_client().get_chain_tip()?.0;
|
||||
// - maybe_context = w.get_private_context(keychain_mask, sl.id.as_bytes())
|
||||
// - create_contract_ctx -> updater::refresh_outputs(wallet, keychain_mask, parent_key_id, false)?;
|
||||
// - add_outputs -> let current_height = w.w2n_client().get_chain_tip()?.0;
|
||||
// - add_outputs -> contribute_output -> let key_id = keys::next_available_key(wallet, keychain_mask).unwrap();
|
||||
// - TODO: would we need to compute keys::next_available_key for as many outputs as we plan to contribute and pass
|
||||
// them as a param to keep this without side effects?
|
||||
|
||||
#### Sign
|
||||
// Side-effects:
|
||||
// - contract_utils::check_already_signed -> tx_log_iter
|
||||
// - contract_utils::get_net_change -> context and net_change
|
||||
// - everything from 'setup'
|
||||
@@ -0,0 +1,27 @@
|
||||
// Copyright 2022 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 contract related actions.
|
||||
|
||||
mod new;
|
||||
mod revoke;
|
||||
mod setup;
|
||||
mod sign;
|
||||
mod view;
|
||||
|
||||
pub use self::new::new;
|
||||
pub use self::revoke::revoke;
|
||||
pub use self::setup::setup;
|
||||
pub use self::sign::sign;
|
||||
pub use self::view::view;
|
||||
@@ -0,0 +1,76 @@
|
||||
// Copyright 2022 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.
|
||||
|
||||
//! Implementation of contract new
|
||||
|
||||
use crate::contract;
|
||||
use crate::contract::actions::setup;
|
||||
use crate::contract::types::ContractSetupArgsAPI;
|
||||
use crate::error::Error;
|
||||
use crate::grin_keychain::Keychain;
|
||||
use crate::grin_util::secp::key::SecretKey;
|
||||
use crate::slate::Slate;
|
||||
use crate::types::{Context, NodeClient, WalletBackend};
|
||||
|
||||
/// Create a new contract with initial setup done by the initiator
|
||||
pub fn new<'a, T: ?Sized, C, K>(
|
||||
w: &mut T,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
setup_args: &ContractSetupArgsAPI,
|
||||
) -> Result<Slate, Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
// Compute state for 'new'
|
||||
let (slate, mut context) = compute(w, keychain_mask, setup_args)?;
|
||||
|
||||
// Atomically commit state
|
||||
contract::utils::save_step(
|
||||
w,
|
||||
keychain_mask,
|
||||
&slate,
|
||||
&mut context,
|
||||
setup_args.add_outputs,
|
||||
false,
|
||||
)?;
|
||||
|
||||
Ok(slate)
|
||||
}
|
||||
|
||||
/// Compute logic for new
|
||||
pub fn compute<'a, T: ?Sized, C, K>(
|
||||
w: &mut T,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
setup_args: &ContractSetupArgsAPI,
|
||||
) -> Result<(Slate, Context), Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
let net_change = setup_args.net_change.unwrap();
|
||||
debug!("contract::new => net_change passed: {}", net_change);
|
||||
|
||||
// Initialize a new contract (if net_change is positive, I'm the receiver meaning this is invoice flow)
|
||||
let num_participants = setup_args.num_participants;
|
||||
let mut slate = Slate::blank(num_participants, net_change > 0);
|
||||
// We set slate.amount to contain the _positive_ net_change for the other party so they can derive expectations.
|
||||
slate.amount = net_change.abs() as u64;
|
||||
debug!("contract::new => slate amount: {}", slate.amount);
|
||||
|
||||
// Perform setup for the slate
|
||||
setup::compute(w, keychain_mask, &mut slate, setup_args)
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// Copyright 2022 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.
|
||||
|
||||
//! Implementation of contract revoke
|
||||
use crate::contract::types::{ContractRevokeArgsAPI, ContractSetupArgsAPI, OutputSelectionArgs};
|
||||
use crate::contract::{new, sign};
|
||||
use crate::error::Error;
|
||||
use crate::grin_keychain::Keychain;
|
||||
use crate::grin_util::secp::key::SecretKey;
|
||||
use crate::internal::tx;
|
||||
use crate::slate::Slate;
|
||||
use crate::types::{NodeClient, OutputData, OutputStatus, WalletBackend};
|
||||
|
||||
/// Contract revocation is done by double-spending the input
|
||||
pub fn revoke<'a, T: ?Sized, C, K>(
|
||||
w: &mut T,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
args: &ContractRevokeArgsAPI,
|
||||
) -> Result<Option<Slate>, Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
// TODO: check the correctness of this. This is essentially old cancel + self-spend.
|
||||
// FUTURE: we may want to boost fees in case we notice something in the mempool. There
|
||||
// are also race conditions possible. We may not want to label txlogenry as Canceled
|
||||
// until the new tx gets on the chain.
|
||||
// NOTE: We should not care about deleting the context because as soon as we sign
|
||||
// a contract, the context is deleted.
|
||||
|
||||
// If we contributed inputs, we must have locked them at which point we also set the
|
||||
// OutputData.tx_log_entry which is the tx_id.
|
||||
let tx_id = args.tx_id;
|
||||
|
||||
// Find my outputs that have been Locked and refer to the given tx_id
|
||||
let my_contributed_inputs = w
|
||||
.batch(keychain_mask)?
|
||||
.iter()
|
||||
.filter(|out| {
|
||||
// Find an output that is Locked and is in the tx_input_commit
|
||||
out.status == OutputStatus::Locked
|
||||
&& (out.tx_log_entry.is_some() && out.tx_log_entry.as_ref().unwrap() == &tx_id)
|
||||
})
|
||||
.collect::<Vec<OutputData>>();
|
||||
|
||||
// 1. Unlock the input by calling cancel_tx
|
||||
let parent_key_id = w.parent_key_id();
|
||||
tx::cancel_tx(&mut *w, keychain_mask, &parent_key_id, Some(tx_id), None)?;
|
||||
|
||||
if my_contributed_inputs.len() == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let input_commit = my_contributed_inputs[0].commit.as_ref().unwrap();
|
||||
// 2. Create a 1-1 self-spend transaction using this input
|
||||
let ct_slate = new(
|
||||
w,
|
||||
keychain_mask,
|
||||
&ContractSetupArgsAPI {
|
||||
// TODO: Check the src_acct_name below. This would use the currently active account
|
||||
src_acct_name: None,
|
||||
net_change: Some(0), // self-spend
|
||||
num_participants: 1,
|
||||
add_outputs: false,
|
||||
selection_args: OutputSelectionArgs {
|
||||
use_inputs: Some(String::from(input_commit)),
|
||||
..Default::default()
|
||||
},
|
||||
proof_args: Default::default(),
|
||||
},
|
||||
)?;
|
||||
let finished_slate = sign(
|
||||
w,
|
||||
keychain_mask,
|
||||
&ct_slate,
|
||||
&ContractSetupArgsAPI {
|
||||
// TODO: Check the src_acct_name below. This would use the currently active account
|
||||
src_acct_name: None,
|
||||
net_change: None, // we already have it in the context as 0 now
|
||||
num_participants: 1,
|
||||
add_outputs: false,
|
||||
selection_args: OutputSelectionArgs {
|
||||
use_inputs: Some(String::from(input_commit)),
|
||||
..Default::default()
|
||||
},
|
||||
proof_args: Default::default(),
|
||||
},
|
||||
)?;
|
||||
// TODO: Think about what to do with transaction context of the cancelled slate. It should probably get deleted.
|
||||
|
||||
Ok(Some(finished_slate))
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// Copyright 2022 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.
|
||||
|
||||
//! Implementation of contract setup
|
||||
|
||||
use crate::api_impl::owner::check_ttl;
|
||||
use crate::contract;
|
||||
use crate::contract::types::ContractSetupArgsAPI;
|
||||
use crate::error::Error;
|
||||
use crate::grin_keychain::Keychain;
|
||||
use crate::grin_util::secp::key::SecretKey;
|
||||
use crate::slate::Slate;
|
||||
use crate::types::{Context, NodeClient, WalletBackend};
|
||||
|
||||
/// Perform a contract setup
|
||||
pub fn setup<'a, T: ?Sized, C, K>(
|
||||
w: &mut T,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
slate: &Slate,
|
||||
setup_args: &ContractSetupArgsAPI,
|
||||
) -> Result<Slate, Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
// Compute state for 'setup'
|
||||
let (slate, mut context) = compute(w, keychain_mask, slate, setup_args)?;
|
||||
|
||||
// Atomically commit state
|
||||
contract::utils::save_step(
|
||||
w,
|
||||
keychain_mask,
|
||||
&slate,
|
||||
&mut context,
|
||||
setup_args.add_outputs,
|
||||
false,
|
||||
)?;
|
||||
|
||||
Ok(slate)
|
||||
}
|
||||
|
||||
/// Compute logic for setup
|
||||
pub fn compute<'a, T: ?Sized, C, K>(
|
||||
w: &mut T,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
slate: &Slate,
|
||||
setup_args: &ContractSetupArgsAPI,
|
||||
) -> Result<(Slate, Context), Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
let mut sl = slate.clone();
|
||||
check_ttl(w, &sl)?;
|
||||
|
||||
// Get or create a transaction Context and verify consistency of setup arguments
|
||||
let mut context = contract::context::get_or_create(w, keychain_mask, &mut sl, setup_args)?;
|
||||
contract::utils::verify_setup_args_consistency(
|
||||
&context.setup_args.as_ref().unwrap(),
|
||||
&setup_args,
|
||||
)?;
|
||||
|
||||
// Add keys and payment proof to slate (both are idempotent operations)
|
||||
contract::slate::add_keys(&mut sl, &w.keychain(keychain_mask)?, &mut context)?;
|
||||
contract::slate::add_payment_proof(
|
||||
w,
|
||||
&mut sl,
|
||||
keychain_mask,
|
||||
&mut context,
|
||||
&setup_args.net_change,
|
||||
&setup_args.proof_args,
|
||||
)?; // noop for the sender
|
||||
|
||||
// Add inputs/outputs to the Context if needed. No locking is done here. This happens at save_step.
|
||||
if setup_args.add_outputs {
|
||||
contract::context::add_outputs(&mut *w, keychain_mask, &mut context)?;
|
||||
}
|
||||
|
||||
Ok((sl, context))
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
// Copyright 2022 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.
|
||||
|
||||
//! Implementation of contract sign
|
||||
|
||||
use crate::contract;
|
||||
use crate::contract::actions::setup;
|
||||
use crate::contract::types::ContractSetupArgsAPI;
|
||||
use crate::error::Error;
|
||||
use crate::grin_keychain::Keychain;
|
||||
use crate::grin_util::secp::key::SecretKey;
|
||||
use crate::slate::Slate;
|
||||
use crate::types::{Context, NodeClient, WalletBackend};
|
||||
|
||||
/// Sign a contract
|
||||
pub fn sign<'a, T: ?Sized, C, K>(
|
||||
w: &mut T,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
slate: &Slate,
|
||||
setup_args: &ContractSetupArgsAPI,
|
||||
) -> Result<Slate, Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
// Compute if we will add outputs at this step
|
||||
let will_add_outputs = match w.get_private_context(keychain_mask, slate.id.as_bytes()) {
|
||||
Ok(ctx) => ctx.get_inputs().len() + ctx.get_outputs().len() == 0,
|
||||
Err(_) => true,
|
||||
};
|
||||
// Compute state for 'sign'
|
||||
let (sl, mut context) = compute(w, keychain_mask, slate, setup_args)?;
|
||||
|
||||
// Atomically commit state
|
||||
contract::utils::save_step(w, keychain_mask, &sl, &mut context, will_add_outputs, true)?;
|
||||
|
||||
Ok(sl)
|
||||
}
|
||||
|
||||
/// Compute logic for sign
|
||||
pub fn compute<'a, T: ?Sized, C, K>(
|
||||
w: &mut T,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
slate: &Slate,
|
||||
setup_args: &ContractSetupArgsAPI,
|
||||
) -> Result<(Slate, Context), Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
let mut sl = slate.clone();
|
||||
contract::utils::verify_not_signed(w, sl.id)?;
|
||||
|
||||
// Ensure net_change has been provided
|
||||
let expected_net_change =
|
||||
contract::utils::get_net_change(w, keychain_mask, &sl, setup_args.net_change)?;
|
||||
|
||||
// Define the values that must be provided in the setup phase at the sign step
|
||||
let mut setup_args = setup_args.clone();
|
||||
setup_args.net_change = Some(expected_net_change);
|
||||
setup_args.num_participants = sl.num_participants;
|
||||
setup_args.add_outputs = true; // we add outputs to the Context in case we haven't done that yet
|
||||
|
||||
// Ensure Setup phase is done and that inputs/outputs have been added to the Context
|
||||
let (mut sl, mut context) = setup::compute(w, keychain_mask, &mut sl, &setup_args)?;
|
||||
// Add outputs to the slate, verify the payment proof and sign the slate
|
||||
contract::slate::add_outputs(w, keychain_mask, &mut sl, &context)?;
|
||||
if let Some(ref p) = sl.payment_proof {
|
||||
contract::slate::verify_payment_proof(&sl, expected_net_change, &p.receiver_address)?;
|
||||
// noop for the receiver
|
||||
}
|
||||
|
||||
contract::slate::sign(w, keychain_mask, &mut sl, &mut context)?;
|
||||
contract::slate::transition_state(&mut sl)?;
|
||||
|
||||
// If we have all the partial signatures, finalize the tx
|
||||
if contract::slate::can_finalize(&sl) {
|
||||
contract::slate::finalize(w, keychain_mask, &mut sl)?;
|
||||
}
|
||||
|
||||
Ok((sl, context))
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// Copyright 2022 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.
|
||||
|
||||
//! Implementation of contract view
|
||||
|
||||
use crate::contract::types::ContractView;
|
||||
use crate::error::Error;
|
||||
use crate::grin_keychain::Keychain;
|
||||
use crate::grin_util::secp::key::SecretKey;
|
||||
use crate::slate::{Slate, SlateState};
|
||||
use crate::types::{NodeClient, WalletBackend};
|
||||
|
||||
/// View contract
|
||||
pub fn view<'a, T: ?Sized, C, K>(
|
||||
_w: &mut T,
|
||||
_keychain_mask: Option<&SecretKey>,
|
||||
slate: &mut Slate,
|
||||
_encrypted_for: &str,
|
||||
) -> Result<ContractView, Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
// NOTE: This should only be run on slates that we received and were signed for us.
|
||||
// Otherwise, you can't really predict who the party doing the next step should be.
|
||||
|
||||
// TODO: Do we need to do any slate verification here?
|
||||
let suggested_net_change: Option<i64> = match slate.state {
|
||||
// TODO: Check bounds against overflow/underflow
|
||||
SlateState::Invoice1 => Some(slate.amount as i64),
|
||||
SlateState::Standard1 => Some(-(slate.amount as i64)),
|
||||
_ => None,
|
||||
};
|
||||
let is_executed = false;
|
||||
let num_sigs = slate
|
||||
.participant_data
|
||||
.clone()
|
||||
.into_iter()
|
||||
.filter(|v| !v.is_complete())
|
||||
.count();
|
||||
|
||||
// TODO: Maybe we can know if the slate was meant for us if it was encrypted for us.
|
||||
// A possible issue is that one can encrypt the same slate for 10 people.
|
||||
let ct_view = ContractView {
|
||||
num_participants: slate.num_participants,
|
||||
suggested_net_change: suggested_net_change,
|
||||
agreed_net_change: None, // TODO
|
||||
num_sigs: num_sigs as u8,
|
||||
is_executed: is_executed,
|
||||
..Default::default()
|
||||
};
|
||||
Ok(ct_view)
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
// Copyright 2022 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.
|
||||
|
||||
//! Contract functions on the Context
|
||||
|
||||
use crate::contract::selection::prepare_outputs;
|
||||
use crate::contract::types::ContractSetupArgsAPI;
|
||||
use crate::contract::utils as contract_utils;
|
||||
use crate::grin_keychain::{Identifier, Keychain};
|
||||
use crate::grin_util::secp::key::SecretKey;
|
||||
use crate::internal::{keys, updater};
|
||||
use crate::slate::Slate;
|
||||
use crate::types::{Context, NodeClient, WalletBackend};
|
||||
use crate::{Error, OutputData};
|
||||
use grin_core::core::FeeFields;
|
||||
|
||||
/// Get or create transaction Context for the given slate
|
||||
pub fn get_or_create<'a, T: ?Sized, C, K>(
|
||||
w: &mut T,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
slate: &mut Slate,
|
||||
setup_args: &ContractSetupArgsAPI,
|
||||
) -> Result<Context, Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
debug!("contract::context::get_or_create => called");
|
||||
let maybe_context = w.get_private_context(keychain_mask, slate.id.as_bytes());
|
||||
|
||||
let context = match maybe_context {
|
||||
Err(_) => {
|
||||
// Get data required for creating a context
|
||||
let height = w.w2n_client().get_chain_tip()?.0;
|
||||
let parent_key_id =
|
||||
contract_utils::parent_key_for(w, setup_args.src_acct_name.as_ref());
|
||||
self::create(
|
||||
w,
|
||||
keychain_mask,
|
||||
slate,
|
||||
height,
|
||||
// &args,
|
||||
setup_args,
|
||||
&parent_key_id,
|
||||
false,
|
||||
)?
|
||||
}
|
||||
Ok(ctx) => ctx,
|
||||
};
|
||||
Ok(context)
|
||||
}
|
||||
|
||||
/// Creates a context for a contract
|
||||
fn create<'a, T: ?Sized, C, K>(
|
||||
w: &mut T,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
slate: &mut Slate,
|
||||
current_height: u64,
|
||||
// TODO: compare with &InitTxArgs to see if any information is missing
|
||||
setup_args: &ContractSetupArgsAPI,
|
||||
parent_key_id: &Identifier,
|
||||
use_test_rng: bool,
|
||||
) -> Result<Context, Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
debug!("Creating a new contract context");
|
||||
// sender should always refresh outputs
|
||||
updater::refresh_outputs(w, keychain_mask, parent_key_id, false)?;
|
||||
|
||||
// Fee contribution estimation
|
||||
let net_change = setup_args.net_change.unwrap();
|
||||
// select inputs to estimate fee cost
|
||||
let (inputs, _, my_fee) =
|
||||
prepare_outputs(w, &parent_key_id, current_height, &setup_args, None)?;
|
||||
// The number of outputs we expect is the number of custom outputs plus one change output
|
||||
debug!(
|
||||
"My fee contribution estimation: {} for n_inputs: {}, n_outputs: {}, n_kernels: {}, num_participants: {}",
|
||||
my_fee.fee(), inputs.len(), setup_args.selection_args.num_custom_outputs() + 1, 1, setup_args.num_participants
|
||||
);
|
||||
// Make sure `my_fee < net_change` holds for the receiver. This can't be true for a self-spend, because nobody
|
||||
// has a net_change > 0 which makes a self-spend ok to be a net negative when fees are included.
|
||||
if net_change > 0 && my_fee.fee() > net_change.abs() as u64 {
|
||||
panic!(
|
||||
"My contribution as a receiver would be net negative. my_fee: {}, net_change: {}",
|
||||
my_fee.fee(),
|
||||
net_change
|
||||
);
|
||||
}
|
||||
// Add my share of fee contribution to the slate fees
|
||||
slate.fee_fields = FeeFields::new(0, slate.fee_fields.fee() + my_fee.fee())?;
|
||||
debug!("Slate.fee: {}", slate.fee_fields.fee());
|
||||
|
||||
// Create a Context for this slate
|
||||
let keychain = w.keychain(keychain_mask)?;
|
||||
// TODO: it seems 'is_initiator: true' is only used in test_rng. Do we care about this?
|
||||
let mut context = Context::new(keychain.secp(), &parent_key_id, use_test_rng, true);
|
||||
// Context.fee will hold _our_ fee contribution and not the total slate fee
|
||||
context.fee = my_fee.as_opt();
|
||||
// Context.amount is not used in contracts, but we set it anyway.
|
||||
context.amount = slate.amount;
|
||||
// TODO: looking at what uses Context.late_lock_args, it seems only the args in SelectionArgs are used except
|
||||
// for args.ttl_blocks. Is this needed? Can we refactor this?
|
||||
context.setup_args = Some(setup_args.clone());
|
||||
debug!(
|
||||
"Setting Context.net_change as: {}",
|
||||
context.get_net_change()
|
||||
);
|
||||
|
||||
Ok(context)
|
||||
}
|
||||
|
||||
/// Add outputs to a contract context (including spent outputs which get locked)
|
||||
pub fn add_outputs<'a, T: ?Sized, C, K>(
|
||||
w: &mut T,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
context: &mut Context,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
debug!("contract::utils::add_outputs => called");
|
||||
// Do nothing if we have already contributed our outputs. The assumption is that if this was done,
|
||||
// our output contribution is complete.
|
||||
if context.output_ids.len() > 0 || context.input_ids.len() > 0 {
|
||||
debug!("contract::utils::add_outputs => outputs have already been added, returning.");
|
||||
return Ok(());
|
||||
}
|
||||
let setup_args = context.setup_args.as_ref().unwrap();
|
||||
debug!("contract::utils::add_outputs => adding outputs");
|
||||
let current_height = w.w2n_client().get_chain_tip()?.0;
|
||||
let parent_key_id = &context.parent_key_id;
|
||||
|
||||
// Select inputs for which `Σmy_inputs >= Σmy_outputs + my_fee_cost` holds. Uses committed fee if present.
|
||||
let (inputs, my_output_amounts, my_fee) = prepare_outputs(
|
||||
&mut *w,
|
||||
parent_key_id,
|
||||
current_height,
|
||||
&setup_args,
|
||||
context.fee,
|
||||
)?;
|
||||
assert_eq!(my_fee.fee(), context.fee.unwrap().fee(), "my_fee!=ctx.fee");
|
||||
// Add selected/created inputs/outputs to the context
|
||||
add_inputs_to_ctx(context, &inputs)?;
|
||||
add_outputs_to_ctx(w, keychain_mask, context, my_output_amounts)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add inputs to Context
|
||||
fn add_inputs_to_ctx(context: &mut Context, inputs: &Vec<OutputData>) -> Result<(), Error> {
|
||||
debug!("contract::utils::add_inputs_to_ctx => adding inputs to context");
|
||||
for input in inputs {
|
||||
context.add_input(&input.key_id, &input.mmr_index, input.value);
|
||||
debug!(
|
||||
"contract::utils::add_inputs_to_ctx => input id: {}, value:{}",
|
||||
&input.key_id, input.value
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add outputs to Context
|
||||
fn add_outputs_to_ctx<'a, T: ?Sized, C, K>(
|
||||
w: &mut T,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
context: &mut Context,
|
||||
amounts: Vec<u64>,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
for amount in amounts {
|
||||
// TODO: it seems like next_available_key does not respect the parent_key_id. Check if it does, it probably should?
|
||||
// A late-lock might have a different account set to active than the one that was set to the Context
|
||||
let key_id = keys::next_available_key(w, keychain_mask).unwrap();
|
||||
context.add_output(&key_id, &None, amount);
|
||||
debug!(
|
||||
"contract::utils::add_output_to_ctx => added output to context. Output id: {}, amount: {}",
|
||||
key_id.clone(),
|
||||
amount
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// Copyright 2022 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 contract related actions.
|
||||
|
||||
mod actions;
|
||||
mod context;
|
||||
pub mod proofs;
|
||||
mod selection;
|
||||
mod slate;
|
||||
pub mod types;
|
||||
mod utils;
|
||||
|
||||
pub use self::actions::{new, revoke, setup, sign, view};
|
||||
|
||||
pub use self::slate::can_finalize;
|
||||
pub use self::utils::my_fee_contribution;
|
||||
@@ -0,0 +1,452 @@
|
||||
// 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.
|
||||
|
||||
//! Experimental early payment proof functionality, currently only used
|
||||
//! with contracts. Can move outside of this module if early proofs are adopted
|
||||
//! by legacy transactions
|
||||
|
||||
use crate::contract::types::ProofArgs;
|
||||
use crate::grin_core::libtx::aggsig;
|
||||
use crate::grin_core::libtx::secp_ser;
|
||||
use crate::grin_core::ser as grin_ser;
|
||||
use crate::grin_core::ser::{Readable, Reader, Writeable, Writer};
|
||||
use crate::grin_keychain::Keychain;
|
||||
use crate::grin_util::secp::key::{PublicKey, SecretKey};
|
||||
use crate::grin_util::secp::pedersen::Commitment;
|
||||
use crate::grin_util::secp::Signature;
|
||||
use crate::grin_util::static_secp_instance;
|
||||
use crate::slate::{PaymentInfo, PaymentMemo, Slate};
|
||||
use crate::slate_versions::ser as dalek_ser;
|
||||
use crate::types::{Context, NodeClient, WalletBackend};
|
||||
use crate::{address, Error};
|
||||
use byteorder::{BigEndian, ByteOrder};
|
||||
use chrono::{DateTime, NaiveDateTime, Utc};
|
||||
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_util::secp::Message;
|
||||
use std::convert::TryInto;
|
||||
|
||||
/// All elements required to validate a proof within a single struct
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProofWitness {
|
||||
/// Kernel index, supplied so verifiers can look up kernel
|
||||
/// without an expensive lookup operation
|
||||
#[serde(with = "secp_ser::string_or_u64")]
|
||||
pub kernel_index: u64,
|
||||
/// Kernel commitment, supplied so prover can recompute index
|
||||
/// if required after a reorg
|
||||
#[serde(
|
||||
serialize_with = "secp_ser::as_hex",
|
||||
deserialize_with = "secp_ser::commitment_from_hex"
|
||||
)]
|
||||
pub kernel_commitment: Commitment,
|
||||
/// sender partial signature, used to recover receiver partial signature
|
||||
#[serde(with = "secp_ser::sig_serde")]
|
||||
pub sender_partial_sig: Signature,
|
||||
}
|
||||
|
||||
/// Payment proof, to be extracted from slates for
|
||||
/// signing (when wrapped as PaymentProofBin) or json export from stored tx data
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
|
||||
pub struct InvoiceProof {
|
||||
/// Proof type, 0x00 legacy (though this will use StoredProofInfo above, 1 invoice, 2 Sender nonce)
|
||||
pub proof_type: u8,
|
||||
/// amount
|
||||
#[serde(with = "secp_ser::string_or_u64")]
|
||||
pub amount: u64,
|
||||
/// receiver's public nonce from signing
|
||||
#[serde(with = "secp_ser::pubkey_serde")]
|
||||
pub receiver_public_nonce: PublicKey,
|
||||
/// receiver's public excess from signing
|
||||
#[serde(with = "secp_ser::pubkey_serde")]
|
||||
pub receiver_public_excess: PublicKey,
|
||||
/// Sender's address
|
||||
#[serde(with = "dalek_ser::dalek_pubkey_serde")]
|
||||
pub sender_address: DalekPublicKey,
|
||||
/// Timestamp provided by recipient when signing
|
||||
pub timestamp: i64,
|
||||
/// Optional payment memo
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub memo: Option<PaymentMemo>,
|
||||
/// Not serialized in binary format
|
||||
#[serde(with = "dalek_ser::option_dalek_sig_serde")]
|
||||
pub promise_signature: Option<DalekSignature>,
|
||||
/// Not serialized in binary format, just a convenient place to insert
|
||||
/// the witness kernel commitment index
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub witness_data: Option<ProofWitness>,
|
||||
}
|
||||
|
||||
struct InvoiceProofBin(InvoiceProof);
|
||||
|
||||
impl Writeable for InvoiceProofBin {
|
||||
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), grin_ser::Error> {
|
||||
writer.write_u8(1)?;
|
||||
|
||||
// Amount field is 7 bytes, throw error if value is greater
|
||||
let mut amount_bytes = [0; 8];
|
||||
BigEndian::write_u64(&mut amount_bytes, self.0.amount);
|
||||
|
||||
if amount_bytes[0] > 0 {
|
||||
return Err(grin_ser::Error::UnexpectedData {
|
||||
expected: [0u8].to_vec(),
|
||||
received: [amount_bytes[0]].to_vec(),
|
||||
});
|
||||
}
|
||||
writer.write_fixed_bytes(amount_bytes[1..].to_vec())?;
|
||||
{
|
||||
let static_secp = static_secp_instance();
|
||||
let static_secp = static_secp.lock();
|
||||
writer.write_fixed_bytes(
|
||||
self.0
|
||||
.receiver_public_nonce
|
||||
.serialize_vec(&static_secp, true),
|
||||
)?;
|
||||
writer.write_fixed_bytes(
|
||||
self.0
|
||||
.receiver_public_excess
|
||||
.serialize_vec(&static_secp, true),
|
||||
)?;
|
||||
}
|
||||
writer.write_fixed_bytes(self.0.sender_address.as_bytes())?;
|
||||
writer.write_i64(self.0.timestamp)?;
|
||||
match &self.0.memo {
|
||||
Some(s) => {
|
||||
writer.write_u8(s.memo_type)?;
|
||||
writer.write_fixed_bytes(&s.memo.to_vec())?;
|
||||
}
|
||||
None => {
|
||||
writer.write_u8(0)?;
|
||||
writer.write_fixed_bytes([0u8; 32].to_vec())?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Not strictly necessary, but useful for tests
|
||||
impl Readable for InvoiceProofBin {
|
||||
fn read<R: Reader>(reader: &mut R) -> Result<InvoiceProofBin, grin_ser::Error> {
|
||||
// first 8 bytes are proof type + 7 bytes worth of amount
|
||||
let mut amount = reader.read_u64()?;
|
||||
let proof_type: u8 = ((amount & 0xFF00_0000_0000_0000) >> 56).try_into().unwrap();
|
||||
amount &= 0x00FF_FFFF_FFFF_FFFF;
|
||||
|
||||
let receiver_public_nonce;
|
||||
let receiver_public_excess;
|
||||
{
|
||||
let static_secp = static_secp_instance();
|
||||
let static_secp = static_secp.lock();
|
||||
receiver_public_nonce =
|
||||
PublicKey::from_slice(&static_secp, &reader.read_fixed_bytes(33)?).unwrap();
|
||||
receiver_public_excess =
|
||||
PublicKey::from_slice(&static_secp, &reader.read_fixed_bytes(33)?).unwrap();
|
||||
}
|
||||
|
||||
let sender_address_vec = reader.read_fixed_bytes(32)?;
|
||||
let sender_address = DalekPublicKey::from_bytes(&sender_address_vec).unwrap();
|
||||
|
||||
let timestamp = reader.read_i64()?;
|
||||
|
||||
let memo_type = reader.read_u8()?;
|
||||
let memo = reader.read_fixed_bytes(32)?;
|
||||
let mut memo_bytes: [u8; 32] = [0u8; 32];
|
||||
memo_bytes.copy_from_slice(&memo);
|
||||
|
||||
let res = InvoiceProof {
|
||||
proof_type,
|
||||
amount,
|
||||
receiver_public_nonce,
|
||||
receiver_public_excess,
|
||||
sender_address,
|
||||
timestamp,
|
||||
memo: match memo_type {
|
||||
0 => None,
|
||||
_ => Some(PaymentMemo {
|
||||
memo_type,
|
||||
memo: memo_bytes,
|
||||
}),
|
||||
},
|
||||
promise_signature: None,
|
||||
witness_data: None,
|
||||
};
|
||||
|
||||
Ok(InvoiceProofBin(res))
|
||||
}
|
||||
}
|
||||
|
||||
impl InvoiceProof {
|
||||
/// Extracts as much data as possible from the slate to create an invoice proof
|
||||
pub fn from_slate(
|
||||
slate: &Slate,
|
||||
participant_index: usize,
|
||||
sender_address: Option<DalekPublicKey>,
|
||||
) -> Result<Self, Error> {
|
||||
// Sender address is either provided or in slate (or error)
|
||||
let sender_address = match sender_address {
|
||||
Some(a) => a,
|
||||
None => {
|
||||
if let Some(ref p) = slate.payment_proof {
|
||||
if let Some(a) = p.sender_address {
|
||||
a
|
||||
} else {
|
||||
return Err(Error::NoSenderAddressProvided);
|
||||
}
|
||||
} else {
|
||||
return Err(Error::NoSenderAddressProvided);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let timestamp = match slate.payment_proof.as_ref() {
|
||||
Some(p) => NaiveDateTime::from_timestamp_opt(p.timestamp.timestamp(), 0)
|
||||
.unwrap()
|
||||
.timestamp(),
|
||||
None => 0,
|
||||
};
|
||||
|
||||
let memo = match slate.payment_proof.as_ref() {
|
||||
Some(p) => p.memo.clone(),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let promise_signature = match slate.payment_proof.as_ref() {
|
||||
Some(p) => p.promise_signature.clone(),
|
||||
None => None,
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
proof_type: 1u8,
|
||||
amount: slate.amount,
|
||||
receiver_public_nonce: slate.participant_data[participant_index].public_nonce,
|
||||
receiver_public_excess: slate.participant_data[participant_index].public_blind_excess,
|
||||
sender_address,
|
||||
timestamp,
|
||||
memo,
|
||||
promise_signature,
|
||||
witness_data: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Sign the invoice proof, provided all fields are populated
|
||||
pub fn sign(&self, sec_key: &SecretKey) -> Result<(DalekSignature, DalekPublicKey), Error> {
|
||||
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,
|
||||
};
|
||||
let mut sig_data_bin = Vec::new();
|
||||
let _ = grin_ser::serialize_default(&mut sig_data_bin, &InvoiceProofBin(self.clone()))
|
||||
.expect("serialization failed");
|
||||
|
||||
Ok((keypair.sign(&sig_data_bin), pub_key))
|
||||
}
|
||||
|
||||
/// Verify the signature of the invoice proof
|
||||
pub fn verify_promise_signature(
|
||||
&self,
|
||||
recipient_address: &DalekPublicKey,
|
||||
) -> Result<(), Error> {
|
||||
if self.promise_signature.is_none() {
|
||||
return Err(Error::PaymentProofValidation(
|
||||
"Missing promise signature".into(),
|
||||
));
|
||||
}
|
||||
|
||||
// Rebuild message
|
||||
let mut sig_data_bin = Vec::new();
|
||||
let _ = grin_ser::serialize_default(&mut sig_data_bin, &InvoiceProofBin(self.clone()))
|
||||
.expect("serialization failed");
|
||||
|
||||
if recipient_address
|
||||
.verify(&sig_data_bin, self.promise_signature.as_ref().unwrap())
|
||||
.is_err()
|
||||
{
|
||||
return Err(Error::PaymentProof(
|
||||
"Invalid recipient signature".to_owned(),
|
||||
));
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Verify signature and proof against a given kernel message (kernel lookup is beyond the scope
|
||||
/// of this module)
|
||||
pub fn verify_witness(
|
||||
&self,
|
||||
recipient_address: &DalekPublicKey,
|
||||
excess_sig: &Signature,
|
||||
msg: &Message,
|
||||
) -> Result<(), Error> {
|
||||
if self.witness_data.is_none() {
|
||||
return Err(Error::PaymentProofValidation("Missing witness data".into()));
|
||||
}
|
||||
|
||||
self.verify_promise_signature(recipient_address)?;
|
||||
|
||||
let wd = self.witness_data.as_ref().unwrap().clone();
|
||||
{
|
||||
let static_secp = static_secp_instance();
|
||||
let static_secp = static_secp.lock();
|
||||
|
||||
let receiver_part_sig =
|
||||
aggsig::subtract_signature(&static_secp, &excess_sig, &wd.sender_partial_sig)?;
|
||||
|
||||
// Retrieve the public nonce sum from the kernel excess signature
|
||||
let mut pub_nonce_sum_bytes = [3u8; 33];
|
||||
pub_nonce_sum_bytes[1..33].copy_from_slice(&excess_sig[0..32]);
|
||||
let pub_nonce_sum = PublicKey::from_slice(&static_secp, &pub_nonce_sum_bytes)?;
|
||||
|
||||
// Retrieve the public key sum from the kernel excess
|
||||
let pub_blind_sum = wd.kernel_commitment.to_pubkey(&static_secp)?;
|
||||
|
||||
if let Err(_) = aggsig::verify_partial_sig(
|
||||
&static_secp,
|
||||
&receiver_part_sig.0,
|
||||
&pub_nonce_sum,
|
||||
&self.receiver_public_excess,
|
||||
Some(&pub_blind_sum),
|
||||
&msg,
|
||||
) {
|
||||
// Try other possibility
|
||||
if let Some(s) = receiver_part_sig.1 {
|
||||
aggsig::verify_partial_sig(
|
||||
&static_secp,
|
||||
&s,
|
||||
&pub_nonce_sum,
|
||||
&self.receiver_public_excess,
|
||||
Some(&pub_blind_sum),
|
||||
&msg,
|
||||
)?;
|
||||
} else {
|
||||
return Err(Error::PaymentProofValidation(
|
||||
"Signature subtraction failed".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl serde::Serialize for InvoiceProofBin {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds all info needed for a payment proof to a slate, complete with signed recipient data
|
||||
pub fn add_payment_proof<'a, T: ?Sized, C, K>(
|
||||
wallet: &mut T,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
slate: &mut Slate,
|
||||
context: &Context,
|
||||
proof_args: &ProofArgs,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
// TODO: Just generating invoice (type 1) for now
|
||||
let (invoice_proof, promise_signature, receiver_address) =
|
||||
generate_invoice_signature(wallet, keychain_mask, slate, context, proof_args)?;
|
||||
let timestamp = NaiveDateTime::from_timestamp_opt(Utc::now().timestamp(), 0).unwrap();
|
||||
let timestamp = DateTime::<Utc>::from_utc(timestamp, Utc);
|
||||
|
||||
let proof = PaymentInfo {
|
||||
sender_address: proof_args.sender_address.clone(),
|
||||
receiver_address,
|
||||
timestamp,
|
||||
promise_signature: Some(promise_signature),
|
||||
memo: invoice_proof.memo,
|
||||
};
|
||||
slate.payment_proof = Some(proof);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Generates a signature for proof type 'Invoice'
|
||||
fn generate_invoice_signature<'a, T: ?Sized, C, K>(
|
||||
wallet: &mut T,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
slate: &mut Slate,
|
||||
context: &Context,
|
||||
proof_args: &ProofArgs,
|
||||
) -> Result<(InvoiceProof, DalekSignature, DalekPublicKey), Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
let keychain = wallet.keychain(keychain_mask)?;
|
||||
let index = slate.find_index_matching_context(&keychain, context)?;
|
||||
let mut invoice_proof = InvoiceProof::from_slate(&slate, index, proof_args.sender_address)?;
|
||||
let derivation_index = match context.payment_proof_derivation_index {
|
||||
Some(i) => i,
|
||||
None => 0,
|
||||
};
|
||||
let parent_key_id = wallet.parent_key_id();
|
||||
let recp_key =
|
||||
address::address_from_derivation_path(&keychain, &parent_key_id, derivation_index)?;
|
||||
|
||||
invoice_proof.timestamp = NaiveDateTime::from_timestamp_opt(Utc::now().timestamp(), 0)
|
||||
.unwrap()
|
||||
.timestamp();
|
||||
let (sig, addr) = invoice_proof.sign(&recp_key)?;
|
||||
Ok((invoice_proof, sig, addr))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::slate_versions::tests::populate_test_slate;
|
||||
|
||||
#[test]
|
||||
fn ser_invoice_proof_bin() -> Result<(), Error> {
|
||||
let mut slate = populate_test_slate()?;
|
||||
slate.amount |= 0xFF00_0000_0000_0000;
|
||||
// Bin serialization doesn't include promise sig as it's used to create signature data
|
||||
slate.payment_proof.as_mut().unwrap().promise_signature = None;
|
||||
|
||||
// Should fail, amount too big
|
||||
let invoice_proof = InvoiceProof::from_slate(&slate, 1, None)?;
|
||||
let mut vec = Vec::new();
|
||||
assert!(grin_ser::serialize_default(&mut vec, &InvoiceProofBin(invoice_proof)).is_err());
|
||||
|
||||
// Should be okay now
|
||||
slate.amount = 1234;
|
||||
let invoice_proof = InvoiceProof::from_slate(&slate, 1, None)?;
|
||||
let mut vec = Vec::new();
|
||||
grin_ser::serialize_default(&mut vec, &InvoiceProofBin(invoice_proof.clone()))
|
||||
.expect("Serialization Failed");
|
||||
|
||||
let proof_deser: InvoiceProofBin = grin_ser::deserialize_default(&mut &vec[..]).unwrap();
|
||||
assert_eq!(invoice_proof, proof_deser.0);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,596 @@
|
||||
// Copyright 2022 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.
|
||||
|
||||
//! Contract coin selection functions
|
||||
|
||||
use crate::contract::types::{ContractSetupArgsAPI, OutputSelectionArgs};
|
||||
use crate::contract::utils::my_fee_contribution;
|
||||
use crate::grin_core::core::amount_to_hr_string;
|
||||
use crate::grin_keychain::{Identifier, Keychain};
|
||||
use crate::types::{NodeClient, WalletBackend};
|
||||
use crate::{Error, OutputData};
|
||||
use grin_core::core::FeeFields;
|
||||
|
||||
/// Prepares inputs & outputs that satisfy `Σmy_inputs >= Σmy_outputs + my_fee_cost` taking into account selection args
|
||||
pub fn prepare_outputs<'a, T: ?Sized, C, K>(
|
||||
w: &mut T,
|
||||
parent_key_id: &Identifier,
|
||||
current_height: u64,
|
||||
setup_args: &ContractSetupArgsAPI,
|
||||
committed_fee: Option<FeeFields>,
|
||||
) -> Result<(Vec<OutputData>, Vec<u64>, FeeFields), Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
// Find available inputs
|
||||
let mut eligible_inputs = find_eligible(w, parent_key_id, current_height)?;
|
||||
// Select which inputs to use to satisfy the equation
|
||||
compute(setup_args, committed_fee, &mut eligible_inputs)
|
||||
}
|
||||
|
||||
/// Find all inputs eligible to spend
|
||||
pub fn find_eligible<'a, T: ?Sized, C, K>(
|
||||
w: &mut T,
|
||||
parent_key_id: &Identifier,
|
||||
current_height: u64,
|
||||
) -> Result<Vec<OutputData>, Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
// Find eligible inputs in the wallet
|
||||
let eligible_inputs = w
|
||||
.iter()
|
||||
.filter(|out| out.root_key_id == *parent_key_id && out.eligible_to_spend(current_height, 1))
|
||||
.collect::<Vec<OutputData>>();
|
||||
Ok(eligible_inputs)
|
||||
}
|
||||
// Given a list of inputs, an optional committed fee and setup args, compute which inputs to use, what amount outputs to make and fee cost
|
||||
pub fn compute(
|
||||
setup_args: &ContractSetupArgsAPI,
|
||||
committed_fee: Option<FeeFields>,
|
||||
inputs: &mut Vec<OutputData>,
|
||||
) -> Result<(Vec<OutputData>, Vec<u64>, FeeFields), Error>
|
||||
where
|
||||
{
|
||||
let (inputs, fee) = select_inputs(setup_args, committed_fee, inputs)?;
|
||||
let output_amounts = build_output_amount_list(
|
||||
inputs.clone().iter().map(|out| out.value).sum::<u64>(),
|
||||
fee.fee(),
|
||||
setup_args,
|
||||
);
|
||||
Ok((inputs, output_amounts, fee))
|
||||
}
|
||||
|
||||
// Given a list of inputs, an optional committed fee and setup args, compute which inputs to use
|
||||
fn select_inputs(
|
||||
setup_args: &ContractSetupArgsAPI,
|
||||
committed_fee: Option<FeeFields>,
|
||||
inputs: &mut Vec<OutputData>,
|
||||
) -> Result<(Vec<OutputData>, FeeFields), Error>
|
||||
where
|
||||
{
|
||||
// We use 'lhs' and 'rhs' to denote the amounts on the left/right-hand side of the equation.
|
||||
// To simulate receive/payment value we:
|
||||
// - add positive net_change to the 'lhs' for the receiver (to simulate sender's input)
|
||||
// - add positive net_change to the 'rhs' for the sender (to simulate receiver's output)
|
||||
// For either party, the following MUST hold for the inputs the function returns:
|
||||
// Σmy_inputs >= Σmy_outputs + my_fee_cost
|
||||
// Each party later balances the equation by adding an additional output (change output or receiver output)
|
||||
let net_change = setup_args.net_change.unwrap();
|
||||
let custom_outputs_amount_sum = setup_args.selection_args.sum_output_amounts();
|
||||
let pay_amount = if net_change < 0 {
|
||||
net_change.abs() as u64
|
||||
} else {
|
||||
0
|
||||
};
|
||||
// Add the amount we pay and the custom outputs to rhs of the equation
|
||||
let rhs = pay_amount + custom_outputs_amount_sum;
|
||||
let required_inputs = setup_args.selection_args.required_inputs();
|
||||
let is_payjoin = setup_args.selection_args.is_payjoin();
|
||||
let is_self_spend = setup_args.num_participants == 1;
|
||||
debug!(
|
||||
"contract::selection::selecting inputs: num_participants: {}, min_input_amount: {}, is_payjoin: {}",
|
||||
setup_args.num_participants, rhs, is_payjoin
|
||||
);
|
||||
// We don't try to contribute an input only in the case where we have multiple participants
|
||||
// where we are on the receiving end and we don't want to do a payjoin
|
||||
if !is_self_spend && (pay_amount == 0 && !is_payjoin) {
|
||||
return Ok((
|
||||
vec![],
|
||||
my_fee_contribution(
|
||||
0,
|
||||
setup_args.selection_args.num_custom_outputs() + 1,
|
||||
1,
|
||||
setup_args.num_participants,
|
||||
)?,
|
||||
));
|
||||
}
|
||||
// NOTE: that these are inputs that MUST be selected. We should lock the inputs if they're
|
||||
// required to minimize any potential race conditions.
|
||||
let must_use_list = required_inputs.unwrap_or(vec![]);
|
||||
if must_use_list.len() > 0 {
|
||||
// Sort the inputs first by the ones listed in the use_inputs and then by value
|
||||
inputs.sort_by_key(|out| {
|
||||
(
|
||||
// We have to negate the boolean to prioritize truthy values because
|
||||
// false is 0 and hence would be sorted before truthy entries
|
||||
!(out.commit.is_some()
|
||||
&& must_use_list.contains(&&out.commit.as_ref().unwrap()[..])),
|
||||
out.value,
|
||||
)
|
||||
});
|
||||
} else {
|
||||
// Sort the inputs only by value
|
||||
inputs.sort_by_key(|out| out.value);
|
||||
}
|
||||
|
||||
// NOTE: Since we sort by value increasingly, if we hold any 0-value inputs, they will all be used if we're the sender
|
||||
// or a single one if we're the receiver doing a payjoin.
|
||||
// If we are the receiver, we pretend we have a virtual input from the sender (for which we don't pay the fees) so we can easily
|
||||
// test that lhs >= rhs and see if we will be able to satisfy equation. We simulate this by starting with lhs = net_change.
|
||||
let mut lhs = 0;
|
||||
if net_change > 0 {
|
||||
lhs = net_change as u64; // TODO: check bounds
|
||||
}
|
||||
// We want to count how many inputs we've picked _so far_. This is used to prevent picking
|
||||
// all 0*H +r*G outputs when we call with min_input_amount=0 and want just a payjoin.
|
||||
let mut n_inputs = 0;
|
||||
let mut must_use_list_cnt: u32 = 0;
|
||||
let my_num_outputs = setup_args.selection_args.num_custom_outputs() + 1;
|
||||
// If we have already committed to a fee (context.fee) then set this as our "minimum" fee. The reason we have to
|
||||
// do this is to avoid solving the equation for less than the committed fee. We have to guarantee the inputs we take
|
||||
// are enough to cover the committed fee. At the end of selection, we check that the fees for the selection were not
|
||||
// higher than the fee value we committed to.
|
||||
let mut my_fee = if committed_fee.is_some() {
|
||||
committed_fee.unwrap()
|
||||
} else {
|
||||
// We start with a fee of 1 output and a shared kernel which is minimum for both parties
|
||||
my_fee_contribution(0, 1, 1, setup_args.num_participants).unwrap()
|
||||
// FeeFields::zero()
|
||||
};
|
||||
|
||||
// NOTE: This always takes at least one input if it is available. We take the inputs we must take and then we take
|
||||
// inputs until we fulfill Σmy_inputs >= Σmy_outputs + my_fee_cost
|
||||
let selected_inputs = inputs
|
||||
.iter()
|
||||
.take_while(|out| {
|
||||
// Take the commitment if it is listed as one of those we MUST take
|
||||
let must_take =
|
||||
out.commit.is_some() && must_use_list.contains(&&out.commit.as_ref().unwrap()[..]);
|
||||
// Compute the fee without this input
|
||||
let fee_without =
|
||||
my_fee_contribution(n_inputs, my_num_outputs, 1, setup_args.num_participants)
|
||||
.unwrap();
|
||||
// Compute the total fee cost if we took this input
|
||||
let mut fee_with =
|
||||
my_fee_contribution(n_inputs + 1, my_num_outputs, 1, setup_args.num_participants)
|
||||
.unwrap();
|
||||
// If the current fee is lower than the committed fee (my_fee) then set it to committed fee
|
||||
if my_fee.fee() > fee_with.fee() {
|
||||
fee_with = my_fee;
|
||||
}
|
||||
// If we don't have a "must take" input, have contributed an input and have enough to balance the equation, we can stop
|
||||
let can_finish = lhs >= (rhs + fee_without.fee()) && n_inputs > 0 && !must_take;
|
||||
if can_finish {
|
||||
return false;
|
||||
}
|
||||
// Take the commitment if `lhs < rhs+fees_with` (or if we have not yet taken an input - payjoins)
|
||||
let should_take = lhs < (rhs + fee_with.fee()) || n_inputs == 0;
|
||||
let res = must_take || should_take;
|
||||
if res {
|
||||
lhs += out.value;
|
||||
n_inputs += 1;
|
||||
// Update the fee cost if we decided to take the input
|
||||
my_fee = fee_with;
|
||||
if must_take {
|
||||
must_use_list_cnt += 1;
|
||||
}
|
||||
}
|
||||
debug!(
|
||||
"contract::selection::select_inputs => out_value:{}, new my_inputs_sum:{}",
|
||||
out.value, lhs
|
||||
);
|
||||
res
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<OutputData>>();
|
||||
|
||||
// Return an error if the fee computed is larger than the committed fee
|
||||
if committed_fee.is_some() && my_fee.fee() > committed_fee.unwrap().fee() {
|
||||
// TODO: Return a specific Fee estimation error and suggest the user to cancel the transaction
|
||||
let msg = format!(
|
||||
"Fee computed ({}) is larger than the committed fee ({})",
|
||||
my_fee.fee(),
|
||||
committed_fee.unwrap().fee()
|
||||
);
|
||||
return Err(Error::GenericError(msg.into()).into());
|
||||
}
|
||||
|
||||
// Check that the inputs we picked are enough to cover all our output amounts and fees
|
||||
// asserts that Σmy_inputs >= Σmy_outputs + my_fee_cost
|
||||
if lhs < rhs + my_fee.fee() {
|
||||
let total = inputs.iter().fold(0, |acc, x| acc + x.value);
|
||||
debug!("Not enough funds. Total funds eligible to spend: {}, needed: {}. Fee cost for this transaction: {}", total, rhs+my_fee.fee(), my_fee.fee());
|
||||
return Err(Error::NotEnoughFunds {
|
||||
available: total,
|
||||
available_disp: amount_to_hr_string(total, false),
|
||||
needed: rhs + my_fee.fee(),
|
||||
needed_disp: amount_to_hr_string(rhs + my_fee.fee(), false),
|
||||
}
|
||||
.into());
|
||||
// return Err(ErrorKind::GenericError(msg.into()).into());
|
||||
}
|
||||
|
||||
// Assert that all the use_inputs have been selected
|
||||
if must_use_list.len() != must_use_list_cnt as usize {
|
||||
let msg = format!(
|
||||
"We have not found all the inputs that have been requested. {}, found only: {}",
|
||||
setup_args.selection_args.use_inputs.as_ref().unwrap(),
|
||||
must_use_list_cnt
|
||||
);
|
||||
return Err(Error::GenericError(msg.into()).into());
|
||||
}
|
||||
|
||||
debug!(
|
||||
"contract::selection::select_inputs => selected_inputs: {:#?}",
|
||||
selected_inputs
|
||||
);
|
||||
// We are returning a set of inputs for which `Σmy_inputs >= Σmy_outputs + my_fee_cost` holds
|
||||
Ok((selected_inputs, my_fee))
|
||||
}
|
||||
|
||||
fn build_output_amount_list(
|
||||
my_input_sum: u64,
|
||||
my_fee_cost: u64,
|
||||
setup_args: &ContractSetupArgsAPI,
|
||||
) -> Vec<u64> {
|
||||
let expected_net_change = setup_args.net_change.unwrap();
|
||||
let mut my_output_amounts = setup_args.selection_args.output_amounts();
|
||||
let custom_outputs_sum = my_output_amounts.iter().sum::<u64>();
|
||||
// We know that `Σmy_inputs >= Σmy_outputs + my_fee_cost` holds so we balance the equation by adding
|
||||
// an additional output holding the missing amount (change output or receiver output)
|
||||
// TODO: check bounds when casting.
|
||||
let my_change_output_amount =
|
||||
(my_input_sum - custom_outputs_sum) as i64 + expected_net_change - my_fee_cost as i64;
|
||||
// TODO: Check if it's even possible for change output to be negative (it shouldn't be if the equation is correct)
|
||||
if my_change_output_amount < 0 {
|
||||
panic!(
|
||||
"contract::selection::build_output_amount_list => ERROR: This should never happen!!! Values: my_input_sum: {}, expected_net_change: {}, my_fee_cost: {}",
|
||||
my_input_sum as i64, expected_net_change, my_fee_cost as i64
|
||||
);
|
||||
}
|
||||
// Add our change/receiver output (which can be a zero-value output) to the list of outputs
|
||||
my_output_amounts.push(my_change_output_amount as u64);
|
||||
debug!(
|
||||
"contract::selection::build_output_amount_list => inputs sum: {}, my_output_amounts:{:#?}",
|
||||
my_input_sum, my_output_amounts
|
||||
);
|
||||
my_output_amounts
|
||||
}
|
||||
|
||||
/// Compares the output selection args provided at call with those from Context and checks whether they conflict
|
||||
pub fn verify_selection_consistency(
|
||||
ctx_args: &OutputSelectionArgs,
|
||||
cur_args: &OutputSelectionArgs,
|
||||
) -> Result<(), Error> {
|
||||
// We can't define a selection strategy if we've already done the setup phase. We only allow to pass either the
|
||||
// default or exactly the same strategy we defined when doing the setup phase.
|
||||
// TODO: Test that this works. Perhaps we'd have to define how to compare the two?
|
||||
if cur_args != ctx_args && cur_args != &OutputSelectionArgs::default() {
|
||||
panic!("Can't define selection args now because we've already done the setup phase. ctx_selection_args:{:#?}, cur_selection_args:{:#?}", ctx_args, cur_args);
|
||||
}
|
||||
// NOTE: The logic above isn't perfect. This is because the user could define arguments that are the default. In this case
|
||||
// we'd simply silently use the arguments provided in the setup phase. This could be confusing for the user.
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Tests
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
use super::*;
|
||||
use crate::grin_keychain::{Identifier, IDENTIFIER_SIZE};
|
||||
use crate::OutputStatus;
|
||||
|
||||
fn _create_output_data_for(amounts: Vec<u64>) -> Vec<OutputData> {
|
||||
let mut rv: Vec<OutputData> = vec![];
|
||||
for (idx, amount) in amounts.iter().enumerate() {
|
||||
let identifier = [0u8; IDENTIFIER_SIZE];
|
||||
let key_id = Identifier::from_bytes(&identifier);
|
||||
rv.push(OutputData {
|
||||
// The identifiers here don't make sense, but they're not needed for testing
|
||||
root_key_id: key_id.clone(),
|
||||
key_id: key_id.clone(),
|
||||
n_child: key_id.clone().to_path().last_path_index(),
|
||||
mmr_index: None,
|
||||
commit: Some(format!("{}{}", "abc", idx.to_string())),
|
||||
value: *amount,
|
||||
status: OutputStatus::Unspent,
|
||||
height: 1,
|
||||
lock_height: 0,
|
||||
is_coinbase: false,
|
||||
tx_log_entry: None,
|
||||
});
|
||||
}
|
||||
rv
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sender_no_inputs() {
|
||||
// net_change=-1, no inputs, no fee committed => NotEnoughFunds
|
||||
let setup_args = ContractSetupArgsAPI {
|
||||
net_change: Some(-1_000_000_000),
|
||||
..Default::default()
|
||||
};
|
||||
let expected = Error::NotEnoughFunds {
|
||||
available: 0,
|
||||
available_disp: amount_to_hr_string(0, false),
|
||||
needed: 1_000_000_000 + my_fee_contribution(0, 1, 1, 2).unwrap().fee(),
|
||||
needed_disp: amount_to_hr_string(
|
||||
1_000_000_000 + my_fee_contribution(0, 1, 1, 2).unwrap().fee(),
|
||||
false,
|
||||
),
|
||||
};
|
||||
let result = compute(&setup_args, None, &mut vec![]);
|
||||
assert_eq!(result.err().unwrap(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sender_not_enough_funds_for_fee() {
|
||||
// net_change=-3, inputs=[2, 1], no fee committed => NotEnoughFunds because we can't pay for fees
|
||||
let setup_args = ContractSetupArgsAPI {
|
||||
net_change: Some(-3_000_000_000),
|
||||
..Default::default()
|
||||
};
|
||||
let expected = Error::NotEnoughFunds {
|
||||
available: 3_000_000_000,
|
||||
available_disp: amount_to_hr_string(3_000_000_000, false),
|
||||
needed: 3_000_000_000 + my_fee_contribution(2, 1, 1, 2).unwrap().fee(),
|
||||
needed_disp: amount_to_hr_string(
|
||||
3_000_000_000 + my_fee_contribution(2, 1, 1, 2).unwrap().fee(),
|
||||
false,
|
||||
),
|
||||
};
|
||||
let mut inputs = _create_output_data_for(vec![2_000_000_000, 1_000_000_000]);
|
||||
let result = compute(&setup_args, None, &mut inputs);
|
||||
assert_eq!(result.err().unwrap(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sender_happy_path() {
|
||||
// net_change=-3, inputs=[3, 2, 1, 2], no fee committed => Ok([1, 2, 2], fees)
|
||||
let setup_args = ContractSetupArgsAPI {
|
||||
net_change: Some(-3_000_000_000),
|
||||
..Default::default()
|
||||
};
|
||||
let inputs = _create_output_data_for(vec![
|
||||
3_000_000_000,
|
||||
2_000_000_000,
|
||||
1_000_000_000,
|
||||
2_000_000_000,
|
||||
]);
|
||||
// We expect 3 inputs with amounts 1, 2, 2
|
||||
let expected_inputs = vec![&inputs[2], &inputs[1], &inputs[3]];
|
||||
let expected_fee = my_fee_contribution(3, 1, 1, 2).unwrap();
|
||||
let expected_output_amounts = vec![
|
||||
// we expect a single output with change holding 5 - 3 - fees
|
||||
(5_000_000_000 as i64 + (setup_args.net_change.unwrap())) as u64 - expected_fee.fee(),
|
||||
];
|
||||
let result = compute(&setup_args, None, &mut inputs.clone()).unwrap();
|
||||
|
||||
let result_ref = (
|
||||
result.0.iter().collect::<Vec<&OutputData>>(),
|
||||
result.1,
|
||||
result.2,
|
||||
);
|
||||
assert_eq!(
|
||||
result_ref,
|
||||
(expected_inputs, expected_output_amounts, expected_fee)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sender_exact() {
|
||||
// net_change=-3, inputs=[3, my_fees(2, 1)], no fee committed => Ok([3, my_fees(2, 1)], fees)
|
||||
let setup_args = ContractSetupArgsAPI {
|
||||
net_change: Some(-3_000_000_000),
|
||||
..Default::default()
|
||||
};
|
||||
let inputs = _create_output_data_for(vec![
|
||||
my_fee_contribution(2, 1, 1, 2).unwrap().fee(),
|
||||
3_000_000_000,
|
||||
]);
|
||||
let expected_inputs = inputs.clone(); // we expect both inputs in the same order
|
||||
let expected_fee = my_fee_contribution(2, 1, 1, 2).unwrap();
|
||||
let expected_output_amounts = vec![0]; // we expect a change output of 0-value
|
||||
let result = compute(&setup_args, None, &mut inputs.clone()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
(expected_inputs, expected_output_amounts, expected_fee)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn receiver_payjoin_exact() {
|
||||
// net_change=-my_fees(1, 1), inputs=[my_fees(1, 0)], no fee committed => Ok([3, my_fees(2, 1)], fees)
|
||||
let setup_args = ContractSetupArgsAPI {
|
||||
// we expect to receive exactly our fee contribution my_fees(1, 1)
|
||||
net_change: Some(my_fee_contribution(1, 1, 1, 2).unwrap().fee() as i64),
|
||||
..Default::default()
|
||||
};
|
||||
let inputs = _create_output_data_for(vec![0, 1_000_000_000]); // we have a 0-value and 1 grin input
|
||||
let expected_inputs = vec![&inputs[0]]; // we expect to use the 0-value input
|
||||
let expected_fee = my_fee_contribution(1, 1, 1, 2).unwrap();
|
||||
let expected_output_amounts = vec![0]; // we expect a change output of 0-value
|
||||
let result = compute(&setup_args, None, &mut inputs.clone()).unwrap();
|
||||
|
||||
let result_ref = (
|
||||
result.0.iter().collect::<Vec<&OutputData>>(),
|
||||
result.1,
|
||||
result.2,
|
||||
);
|
||||
assert_eq!(
|
||||
result_ref,
|
||||
(expected_inputs, expected_output_amounts, expected_fee)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn receiver_no_payjoin() {
|
||||
let setup_args = ContractSetupArgsAPI {
|
||||
// we expect to receive exactly our fee contribution my_fees(1, 1)
|
||||
net_change: Some(3_000_000_000),
|
||||
selection_args: OutputSelectionArgs {
|
||||
use_inputs: None,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let inputs = _create_output_data_for(vec![1_000_000_000]);
|
||||
let expected_inputs = vec![];
|
||||
let expected_fee = my_fee_contribution(0, 1, 1, 2).unwrap();
|
||||
let expected_output_amounts = vec![
|
||||
// we expect a single output with change holding 3 - fees
|
||||
(setup_args.net_change.unwrap() as u64) - expected_fee.fee(),
|
||||
];
|
||||
let result = compute(&setup_args, None, &mut inputs.clone()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
(expected_inputs, expected_output_amounts, expected_fee)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sender_use_inputs_ok() {
|
||||
let setup_args = ContractSetupArgsAPI {
|
||||
// we expect to receive exactly our fee contribution my_fees(1, 1)
|
||||
net_change: Some(-2_000_000_000),
|
||||
selection_args: OutputSelectionArgs {
|
||||
use_inputs: Some(String::from("abc0,abc2,abc3")),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let inputs = _create_output_data_for(vec![
|
||||
1_000_000_000, // abc0
|
||||
2_000_000_000,
|
||||
3_000_000_000, // abc2
|
||||
4_000_000_000, // abc3
|
||||
]);
|
||||
let expected_inputs = vec![&inputs[0], &inputs[2], &inputs[3]];
|
||||
let expected_fee = my_fee_contribution(3, 1, 1, 2).unwrap();
|
||||
let expected_output_amounts = vec![
|
||||
// we expect a single output with change holding 3 - fees
|
||||
(8_000_000_000 as i64 + setup_args.net_change.unwrap()) as u64 - expected_fee.fee(),
|
||||
];
|
||||
let result = compute(&setup_args, None, &mut inputs.clone()).unwrap();
|
||||
|
||||
let result_ref = (
|
||||
result.0.iter().collect::<Vec<&OutputData>>(),
|
||||
result.1,
|
||||
result.2,
|
||||
);
|
||||
assert_eq!(
|
||||
result_ref,
|
||||
(expected_inputs, expected_output_amounts, expected_fee)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sender_use_inputs_happy_err() {
|
||||
let setup_args = ContractSetupArgsAPI {
|
||||
net_change: Some(-2_000_000_000),
|
||||
selection_args: OutputSelectionArgs {
|
||||
// there is no abc5 input
|
||||
use_inputs: Some(String::from("abc0,abc2,abc5")),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let inputs = _create_output_data_for(vec![
|
||||
1_000_000_000, // abc0
|
||||
2_000_000_000,
|
||||
3_000_000_000, // abc2
|
||||
4_000_000_000,
|
||||
]);
|
||||
let msg = format!(
|
||||
"We have not found all the inputs that have been requested. abc0,abc2,abc5, found only: 2"
|
||||
);
|
||||
let expected_err = Error::GenericError(msg.into()).into();
|
||||
let result = compute(&setup_args, None, &mut inputs.clone());
|
||||
|
||||
assert_eq!(result.err().unwrap(), expected_err);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sender_make_outputs_ok() {
|
||||
let setup_args = ContractSetupArgsAPI {
|
||||
net_change: Some(-2_000_000_000),
|
||||
selection_args: OutputSelectionArgs {
|
||||
// there is no abc5 input
|
||||
make_outputs: Some(String::from("1,3")),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let inputs = _create_output_data_for(vec![
|
||||
1_000_000_000,
|
||||
2_000_000_000,
|
||||
3_000_000_000,
|
||||
4_000_000_000,
|
||||
]);
|
||||
// we expect all to be used (2+1+3+fees)
|
||||
let expected_inputs = inputs.clone();
|
||||
let expected_fee = my_fee_contribution(4, 3, 1, 2).unwrap();
|
||||
let expected_output_amounts = vec![
|
||||
1_000_000_000u64,
|
||||
3_000_000_000u64,
|
||||
// change output
|
||||
((10_000_000_000u64 - 4_000_000_000u64) as i64 + setup_args.net_change.unwrap()) as u64
|
||||
- expected_fee.fee(),
|
||||
];
|
||||
let result = compute(&setup_args, None, &mut inputs.clone()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
(expected_inputs, expected_output_amounts, expected_fee)
|
||||
);
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
Tests to add:
|
||||
- compute_receiver_invariant - test that receiving_amount - my_fees >= 0 (to prevent going into negative accidentally)
|
||||
- compute_sender_invariant - test that -send_amount - my_fees < 0 (do you need this one and is it correct?)
|
||||
- compute_receiver_payjoin_negative_fee - could the receiver receive a negative amount through fees? but the thing
|
||||
would go through because they made a payjoin so they could pay for the fees?
|
||||
- compute_receiver_omit_payjoin - we can't contribute an input, but have enough for other fees
|
||||
- compute_make_outputs_fee_err - fail due to not enough funds for fees
|
||||
- compute_make_outputs_sum_err - is this even possible?
|
||||
- compute_zero_value_outputs_sender - sender uses all 0-value outputs when sending
|
||||
- compute_zero_value_inputs_receiver - receiver uses 0-value inputs in payjoin
|
||||
- test_fee_committed_err - we have already committed to a certain fee which we no longer satisfy
|
||||
- think if we should have sender/receiver separate testing
|
||||
- sender_use_all_features
|
||||
- coinbase output cases
|
||||
- validate --make-outputs has all positive u64 numbers
|
||||
|
||||
*/
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
// Copyright 2022 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.
|
||||
|
||||
//! Contract functions on the Slate
|
||||
|
||||
use crate::grin_core::libtx::build;
|
||||
use crate::grin_core::libtx::proof::ProofBuilder;
|
||||
use crate::grin_keychain::Keychain;
|
||||
use crate::grin_util::secp::key::SecretKey;
|
||||
use crate::slate::{Slate, SlateState};
|
||||
use crate::types::{Context, NodeClient, WalletBackend};
|
||||
use crate::Error;
|
||||
|
||||
use super::types::ProofArgs;
|
||||
use crate::contract::proofs::InvoiceProof;
|
||||
use ed25519_dalek::PublicKey as DalekPublicKey;
|
||||
|
||||
/// TODO: Removed for now, consider secp error in sign function
|
||||
/// The secret key we replace the actual key with after we have signed with the Context keys. This is
|
||||
/// to prevent possibility of signing with the same key twice.
|
||||
/// pub const SEC_KEY_FAKE: [u8; 32] = [0; 32];
|
||||
|
||||
/// Add payment proof data to slate, noop for sender
|
||||
pub fn add_payment_proof<'a, T: ?Sized, C, K>(
|
||||
w: &mut T,
|
||||
slate: &mut Slate,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
context: &Context,
|
||||
net_change: &Option<i64>,
|
||||
proof_args: &ProofArgs,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
// TODO: Implement. Consider adding this function to the Slate itself so they can easily be versioned
|
||||
// e.g. slate.add_payment_proof_data()
|
||||
debug!("contract::slate::add_payment_proof => called");
|
||||
// If we're a recipient, generate proof unless explicity told not to
|
||||
if let Some(ref c) = net_change {
|
||||
if *c > 0 && !proof_args.suppress_proof && slate.payment_proof.is_none() {
|
||||
super::proofs::add_payment_proof(w, keychain_mask, slate, &context, proof_args)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Verify payment proof signature
|
||||
pub fn verify_payment_proof(
|
||||
slate: &Slate,
|
||||
net_change: i64,
|
||||
recipient_address: &DalekPublicKey,
|
||||
) -> Result<(), Error> {
|
||||
// TODO: Implement. Consider adding this function to the Slate itself so they can easily be versioned
|
||||
// e.g. slate.verify_payment_proof_sig()
|
||||
debug!("contract::slate::verify_payment_proof => called");
|
||||
if net_change > 0 && slate.payment_proof.is_some() {
|
||||
let invoice_proof = InvoiceProof::from_slate(&slate, 1, None)?;
|
||||
invoice_proof.verify_promise_signature(&recipient_address)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds inputs and outputs to slate
|
||||
pub fn add_outputs<'a, T: ?Sized, C, K>(
|
||||
w: &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,
|
||||
{
|
||||
add_inputs_to_slate(w, keychain_mask, slate, context)?;
|
||||
add_outputs_to_slate(w, keychain_mask, slate, context)?;
|
||||
// Adjust the offset for the added input and outputs
|
||||
let keychain = &w.keychain(keychain_mask)?;
|
||||
slate.adjust_offset(keychain, &context)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Contribute inputs to slate
|
||||
fn add_inputs_to_slate<'a, T: ?Sized, C, K>(
|
||||
w: &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,
|
||||
{
|
||||
debug!("contract::slate::add_inputs_to_slate => adding inputs to slate");
|
||||
let keychain = w.keychain(keychain_mask)?;
|
||||
let batch = w.batch(keychain_mask)?;
|
||||
for (key_id, mmr_index, _) in context.get_inputs() {
|
||||
// We have no information if the input is a coinbase or not, so we fetch the data from DB
|
||||
let coin = batch.get(&key_id, &mmr_index).unwrap();
|
||||
if coin.is_coinbase {
|
||||
slate.add_transaction_elements(
|
||||
&keychain,
|
||||
&ProofBuilder::new(&keychain),
|
||||
vec![build::coinbase_input(coin.value, coin.key_id.clone())],
|
||||
)?;
|
||||
debug!(
|
||||
"contract::slate::add_inputs_to_slate => added coinbase input id: {}, value: {}",
|
||||
coin.key_id.clone(),
|
||||
coin.value
|
||||
);
|
||||
} else {
|
||||
slate.add_transaction_elements(
|
||||
&keychain,
|
||||
&ProofBuilder::new(&keychain),
|
||||
vec![build::input(coin.value, coin.key_id.clone())],
|
||||
)?;
|
||||
debug!(
|
||||
"contract::slate::add_inputs_to_slate => added regular input id: {}, value: {}",
|
||||
coin.key_id.clone(),
|
||||
coin.value
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Contribute outputs to slate
|
||||
fn add_outputs_to_slate<'a, T: ?Sized, C, K>(
|
||||
w: &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,
|
||||
{
|
||||
debug!("contract::slate::add_outputs_to_slate => start");
|
||||
let keychain = w.keychain(keychain_mask)?;
|
||||
// Iterate over outputs in the Context and add the same output to the slate
|
||||
for (key_id, _, amount) in context.get_outputs() {
|
||||
slate.add_transaction_elements(
|
||||
&keychain,
|
||||
&ProofBuilder::new(&keychain),
|
||||
vec![build::output(amount, key_id.clone())],
|
||||
)?;
|
||||
debug!(
|
||||
"contract::slate::add_outputs_to_slate => added output to slate. Output id: {}, amount: {}",
|
||||
key_id.clone(),
|
||||
amount
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Transition the slate state to the next one
|
||||
pub fn transition_state(slate: &mut Slate) -> Result<(), Error> {
|
||||
// We don't really use these states right now apart from leaving it to derive expected net_change.
|
||||
// This suggests these can't be used for manipulation. It doesn't hurt to think a bit more if that's the case.
|
||||
let new_state = match slate.state {
|
||||
SlateState::Invoice1 => SlateState::Invoice2,
|
||||
SlateState::Invoice2 => SlateState::Invoice3,
|
||||
SlateState::Standard1 => SlateState::Standard2,
|
||||
SlateState::Standard2 => SlateState::Standard3,
|
||||
_ => {
|
||||
debug!("Slate.state: {}", slate.state);
|
||||
SlateState::Standard3
|
||||
}
|
||||
};
|
||||
slate.state = new_state;
|
||||
// NOTE: It's possible to never reach the step3. A self-spend has only 2 steps: new -> sign.
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add partial signature to the slate.
|
||||
// TODO: Should be a sign & forget pubkey+nonce implementation.
|
||||
pub fn sign<'a, T: ?Sized, C, K>(
|
||||
w: &mut T,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
slate: &mut Slate,
|
||||
context: &mut Context,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
debug!("contract::slate::sign => called");
|
||||
let keychain = w.keychain(keychain_mask)?;
|
||||
slate.fill_round_2(&keychain, &context.sec_key, &context.sec_nonce)?;
|
||||
debug!(
|
||||
"contract::sign => signed for slate fees: {}",
|
||||
slate.fee_fields
|
||||
);
|
||||
debug!("contract::slate::sign => done");
|
||||
|
||||
// TODO: This produces a secp error, probably need a valid key. Verify that this is what we want to do.
|
||||
// let fake_key = SecretKey::from_slice(keychain.secp(), &SEC_KEY_FAKE)?;
|
||||
// context.sec_key = fake_key.clone();
|
||||
// context.sec_nonce = fake_key.clone();
|
||||
// context.initial_sec_key = fake_key.clone();
|
||||
// context.initial_sec_nonce = fake_key.clone();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// We can finalize if all partial sigs are present
|
||||
pub fn can_finalize(slate: &Slate) -> bool {
|
||||
let res = slate
|
||||
.participant_data
|
||||
.clone()
|
||||
.into_iter()
|
||||
.filter(|v| !v.is_complete())
|
||||
.count();
|
||||
|
||||
// We can finalize if the number of partial sigs is the same as the number of participants
|
||||
res == 0 && slate.participant_data.len() == slate.num_participants as usize
|
||||
}
|
||||
|
||||
/// Finalize slate
|
||||
pub fn finalize<'a, T: ?Sized, C, K>(
|
||||
w: &mut T,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
slate: &mut Slate,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
debug!("contract::slate::finalize => called");
|
||||
// Final transaction can be built by anyone at this stage
|
||||
trace!("Slate to finalize is: {}", slate);
|
||||
// At this point, everyone adjusted their offset, so we update the offset on the tx
|
||||
slate.tx_or_err_mut()?.offset = slate.offset.clone();
|
||||
slate.finalize(&w.keychain(keychain_mask)?)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Perform 'setup' step for a contract. This adds our public key and nonce to the slate
|
||||
/// The operation should be idempotent.
|
||||
pub fn add_keys<K>(slate: &mut Slate, keychain: &K, context: &mut Context) -> Result<(), Error>
|
||||
where
|
||||
K: Keychain,
|
||||
{
|
||||
debug!("contract::slate::add_keys => called");
|
||||
// TODO: Is this safe from manipulation?
|
||||
slate.add_participant_info(keychain, context, None)
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
// Copyright 2022 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 a contract
|
||||
|
||||
use crate::grin_core::consensus;
|
||||
use crate::slate_versions::ser as dalek_ser;
|
||||
use ed25519_dalek::PublicKey as DalekPublicKey;
|
||||
|
||||
/// Output selection args
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
||||
pub struct OutputSelectionArgs {
|
||||
/// Constraint on how many confirmations used inputs must have
|
||||
pub min_input_confirmation: u64,
|
||||
/// Which inputs we want to use - default to payjoin if available with Some("any")
|
||||
pub use_inputs: Option<String>,
|
||||
/// Change output specification (comma separated amounts which don't include fee subtraction)
|
||||
/// e.g. "3,1,4,0,0" describes 5 outputs two of which hold 0 value
|
||||
pub make_outputs: Option<String>,
|
||||
}
|
||||
|
||||
impl OutputSelectionArgs {
|
||||
/// We try to make a payjoin if use_inputs has a value (either commitments or Some("any"))
|
||||
pub fn is_payjoin(&self) -> bool {
|
||||
self.use_inputs.is_some()
|
||||
}
|
||||
/// Return a list of commitments we must use
|
||||
pub fn required_inputs(&self) -> Option<Vec<&str>> {
|
||||
if self.use_inputs.is_some() {
|
||||
Some(
|
||||
self.use_inputs.as_ref().unwrap()[..]
|
||||
.split(",")
|
||||
.filter(|x| *x != "any")
|
||||
.collect(),
|
||||
)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
/// Returns the outputs we have to create
|
||||
pub fn output_amounts(&self) -> Vec<u64> {
|
||||
if self.make_outputs.is_some() {
|
||||
let output_amounts: Vec<u64> = self.make_outputs.as_ref().unwrap()[..]
|
||||
.split(",")
|
||||
// TODO: move consensus code outside of here. Consider turning make_outputs to Vec<u64>
|
||||
.map(|amt| (amt.parse::<f64>().unwrap() * consensus::GRIN_BASE as f64) as u64)
|
||||
.collect();
|
||||
output_amounts
|
||||
} else {
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
/// Returns the sum of our output amounts
|
||||
pub fn sum_output_amounts(&self) -> u64 {
|
||||
self.output_amounts().iter().sum()
|
||||
}
|
||||
/// Returns the number of custom outputs
|
||||
pub fn num_custom_outputs(&self) -> usize {
|
||||
self.output_amounts().len()
|
||||
}
|
||||
|
||||
// TODO: make sure to validate this: if custom outputs are specified, it has to be a payjoin.
|
||||
}
|
||||
|
||||
impl Default for OutputSelectionArgs {
|
||||
fn default() -> OutputSelectionArgs {
|
||||
OutputSelectionArgs {
|
||||
min_input_confirmation: 10,
|
||||
use_inputs: Some(String::from("any")),
|
||||
make_outputs: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Types of proof that can be generated
|
||||
/// as per https://github.com/tromp/grin-rfcs/blob/early-payment-proofs/text/0000-early-payment-proofs.md
|
||||
/// TODO: Update when RFC is merged
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize, Debug)]
|
||||
pub enum ProofType {
|
||||
/// Legacy (0x00)
|
||||
Legacy,
|
||||
/// Invoice (0x01, Default)
|
||||
Invoice,
|
||||
/// Sender Nonce (0x02)
|
||||
SenderNonce,
|
||||
}
|
||||
|
||||
/// Proof generation parameters that can be provided during new or sign phases
|
||||
#[derive(Clone, Serialize, Deserialize, Debug)]
|
||||
pub struct ProofArgs {
|
||||
/// If net change is positive during this step, whether to suppress the creation of payment proof
|
||||
pub suppress_proof: bool,
|
||||
/// Type of proof (Default 'Invoice')
|
||||
pub proof_type: ProofType,
|
||||
/// Sender address (required at some stage, may not necessarily be in slate so can be provided explicitly)
|
||||
#[serde(with = "dalek_ser::option_dalek_pubkey_serde")]
|
||||
pub sender_address: Option<DalekPublicKey>,
|
||||
}
|
||||
|
||||
impl Default for ProofArgs {
|
||||
fn default() -> ProofArgs {
|
||||
ProofArgs {
|
||||
suppress_proof: false,
|
||||
proof_type: ProofType::Legacy,
|
||||
sender_address: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Contract Setup - defines how we pick inputs/outputs and what we expect from a contract. Both
|
||||
/// 'new' and 'sign' actions perform a setup phase which is why their endpoints take these parameters.
|
||||
#[derive(Clone, Serialize, Deserialize, Debug)]
|
||||
pub struct ContractSetupArgsAPI {
|
||||
/// 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>,
|
||||
/// The net change we will agree on. The amount is in nanogrins (`1 G = 1_000_000_000nG`).
|
||||
/// The value is positive when we are on the receiving end and negative when we are the sender.
|
||||
/// It is optional because we could have agreed on it before we reach the sign e.g. when we create new contract
|
||||
pub net_change: Option<i64>,
|
||||
/// The number of participants in a contract. Used for computing our kernel fee contribution
|
||||
pub num_participants: u8,
|
||||
/// Should we perform an early lock of outputs
|
||||
pub add_outputs: bool,
|
||||
/// Output selection arguments
|
||||
pub selection_args: OutputSelectionArgs,
|
||||
/// Proof arguments
|
||||
pub proof_args: ProofArgs,
|
||||
}
|
||||
|
||||
impl Default for ContractSetupArgsAPI {
|
||||
fn default() -> ContractSetupArgsAPI {
|
||||
ContractSetupArgsAPI {
|
||||
src_acct_name: None,
|
||||
net_change: None,
|
||||
num_participants: 2,
|
||||
add_outputs: false,
|
||||
selection_args: OutputSelectionArgs {
|
||||
..Default::default()
|
||||
},
|
||||
proof_args: ProofArgs::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Contract New
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
pub struct ContractNewArgsAPI {
|
||||
/// TODO: do we need the target_slate_version?
|
||||
/// 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>,
|
||||
/// Setup args - contract new also initiates the setup by default
|
||||
pub setup_args: ContractSetupArgsAPI,
|
||||
}
|
||||
|
||||
impl Default for ContractNewArgsAPI {
|
||||
fn default() -> ContractNewArgsAPI {
|
||||
ContractNewArgsAPI {
|
||||
target_slate_version: None,
|
||||
setup_args: ContractSetupArgsAPI {
|
||||
src_acct_name: None,
|
||||
net_change: None,
|
||||
num_participants: 2,
|
||||
add_outputs: false,
|
||||
selection_args: OutputSelectionArgs {
|
||||
..Default::default()
|
||||
},
|
||||
proof_args: ProofArgs::default(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// ContractView
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
pub struct ContractView {
|
||||
/// TODO: do we need the target_slate_version?
|
||||
pub target_slate_version: Option<u16>,
|
||||
/// Every slatepack has a number of participants
|
||||
pub num_participants: u8,
|
||||
/// Suggested value for the party at step2 (only provided if slatepack is at step1)
|
||||
pub suggested_net_change: Option<i64>,
|
||||
/// Agreed net_change if we've agreed on it (the context must exist for this)
|
||||
// NOTE: we drop the Context once we've signed. Perhaps we should think about dropping
|
||||
// only the private keys associated with it to prevent double-signing with the same
|
||||
// (pubkey, nonce) pair. This way, we'd retain the history on that wallet instance.
|
||||
// There might also be value in forgetting the whole context.
|
||||
pub agreed_net_change: Option<i64>,
|
||||
/// Number of singatures on the contract
|
||||
pub num_sigs: u8,
|
||||
/// Has the contract been executed on chain
|
||||
pub is_executed: bool,
|
||||
}
|
||||
|
||||
impl Default for ContractView {
|
||||
fn default() -> ContractView {
|
||||
ContractView {
|
||||
target_slate_version: None,
|
||||
num_participants: 2,
|
||||
suggested_net_change: None,
|
||||
agreed_net_change: None,
|
||||
num_sigs: 0,
|
||||
is_executed: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Arguments for contract revoke function
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
pub struct ContractRevokeArgsAPI {
|
||||
/// Tx id to cancel
|
||||
pub tx_id: u32,
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
// Copyright 2022 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.
|
||||
|
||||
//! Contract building utility functions
|
||||
|
||||
use crate::contract::selection::verify_selection_consistency;
|
||||
use crate::contract::types::ContractSetupArgsAPI;
|
||||
use crate::grin_core::libtx::tx_fee;
|
||||
use crate::grin_keychain::{Identifier, Keychain};
|
||||
use crate::grin_util::secp::key::SecretKey;
|
||||
use crate::slate::Slate;
|
||||
use crate::types::{Context, NodeClient, StoredProofInfo, TxLogEntryType, WalletBackend};
|
||||
use crate::util::OnionV3Address;
|
||||
use crate::{address, Error, OutputData, OutputStatus, TxLogEntry};
|
||||
use grin_core::core::FeeFields;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Creates an initial TxLogEntry without input/output or kernel information
|
||||
pub fn create_tx_log_entry(
|
||||
slate: &Slate,
|
||||
net_change: i64,
|
||||
parent_key_id: Identifier,
|
||||
log_id: u32,
|
||||
) -> Result<TxLogEntry, Error> {
|
||||
let log_type = if slate.num_participants == 1 {
|
||||
TxLogEntryType::TxSelfSpend
|
||||
} else {
|
||||
if net_change > 0 {
|
||||
TxLogEntryType::TxReceived
|
||||
} else {
|
||||
TxLogEntryType::TxSent
|
||||
}
|
||||
};
|
||||
let mut t = TxLogEntry::new(parent_key_id.clone(), log_type, log_id);
|
||||
// TODO: TxLogEntry has stored_tx field. Check what this needs to be set to and check other fields as well
|
||||
|
||||
t.tx_slate_id = Some(slate.id);
|
||||
if net_change > 0 {
|
||||
t.amount_credited = net_change as u64;
|
||||
} else {
|
||||
t.amount_debited = -net_change as u64;
|
||||
}
|
||||
t.ttl_cutoff_height = match slate.ttl_cutoff_height {
|
||||
0 => None,
|
||||
n => Some(n),
|
||||
};
|
||||
|
||||
Ok(t)
|
||||
}
|
||||
|
||||
/// Updates TxLogEntry for a contract with information available in the 'sign' step
|
||||
pub fn update_tx_log_entry<'a, T: ?Sized, C, K>(
|
||||
wallet: &mut T,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
slate: &Slate,
|
||||
context: &Context,
|
||||
tx_log_entry: &mut TxLogEntry,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
// This is expected to be called when we are signing the contract and have already contributed inputs & outputs
|
||||
let keychain = wallet.keychain(keychain_mask)?;
|
||||
let parent_key_id = context.parent_key_id.clone();
|
||||
let current_height = wallet.w2n_client().get_chain_tip()?.0;
|
||||
// We have already contributed inputs and outputs so we know how much of each we contribute
|
||||
tx_log_entry.num_outputs = context.output_ids.len();
|
||||
tx_log_entry.num_inputs = context.input_ids.len();
|
||||
tx_log_entry.fee = context.fee;
|
||||
// Set kernel information
|
||||
match slate.calc_excess(keychain.secp()) {
|
||||
Ok(e) => tx_log_entry.kernel_excess = Some(e),
|
||||
Err(_) => panic!("We can't update tx log entry. Excess could not be computed."),
|
||||
};
|
||||
tx_log_entry.kernel_lookup_min_height = Some(current_height);
|
||||
|
||||
// If we're sending and there's payment proof info in the slate added by recipient, store as well
|
||||
if let Some(ref p) = slate.payment_proof {
|
||||
if tx_log_entry.amount_debited > 0 {
|
||||
// note we only use a single path for now
|
||||
let sender_address_path = 0u32;
|
||||
let sender_key = address::address_from_derivation_path(
|
||||
&keychain,
|
||||
&parent_key_id,
|
||||
sender_address_path,
|
||||
)?;
|
||||
let sender_address = OnionV3Address::from_private(&sender_key.0)?;
|
||||
|
||||
// We're looking for the OTHER party here, the recipient
|
||||
let sender_index = slate.find_index_matching_context(&keychain, context)?;
|
||||
let recipient_index = sender_index ^ 1;
|
||||
|
||||
tx_log_entry.payment_proof = Some(StoredProofInfo {
|
||||
receiver_address: p.receiver_address,
|
||||
receiver_signature: p.promise_signature,
|
||||
sender_address: sender_address.to_ed25519()?,
|
||||
sender_address_path,
|
||||
sender_signature: None,
|
||||
/// TODO: Will fill these as separate steps for now, check whether this
|
||||
/// can be merged in a general case (which means knowing which nonces here belong to
|
||||
/// the recipient)
|
||||
proof_type: Some(1u8),
|
||||
receiver_public_nonce: Some(slate.participant_data[recipient_index].public_nonce),
|
||||
receiver_public_excess: Some(
|
||||
slate.participant_data[recipient_index].public_blind_excess,
|
||||
),
|
||||
timestamp: Some(p.timestamp),
|
||||
memo: p.memo.clone(),
|
||||
promise_signature: p.promise_signature,
|
||||
sender_part_sig: slate.participant_data[sender_index].part_sig,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get net_change value. This is obtained either from the Context.net_change or the setup_args.net_change
|
||||
pub fn get_net_change<'a, T: ?Sized, C, K>(
|
||||
w: &mut T,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
// TODO: make this receive only slate.id instead of passing the whole slate
|
||||
slate: &Slate,
|
||||
setup_args_net_change: Option<i64>,
|
||||
) -> Result<i64, Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
let mut expected_net_change: Option<i64> = setup_args_net_change;
|
||||
match w.get_private_context(keychain_mask, slate.id.as_bytes()) {
|
||||
Ok(ctx) => {
|
||||
debug!("contract::sign => context found");
|
||||
// We have a context so we must have agreed on a certain net_change value in Context.net_change.
|
||||
// If we have both Context.net_change and setup_args.net_change, then they must be equal.
|
||||
match expected_net_change {
|
||||
Some(args_net_change) => {
|
||||
if ctx.get_net_change() != args_net_change {
|
||||
panic!(
|
||||
"Expected net change mismatch! Context.net_change: {}, setup_args.net_change: {}",
|
||||
ctx.get_net_change(), args_net_change
|
||||
);
|
||||
}
|
||||
}
|
||||
None => (),
|
||||
}
|
||||
expected_net_change = Some(ctx.get_net_change());
|
||||
}
|
||||
Err(_) => debug!("contract::utils::get_net_change => context not found"),
|
||||
};
|
||||
|
||||
// Fail if net_change was not passed to setup_args and was also not present in the context.
|
||||
// This means it has not been explicitly agreed on and we require the user to pass it.
|
||||
if expected_net_change.is_none() {
|
||||
return Err(Error::GenericError(
|
||||
"You did not agree on the expected net difference.".into(),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
debug!(
|
||||
"contract::utils::get_net_change => expected_net_change: {}",
|
||||
expected_net_change.unwrap()
|
||||
);
|
||||
|
||||
Ok(expected_net_change.unwrap())
|
||||
}
|
||||
|
||||
/// Atomically locks the inputs and saves the changes of Context, TxLogEntry and OutputData.
|
||||
/// Additionally, the transaction is saved in a file in case we signed it.
|
||||
pub fn save_step<'a, T: ?Sized, C, K>(
|
||||
w: &mut T,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
slate: &Slate,
|
||||
context: &mut Context,
|
||||
step_added_outputs: bool,
|
||||
is_signed: bool,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
debug!(
|
||||
"contract::utils::save_step => performing atomic update for slate_id: {}",
|
||||
slate.id
|
||||
);
|
||||
// Phase 1 - precompute the data needed for atomic update
|
||||
let parent_key_id = &context.parent_key_id;
|
||||
let current_height = w.w2n_client().get_chain_tip()?.0;
|
||||
// We are at step2 if we don't have context.log_id and we have signed the slate
|
||||
let is_step2 = !context.log_id.is_some() && is_signed;
|
||||
|
||||
let mut tx_log_entry = {
|
||||
if !context.log_id.is_some() {
|
||||
// We create a new entry with log_id=0 and but replace it with the real id before committing
|
||||
create_tx_log_entry(slate, context.get_net_change(), parent_key_id.clone(), 0)?
|
||||
} else {
|
||||
w.get_tx_log_entry(parent_key_id.clone(), context.log_id.unwrap())?
|
||||
.unwrap()
|
||||
}
|
||||
};
|
||||
|
||||
// Update TxLogEntry if we have signed the contract (we have data about the kernel)
|
||||
if is_signed {
|
||||
update_tx_log_entry(w, keychain_mask, &slate, &context, &mut tx_log_entry)?;
|
||||
// TODO: It's possible to store the transaction in a file while and the atomic commit below fails
|
||||
// In this case, we should revert to the previous stored tx to avoid having discrepancy
|
||||
w.store_tx(&format!("{}", slate.id), slate.tx_or_err()?)?;
|
||||
}
|
||||
// If we added outputs in this step, we have to create OutputData here because 'batch'
|
||||
// takes the mutable ref and we can no longer call calc_commit_for_cache for output
|
||||
let added_outputs = if !step_added_outputs {
|
||||
vec![]
|
||||
} else {
|
||||
let mut output_data_xs: Vec<OutputData> = vec![];
|
||||
// Create an OutputData entry for every created output
|
||||
for (key_id, _, amount) in context.get_outputs() {
|
||||
let commit = w.calc_commit_for_cache(keychain_mask, amount, &key_id)?;
|
||||
let output_data = OutputData {
|
||||
root_key_id: parent_key_id.clone(),
|
||||
key_id: key_id.clone(),
|
||||
mmr_index: None,
|
||||
n_child: key_id.to_path().last_path_index(),
|
||||
commit: commit,
|
||||
value: amount,
|
||||
status: OutputStatus::Unconfirmed,
|
||||
height: current_height,
|
||||
lock_height: 0,
|
||||
is_coinbase: false,
|
||||
tx_log_entry: None,
|
||||
};
|
||||
output_data_xs.push(output_data);
|
||||
}
|
||||
output_data_xs
|
||||
};
|
||||
|
||||
// Phase 2 - atomically update Context, OutputData and TxLogEntry
|
||||
let mut batch = w.batch(keychain_mask)?;
|
||||
|
||||
// Update TxLogEntry
|
||||
if !context.log_id.is_some() {
|
||||
// If we just created the TxLogEntry, we have to assign it an id
|
||||
let log_id = batch.next_tx_log_id(&parent_key_id)?;
|
||||
tx_log_entry.id = log_id;
|
||||
context.log_id = Some(log_id);
|
||||
}
|
||||
batch.save_tx_log_entry(tx_log_entry.clone(), &parent_key_id)?;
|
||||
// Create OutputData entries and lock inputs if we added outputs at this step
|
||||
if step_added_outputs {
|
||||
// Create an OutputData entry for every created output
|
||||
for mut output_data in added_outputs {
|
||||
output_data.tx_log_entry = context.log_id;
|
||||
batch.save(output_data)?;
|
||||
}
|
||||
// Lock inputs
|
||||
for id in context.get_inputs() {
|
||||
let mut coin = batch.get(&id.0, &id.1).unwrap();
|
||||
// At this point we already have context.log_id set
|
||||
coin.tx_log_entry = context.log_id;
|
||||
batch.lock_output(&mut coin)?;
|
||||
}
|
||||
}
|
||||
|
||||
// Update context
|
||||
if is_signed && !is_step2 {
|
||||
// NOTE: We MUST forget the context when we sign. Ideally, these two would be atomic or perhaps
|
||||
// when we call slate::sigadd_partial_signaturen we could swap the secret key with a temporary one just to be safe.
|
||||
// The reason we don't delete if we are at step2 is because in case we want to do safe cancel,
|
||||
// we need to know which inputs are in the context to know which input we have to double-spend.
|
||||
batch.delete_private_context(slate.id.as_bytes())?;
|
||||
} else {
|
||||
batch.save_private_context(slate.id.as_bytes(), &context)?;
|
||||
}
|
||||
|
||||
batch.commit()?;
|
||||
|
||||
// TODO: Assert we don't have the context to avoid potentially leaking it! Also write tests around this.
|
||||
debug!("contract::utils::save_step => Atomic updated done");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Computes fees contribution for a participant
|
||||
pub fn my_fee_contribution(
|
||||
n_inputs: usize,
|
||||
n_outputs: usize,
|
||||
n_kernels: usize,
|
||||
num_participants: u8,
|
||||
) -> Result<FeeFields, Error> {
|
||||
// Add our fee costs for our inputs and a single output
|
||||
let mut fee = tx_fee(n_inputs, n_outputs, 0);
|
||||
// Add out fee costs for kernel. We pay 1/num_participants of a kernel cost
|
||||
let kernel_cost = tx_fee(0, 0, n_kernels);
|
||||
// TODO: we slightly overpay. Make sure to cover all the cases
|
||||
let my_kernel_cost = (kernel_cost as f64 / (num_participants as f64)).ceil();
|
||||
fee += my_kernel_cost as u64;
|
||||
|
||||
// Add my fee contribution to the slate total fee.
|
||||
// TODO: Does this break compatibility with existing slates?
|
||||
let my_fee_fields = FeeFields::new(0, fee)?;
|
||||
Ok(my_fee_fields)
|
||||
}
|
||||
|
||||
/// Returns an error if the slate has already been signed (in our local database). Even if the
|
||||
/// result is Ok, it's still possible it was signed but we don't have the data about it locally.
|
||||
pub fn verify_not_signed<'a, T: ?Sized, C, K>(w: &mut T, slate_id: Uuid) -> Result<(), Error>
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
// If we have a transaction log entry for that slatepack that has a kernel value, then
|
||||
// we have already signed this slate.
|
||||
let tx = w
|
||||
.tx_log_iter()
|
||||
.find(|t| t.tx_slate_id.is_some() && t.tx_slate_id.unwrap() == slate_id);
|
||||
let already_signed = tx.is_some() && tx.unwrap().kernel_excess.is_some();
|
||||
if already_signed {
|
||||
debug!("contract::utils::verify_not_signed => The slate has already been signed.");
|
||||
return Err(Error::GenericError(
|
||||
format!("Slate with id:{} has already been signed.", slate_id).into(),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Compares the setup args provided at call with those in the Context and checks whether they conflict.
|
||||
/// This is relevant to see if there's any conflict in the arguments provided at step1 with step3.
|
||||
pub fn verify_setup_args_consistency(
|
||||
ctx_setup_args: &ContractSetupArgsAPI,
|
||||
cur_setup_args: &ContractSetupArgsAPI,
|
||||
) -> Result<(), Error> {
|
||||
// Compare net_change
|
||||
if ctx_setup_args.net_change.unwrap() != cur_setup_args.net_change.unwrap() {
|
||||
panic!(
|
||||
"Inconsistent net change. Ctx net_change:{}, Current net_change: {}",
|
||||
ctx_setup_args.net_change.unwrap(),
|
||||
cur_setup_args.net_change.unwrap()
|
||||
);
|
||||
}
|
||||
// Compare num_participants
|
||||
if ctx_setup_args.num_participants != cur_setup_args.num_participants {
|
||||
panic!(
|
||||
"Inconsistent num_participants. Ctx num_participants:{}, Current num_participants: {}",
|
||||
ctx_setup_args.num_participants, cur_setup_args.num_participants
|
||||
);
|
||||
}
|
||||
// TODO: Should we verify add_outputs?
|
||||
// TODO: verify that the parent_key_id is consistent, perhaps even with the active_account set?
|
||||
|
||||
// Compare OutputSelectionArgs
|
||||
verify_selection_consistency(
|
||||
&ctx_setup_args.selection_args,
|
||||
&cur_setup_args.selection_args,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the parent_key_id for a given wallet instance and src_acct_name
|
||||
pub fn parent_key_for<'a, T: ?Sized, C, K>(w: &mut T, src_acct_name: Option<&String>) -> Identifier
|
||||
where
|
||||
T: WalletBackend<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
// TODO: does it matter what api.set_active_account is set? also check LMDB set_parent_key_id etc. methods
|
||||
// - Does it matter what api.set_active_account is set? I think w.parent_key_id() already takes the active one
|
||||
// but the verify_consistency may need to verify this or perhaps give a warning that active is different than
|
||||
// the one that was set at the first setup phase.
|
||||
let parent_key_id = match src_acct_name {
|
||||
Some(d) => {
|
||||
let pm = w.get_acct_path(d.clone()).unwrap();
|
||||
match pm {
|
||||
Some(p) => p.path,
|
||||
// TODO: should we error if the path is not found?
|
||||
None => w.parent_key_id(),
|
||||
}
|
||||
}
|
||||
None => w.parent_key_id(),
|
||||
};
|
||||
parent_key_id
|
||||
}
|
||||
Reference in New Issue
Block a user