improve contract view and slatepack handling

This commit is contained in:
wiesche
2026-09-04 15:38:46 +02:00
parent 172a674531
commit 483b29597f
12 changed files with 495 additions and 133 deletions
+94 -76
View File
@@ -19,9 +19,7 @@ use crate::config::{TorConfig, WalletConfig, WALLET_CONFIG_FILE_NAME};
use crate::core::{core, global};
use crate::error::Error;
use crate::impls::PathToSlatepack;
use crate::impls::SlateGetter as _;
use crate::keychain;
use crate::libwallet::api_impl::owner;
use crate::libwallet::api_impl::types::update_tx_slate_state;
use crate::libwallet::contract::can_finalize;
use crate::libwallet::contract::types::{
@@ -762,6 +760,44 @@ where
Ok(slate_out)
}
fn parse_slatepack_with_mode<L, C, K>(
owner_api: &mut Owner<L, C, K>,
keychain_mask: Option<&SecretKey>,
filename: Option<String>,
message: Option<String>,
) -> Result<(Slate, Option<SlatepackAddress>, bool), Error>
where
L: WalletLCProvider<'static, C, K>,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let packer = Slatepacker::new(SlatepackerArgs {
sender: None,
recipients: vec![],
dec_key: None,
});
let mut slatepack = match filename {
Some(f) => {
let pts = PathToSlatepack::new(f.into(), &packer, true);
pts.get_slatepack(false)?
}
None => match message {
Some(message) => packer.deser_slatepack(message.as_bytes(), false)?,
None => {
let msg = "No slate provided via file or direct input";
return Err(Error::GenericError(msg.into()).into());
}
},
};
let was_encrypted = slatepack.is_encrypted();
if was_encrypted {
let dec_key = owner_api.get_slatepack_secret_key(keychain_mask, 0)?;
slatepack.try_decrypt_payload(Some(&dec_key))?;
}
let slate = packer.get_slate(&slatepack)?;
Ok((slate, slatepack.sender, was_encrypted))
}
// Parse a slate and slatepack from a message
pub fn parse_slatepack<L, C, K>(
owner_api: &mut Owner<L, C, K>,
@@ -774,51 +810,9 @@ where
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let mut ret_address = None;
let slate = match filename {
Some(f) => {
// otherwise, get slate from slatepack
let dec_key = owner_api.get_slatepack_secret_key(keychain_mask, 0)?;
let packer = Slatepacker::new(SlatepackerArgs {
sender: None,
recipients: vec![],
dec_key: Some(&dec_key),
});
let pts = PathToSlatepack::new(f.into(), &packer, true);
let sl = Some(pts.get_tx()?.0);
ret_address = pts.get_slatepack(true)?.sender;
sl
}
None => None,
};
let slate = match slate {
Some(s) => s,
None => {
// try and parse directly from input_slatepack_message
match message {
Some(message) => {
let slate = owner_api.slate_from_slatepack_message(
keychain_mask,
message.clone(),
vec![0],
)?;
let slatepack = owner_api.decode_slatepack_message(
keychain_mask,
message.clone(),
vec![0],
)?;
ret_address = slatepack.sender;
slate
}
None => {
let msg = "No slate provided via file or direct input";
return Err(Error::GenericError(msg.into()).into());
}
}
}
};
Ok((slate, ret_address))
let (slate, sender, _) =
parse_slatepack_with_mode(owner_api, keychain_mask, filename, message)?;
Ok((slate, sender))
}
/// Receive command argument
@@ -957,7 +951,7 @@ where
dec_key: None,
});
if slatepack.mode == 1 {
if slatepack.is_encrypted() {
let dec_key = owner_api.get_slatepack_secret_key(keychain_mask, 0)?;
match slatepack.try_decrypt_payload(Some(&dec_key)) {
Ok(_) => {
@@ -1863,35 +1857,18 @@ where
// Args for signing are just setup args
let contract_sign_args = args.to_api_args()?;
let recipient = slatepack_recipient(args.counterparty_addr.as_deref())?;
print_contract_status("Paste slatepack:", args.as_json);
let mut slatepack_msg = String::new();
io::stdin()
.read_line(&mut slatepack_msg)
.map_err(|e| libwallet::Error::GenericError(format!("Failed to read from stdin: {}", e)))?;
let (mut slate, sender, _) =
parse_slatepack_with_mode(owner_api, keychain_mask, None, Some(slatepack_msg))?;
// Prefer --encrypt-for, then reply to the sender. Without either, use plaintext.
let recipient = recipient.or(sender);
let wallet_inst = owner_api.wallet_inst.clone();
let config_path = owner_api.config_path();
controller::owner_single_use(wallet_inst, keychain_mask, config_path, |api, m| {
// Read the slatepack from stdin
print_contract_status("Paste slatepack:", args.as_json);
let mut slatepack_msg = String::new();
io::stdin().read_line(&mut slatepack_msg).map_err(|e| {
libwallet::Error::GenericError(format!("Failed to read from stdin: {}", e))
})?;
// Decrypt the slate, sign it and encrypt it for the next party
// TODO: Make sure you get the counterparty_addr and slate with 1 call.
let slatepack = owner::decode_slatepack_message(
api.wallet_inst.clone(),
keychain_mask,
String::from(slatepack_msg.clone()),
vec![0],
)?;
// Encrypt the reply for --encrypt-for if given, else for the incoming slatepack's
// sender. If neither is known the incoming slate was plaintext, so reply plaintext.
let recipient = recipient.clone().or(slatepack.sender);
let mut slate = owner::slate_from_slatepack_message(
api.wallet_inst.clone(),
keychain_mask,
String::from(slatepack_msg),
vec![0],
)?;
slate = api.contract_sign(m, &slate, &contract_sign_args)?;
let slate_out = prepare_slatepack(api, keychain_mask, &slate, recipient, args.outfile)?;
@@ -1933,7 +1910,7 @@ where
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let (slate, _) = parse_slatepack(
let (slate, _, was_encrypted) = parse_slatepack_with_mode(
owner_api,
keychain_mask,
args.input_file,
@@ -1944,7 +1921,7 @@ where
let config_path = owner_api.config_path();
controller::owner_single_use(wallet_inst, keychain_mask, config_path, |api, m| {
let view = api.contract_view(m, &slate)?;
display::contract_view(&slate, &view);
display::contract_view(&slate, &view, was_encrypted);
Ok(())
})?;
@@ -2020,6 +1997,7 @@ mod send_tests {
#[cfg(test)]
mod contract_tests {
use super::*;
use ed25519_dalek::{SigningKey, VerifyingKey};
#[test]
fn invalid_recipient() {
@@ -2040,4 +2018,44 @@ mod contract_tests {
assert_eq!(value["is_finalized"], true);
assert_eq!(value["message"], output.message);
}
#[test]
fn slatepack_encryption() {
global::set_local_chain_type(global::ChainTypes::AutomatedTesting);
let key = SigningKey::from_bytes(&[1; 32]);
let address = SlatepackAddress::new(&VerifyingKey::from(&key));
let slate = Slate::blank(2, false);
let plain = Slatepacker::new(SlatepackerArgs {
sender: None,
recipients: vec![],
dec_key: None,
})
.create_slatepack(&slate)
.unwrap();
assert!(!plain.is_encrypted());
let encrypted = Slatepacker::new(SlatepackerArgs {
sender: None,
recipients: vec![address],
dec_key: None,
})
.create_slatepack(&slate)
.unwrap();
assert!(encrypted.is_encrypted());
let mut invalid = serde_json::to_value(&plain).unwrap();
invalid["mode"] = serde_json::json!(2);
let data = serde_json::to_vec(&invalid).unwrap();
let packer = Slatepacker::new(SlatepackerArgs {
sender: None,
recipients: vec![],
dec_key: None,
});
assert!(matches!(
packer.deser_slatepack(&data, false),
Err(libwallet::Error::SlatepackDeser(message))
if message.contains("Unsupported Slatepack mode: 2")
));
}
}
+156 -12
View File
@@ -13,7 +13,7 @@
// limitations under the License.
use crate::core::core::FeeFields;
use crate::core::core::{self, amount_to_hr_string};
use crate::core::core::{self, amount_to_hr_string, Inputs, OutputFeatures};
use crate::core::global;
use crate::libwallet::contract::types::{ContractView, OwnCommitmentStatus};
use crate::libwallet::{
@@ -638,19 +638,49 @@ pub fn payment_proof(tx: &TxLogEntry) -> Result<(), Error> {
}
/// Display a summary of a contract slate
pub fn contract_view(slate: &Slate, view: &ContractView) {
pub fn contract_view(slate: &Slate, view: &ContractView, was_encrypted: bool) {
println!("\n____ Contract ____\n");
contract_view_table(slate, view, was_encrypted).printstd();
println!();
}
fn contract_view_table(
slate: &Slate,
view: &ContractView,
was_encrypted: bool,
) -> prettytable::Table {
let mut table = table!();
table.add_row(row![bFC->"Slate Id", bGC->slate.id]);
table.add_row(row![bFC->"State", bGC->slate.state]);
table.add_row(row![bFC->"Encrypted for This Wallet", bGC->yes_no(was_encrypted)]);
table.add_row(row![bFC->"Participants", bGC->view.num_participants]);
table.add_row(row![bFC->"Signatures", bGC->view.num_sigs]);
let suggested = format_net_change(view.suggested_net_change);
table.add_row(row![bFC->"Suggested Counterparty Net Change", bGC->suggested]);
let agreed = format_net_change(view.agreed_net_change);
table.add_row(row![bFC->"Agreed Net Change", bGC->agreed]);
table.add_row(row![bFC->"Executed", bGC->view.is_executed]);
table.add_row(row![bFC->"Transfer Amount", bGC->amount_to_hr_string(slate.amount, false)]);
let suggested = view
.suggested_net_change
.map(|change| format_net_change(Some(change)))
.unwrap_or_else(|| "Not applicable".to_string());
table.add_row(row![bFC->"Expected Amount Change (Before Fee)", bGC->suggested]);
let agreed = view
.agreed_net_change
.map(|change| format_net_change(Some(change)))
.unwrap_or_else(|| "Not agreed yet".to_string());
table.add_row(row![bFC->"Agreed Amount Change (Before Fee)", bGC->agreed]);
table.add_row(
row![bFC->"Current Transaction Fee", bGC->amount_to_hr_string(slate.fee_fields.fee(), false)],
);
let own_fee = view
.own_fee
.map(|fee| amount_to_hr_string(fee, false))
.unwrap_or_else(|| "Not known before signing".to_string());
table.add_row(row![bFC->"Your Fee", bGC->own_fee]);
let balance_change = match view.balance_change {
Some(change) => format_net_change(Some(change)),
None => "Not known before signing".to_string(),
};
table.add_row(row![bFC->"Your Balance Change", bGC->balance_change]);
table.add_row(row![bFC->"Confirmed", bGC->yes_no(view.is_executed)]);
let (unexpected, warning) = match view.own_commitment_status {
OwnCommitmentStatus::UnexpectedInput => ("Input", true),
OwnCommitmentStatus::UnexpectedOutput => ("Output", true),
@@ -659,14 +689,56 @@ pub fn contract_view(slate: &Slate, view: &ContractView) {
OwnCommitmentStatus::Unknown => ("Unknown", false),
};
if warning {
table.add_row(row![bFC->"Unexpected Own Commitments", bFR->unexpected]);
table.add_row(row![bFC->"Unexpected Wallet Inputs/Outputs", bFR->unexpected]);
} else {
table.add_row(row![bFC->"Unexpected Own Commitments", bGC->unexpected]);
table.add_row(row![bFC->"Unexpected Wallet Inputs/Outputs", bGC->unexpected]);
}
if let Some(tx) = slate.tx.as_ref() {
let inputs = tx.inputs();
table.add_row(row![bFC->"Inputs", bGC->inputs.len()]);
match inputs {
Inputs::CommitOnly(inputs) => {
for (index, input) in inputs.iter().enumerate() {
table.add_row(
row![bFC->format!("Input {}", index + 1), bGC->input.commitment().as_ref().to_hex()],
);
}
}
Inputs::FeaturesAndCommit(inputs) => {
for (index, input) in inputs.iter().enumerate() {
let commitment = input.commitment().as_ref().to_hex();
let value = match input.features {
OutputFeatures::Plain => commitment,
OutputFeatures::Coinbase => format!("Coinbase {}", commitment),
};
table.add_row(row![bFC->format!("Input {}", index + 1), bGC->value]);
}
}
}
table.add_row(row![bFC->"Outputs", bGC->tx.outputs().len()]);
for (index, output) in tx.outputs().iter().enumerate() {
let commitment = output.commitment().as_ref().to_hex();
let value = match output.features() {
OutputFeatures::Plain => commitment,
OutputFeatures::Coinbase => format!("Coinbase {}", commitment),
};
table.add_row(row![bFC->format!("Output {}", index + 1), bGC->value]);
}
} else {
table.add_row(row![bFC->"Inputs", bGC->"Not in slate"]);
table.add_row(row![bFC->"Outputs", bGC->"Not in slate"]);
}
table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
table.printstd();
println!();
table
}
fn yes_no(value: bool) -> &'static str {
if value {
"Yes"
} else {
"No"
}
}
fn format_net_change(change: Option<i64>) -> String {
@@ -682,7 +754,26 @@ fn format_net_change(change: Option<i64>) -> String {
#[cfg(test)]
mod tests {
use super::format_net_change;
use super::{contract_view_table, format_net_change};
use crate::core::core::{FeeFields, Input, Inputs, Output, OutputFeatures, Transaction};
use crate::core::global;
use crate::libwallet::contract::types::ContractView;
use crate::libwallet::Slate;
use crate::util::secp::pedersen::{Commitment, RangeProof};
fn table_value(table: &prettytable::Table, label: &str) -> String {
let row = table
.row_iter()
.find(|row| {
row.get_cell(0)
.map(|cell| cell.get_content() == label)
.unwrap_or(false)
})
.unwrap_or_else(|| panic!("missing table row: {}", label));
row.get_cell(1)
.expect("table row has a value")
.get_content()
}
#[test]
fn net_change_sign() {
@@ -690,4 +781,57 @@ mod tests {
assert_eq!(format_net_change(Some(-1_000_000_000)), "-1.000000000");
assert_eq!(format_net_change(None), "None");
}
#[test]
fn contract_view_rows() {
global::set_local_chain_type(global::ChainTypes::AutomatedTesting);
let mut slate = Slate::blank(2, false);
slate.amount = 1_000_000_000;
slate.fee_fields = FeeFields::new(0, 4_000_000).unwrap();
let input_commit = Commitment::from_vec(vec![3]);
let output_commit = Commitment::from_vec(vec![4]);
slate.tx = Some(
slate
.tx
.take()
.unwrap()
.with_input(Input::new(OutputFeatures::Plain, input_commit))
.with_output(Output::new(
OutputFeatures::Coinbase,
output_commit,
RangeProof::zero(),
)),
);
let view = ContractView {
own_fee: Some(2_000_000),
balance_change: Some(-1_002_000_000),
..Default::default()
};
let table = contract_view_table(&slate, &view, true);
assert_eq!(table_value(&table, "Encrypted for This Wallet"), "Yes");
assert_eq!(table_value(&table, "Transfer Amount"), "1.000000000");
assert_eq!(
table_value(&table, "Current Transaction Fee"),
"0.004000000"
);
assert_eq!(table_value(&table, "Your Fee"), "0.002000000");
assert_eq!(table_value(&table, "Your Balance Change"), "-1.002000000");
assert_eq!(table_value(&table, "Confirmed"), "No");
assert_eq!(table_value(&table, "Inputs"), "1");
assert!(table_value(&table, "Input 1").starts_with("03"));
assert_eq!(table_value(&table, "Outputs"), "1");
assert!(table_value(&table, "Output 1").starts_with("Coinbase 04"));
let table = contract_view_table(&slate, &view, false);
assert_eq!(table_value(&table, "Encrypted for This Wallet"), "No");
slate.tx = Some(Transaction::new(
Inputs::CommitOnly(vec![input_commit.into()]),
&[],
&[],
));
let table = contract_view_table(&slate, &view, false);
assert!(table_value(&table, "Input 1").starts_with("03"));
}
}
+15
View File
@@ -215,6 +215,11 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error>
|api, m| {
let view = api.contract_view(m, &slate)?;
assert_eq!(view.own_commitment_status, OwnCommitmentStatus::Clean);
assert_eq!(view.own_fee, Some(participant_fee));
assert_eq!(
view.balance_change,
Some(5_000_000_000 - participant_fee as i64)
);
Ok(())
},
)?;
@@ -225,6 +230,11 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error>
|api, m| {
let view = api.contract_view(m, &slate)?;
assert_eq!(view.own_commitment_status, OwnCommitmentStatus::Clean);
assert_eq!(view.own_fee, Some(participant_fee));
assert_eq!(
view.balance_change,
Some(-5_000_000_000 - participant_fee as i64)
);
let mut no_tx = slate.clone();
no_tx.tx = None;
let view = api.contract_view(m, &no_tx)?;
@@ -408,6 +418,11 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error>
|api, m| {
let view = api.contract_view(m, &slate)?;
assert_eq!(view.own_commitment_status, OwnCommitmentStatus::Unknown);
assert_eq!(view.own_fee, Some(participant_fee));
assert_eq!(
view.balance_change,
Some(-5_000_000_000 - participant_fee as i64)
);
Ok(())
},
)?;
+11 -8
View File
@@ -10,8 +10,7 @@ separate `setup` command. Setup is done by `new`, or by the first `sign` when ne
The owner API provides all four commands. The Rust foreign API also provides `new` and
`sign` for receiving contracts, but they are not exposed by the foreign JSON-RPC API. The
API does not require manual confirmation, so a wallet using it still needs to show the
transaction and ask the user before signing. The reference CLI does not show the full
inputs, outputs, fees and balance changes yet.
transaction and ask the user before signing.
The CLI exchanges Slatepacks. The last `sign` broadcasts the transaction unless
`--no-broadcast` is used.
@@ -41,12 +40,16 @@ so a late-locked contract can fail if another transaction spends the available o
## View and revoke
`view` reads a slate or Slatepack and shows the participants, signatures, suggested or
agreed amount change, whether the local transaction is confirmed, and whether it contains
unexpected inputs or outputs from this wallet. This check is reported as unknown after
the private context has been removed, when input features are missing, or when the slate
does not contain a transaction. `view` does not show all inputs, outputs and fees, and it
cannot find a contract by id.
`view` reads a slate or Slatepack and shows its inputs and outputs when present, fees,
transfer amount and the resulting change to this wallet when known. It also reports whether
the Slatepack was encrypted for this wallet, whether the local transaction is confirmed,
and whether the slate contains unexpected inputs or outputs from this wallet. This last
check is reported as unknown after the private context has been removed, when input features
are missing, or when the slate does not contain a transaction. `view` cannot find a contract
by id.
An encrypted Slatepack can have several recipients. The encryption status only shows that
this wallet could decrypt it.
`revoke` cancels the local transaction. When the wallet added an input, it returns a
self-spend of that input. The caller still has to post it, and either transaction can win
+1 -1
View File
@@ -1601,7 +1601,7 @@ where
K: Keychain,
{
let mut slate = slate.clone();
contract::view(&mut *w, keychain_mask, &mut slate, "")
contract::view(&mut *w, keychain_mask, &mut slate)
}
/// Sign transaction contract
-4
View File
@@ -46,9 +46,6 @@ Separating side effects until the 'save_step' part would make these functions mu
clearer, for the API as much as the CLI.
- `new` has no `--no-setup`.
- Add custom fee rates and contract TTLs, or document them as unsupported.
- Let `view` report whether a slatepack was encrypted for this wallet.
- Show all inputs, outputs, fees and resulting balance changes before the CLI signs.
- Distinguish the transfer amount from the fee-adjusted balance change in `view`.
- Raise the replacement fee when `revoke` races a transaction already in the mempool.
- Merge invoice-proof retrieval with the existing payment-proof API.
- Add a Grin node API for kernel lookup by MMR index, then use the witness index instead
@@ -61,7 +58,6 @@ Separating side effects until the 'save_step' part would make these functions mu
- Preserve kernel features and their arguments across V4 and V5; see #793.
- Choose the sender derivation path explicitly and keep encrypted outgoing files
identifiable locally.
- Decode the sender and slate from an incoming Slatepack in one pass.
- Decide whether `target_slate_version` should control Slatepack output or be removed.
- Add contract history, lookup by id, transport support and configurable proof memos.
- Decide whether the foreign JSON-RPC API should expose `new` and `sign`.
+69 -8
View File
@@ -23,14 +23,42 @@ use crate::grin_keychain::Keychain;
use crate::grin_util::secp::key::SecretKey;
use crate::internal::updater;
use crate::slate::{Slate, SlateState};
use crate::types::NodeClient;
use crate::types::{NodeClient, TxLogEntry};
fn balance_change(net_change: Option<i64>, fee: Option<u64>) -> Result<Option<i64>, Error> {
match (net_change, fee) {
(Some(change), Some(fee)) => {
let fee = i64::try_from(fee)
.map_err(|_| Error::GenericError(format!("Contract fee {} exceeds i64", fee)))?;
change
.checked_sub(fee)
.map(Some)
.ok_or_else(|| Error::GenericError("Contract balance change overflow".to_string()))
}
_ => Ok(None),
}
}
fn tx_net_change(tx: &TxLogEntry) -> Result<i64, Error> {
let credited = i64::try_from(tx.amount_credited).map_err(|_| {
Error::GenericError(format!(
"Contract credit {} exceeds i64",
tx.amount_credited
))
})?;
let debited = i64::try_from(tx.amount_debited).map_err(|_| {
Error::GenericError(format!("Contract debit {} exceeds i64", tx.amount_debited))
})?;
credited
.checked_sub(debited)
.ok_or_else(|| Error::GenericError("Contract net change overflow".to_string()))
}
/// View contract
pub fn view<C, K>(
w: &mut WalletBackend<C, K>,
keychain_mask: Option<&SecretKey>,
slate: &mut Slate,
_encrypted_for: &str,
) -> Result<ContractView, Error>
where
C: NodeClient,
@@ -65,9 +93,11 @@ where
// slate we have never signed simply has no entry and is not executed.
let txs = updater::retrieve_txs(w, None, Some(slate.id), None, None, false)?;
let is_executed = txs.iter().any(|tx| tx.confirmed);
let has_signed = txs
let signed_tx = txs
.iter()
.any(|tx| contract::utils::is_signed_tx(tx, slate.id));
.find(|tx| contract::utils::is_signed_tx(tx, slate.id));
let has_signed = signed_tx.is_some();
let tx = signed_tx.or_else(|| txs.first());
// Once we have signed, the context identifies the commitments we added. If it has
// already been removed, the slate no longer carries enough information to do that.
let own_commitment_status = if slate.tx.is_none() || (context.is_none() && !txs.is_empty()) {
@@ -88,18 +118,27 @@ where
.filter(|v| v.is_complete())
.count();
// If we have a local context for this slate we've agreed on a net change; surface it.
// Read the agreed change from the context, or from the transaction log once it is gone.
let agreed_net_change = context
.as_ref()
.and_then(|context| context.setup_args.as_ref())
.and_then(|args| args.net_change);
.and_then(|args| args.net_change)
.map(Ok)
.or_else(|| tx.map(tx_net_change))
.transpose()?;
let own_fee = context
.as_ref()
.and_then(|context| context.fee)
.or_else(|| tx.and_then(|tx| tx.fee))
.map(|fee| fee.fee());
let balance_change = balance_change(agreed_net_change, own_fee)?;
// 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,
own_fee,
balance_change,
num_sigs: num_sigs as u8,
is_executed: is_executed,
own_commitment_status,
@@ -127,4 +166,26 @@ mod tests {
None
);
}
#[test]
fn balance_change_includes_fee() {
assert_eq!(balance_change(Some(10), Some(2)).unwrap(), Some(8));
assert_eq!(balance_change(Some(-10), Some(2)).unwrap(), Some(-12));
assert_eq!(balance_change(Some(10), None).unwrap(), None);
assert!(balance_change(Some(i64::MIN), Some(1)).is_err());
}
#[test]
fn reads_change_from_tx_log() {
let mut tx = TxLogEntry::new(
crate::grin_keychain::Identifier::zero(),
crate::types::TxLogEntryType::TxReceived,
0,
);
tx.amount_credited = 10;
assert_eq!(tx_net_change(&tx).unwrap(), 10);
tx.amount_credited = 0;
tx.amount_debited = 10;
assert_eq!(tx_net_change(&tx).unwrap(), -10);
}
}
+7 -5
View File
@@ -179,12 +179,12 @@ pub struct ContractView {
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.
/// Agreed net_change, when known from the context or transaction log
pub agreed_net_change: Option<i64>,
/// This wallet's fee contribution, when known from the context or transaction log
pub own_fee: Option<u64>,
/// Agreed balance change after this wallet's fee, or None while the fee is unknown
pub balance_change: Option<i64>,
/// Number of singatures on the contract
pub num_sigs: u8,
/// Has the contract been executed on chain
@@ -220,6 +220,8 @@ impl Default for ContractView {
num_participants: 2,
suggested_net_change: None,
agreed_net_change: None,
own_fee: None,
balance_change: None,
num_sigs: 0,
is_executed: false,
own_commitment_status: OwnCommitmentStatus::Unknown,
+2 -1
View File
@@ -65,7 +65,8 @@ pub use crate::slate_versions::{
GRIN_BLOCK_HEADER_VERSION,
};
pub use crate::slatepack::{
Slatepack, SlatepackAddress, SlatepackArmor, SlatepackBin, Slatepacker, SlatepackerArgs,
Slatepack, SlatepackAddress, SlatepackArmor, SlatepackBin, SlatepackMode, Slatepacker,
SlatepackerArgs,
};
pub use api_impl::owner_updater::StatusMessage;
pub use api_impl::types::{
+1 -1
View File
@@ -22,4 +22,4 @@ mod types;
pub use self::address::SlatepackAddress;
pub use self::armor::{max_size, min_size, SlatepackArmor};
pub use self::packer::{Slatepacker, SlatepackerArgs};
pub use self::types::{Slatepack, SlatepackBin};
pub use self::types::{Slatepack, SlatepackBin, SlatepackMode};
+98 -17
View File
@@ -32,6 +32,57 @@ use std::io::{Cursor, Read, Write};
pub const SLATEPACK_MAJOR_VERSION: u8 = 1;
pub const SLATEPACK_MINOR_VERSION: u8 = 0;
/// Slatepack payload encoding mode.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(u8)]
#[non_exhaustive]
pub enum SlatepackMode {
/// Plaintext payload
Plaintext = 0,
/// Payload encrypted for one or more recipients using age
AgeEncrypted = 1,
}
impl From<SlatepackMode> for u8 {
fn from(mode: SlatepackMode) -> Self {
mode as u8
}
}
impl TryFrom<u8> for SlatepackMode {
type Error = Error;
fn try_from(mode: u8) -> Result<Self, Self::Error> {
match mode {
0 => Ok(Self::Plaintext),
1 => Ok(Self::AgeEncrypted),
_ => Err(Error::SlatepackDeser(format!(
"Unsupported Slatepack mode: {}",
mode
))),
}
}
}
impl serde::Serialize for SlatepackMode {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_u8((*self).into())
}
}
impl<'de> serde::Deserialize<'de> for SlatepackMode {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let mode = u8::deserialize(deserializer)?;
Self::try_from(mode).map_err(serde::de::Error::custom)
}
}
/// Basic Slatepack definition
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct Slatepack {
@@ -39,8 +90,8 @@ pub struct Slatepack {
/// Versioning info
#[serde(with = "slatepack_version")]
pub slatepack: SlatepackVersion,
/// Delivery Mode, 0 = plain_text, 1 = age encrypted
pub mode: u8,
/// Delivery mode
pub mode: SlatepackMode,
// Optional Fields
/// Optional Sender address
@@ -101,7 +152,7 @@ impl Default for Slatepack {
major: SLATEPACK_MAJOR_VERSION,
minor: SLATEPACK_MINOR_VERSION,
},
mode: 0,
mode: SlatepackMode::Plaintext,
sender: None,
encrypted_meta: default_enc_metadata(),
payload: vec![],
@@ -111,6 +162,11 @@ impl Default for Slatepack {
}
impl Slatepack {
/// Whether the payload is encrypted.
pub fn is_encrypted(&self) -> bool {
self.mode == SlatepackMode::AgeEncrypted
}
/// return length of optional fields
pub fn opt_fields_len(&self) -> Result<usize, ser::Error> {
let mut retval = 0;
@@ -174,13 +230,13 @@ impl Slatepack {
writer.write_all(&to_encrypt)?;
writer.finish()?;
self.payload = encrypted.to_vec();
self.mode = 1;
self.mode = SlatepackMode::AgeEncrypted;
Ok(())
}
/// As above, decrypt if needed
pub fn try_decrypt_payload(&mut self, dec_key: Option<&edSecretKey>) -> Result<(), Error> {
if self.mode == 0 {
if !self.is_encrypted() {
return Ok(());
}
let dec_key = match dec_key {
@@ -201,7 +257,11 @@ impl Slatepack {
let decryptor = match age::Decryptor::new(&self.payload[..])? {
age::Decryptor::Recipients(d) => d,
_ => unreachable!(),
age::Decryptor::Passphrase(_) => {
return Err(Error::SlatepackDeser(
"Passphrase encrypted Slatepacks are not supported".into(),
));
}
};
let mut decrypted = vec![];
let mut reader = decryptor.decrypt(std::iter::once(&key as &dyn age::Identity))?;
@@ -230,7 +290,7 @@ impl Slatepack {
.0;
self.sender = meta.sender;
self.encrypted_meta.recipients = meta.recipients;
self.mode = 0;
self.mode = SlatepackMode::Plaintext;
Ok(())
}
@@ -320,7 +380,7 @@ impl Writeable for SlatepackBin {
// Version (2)
sp.slatepack.write(writer)?;
// Mode (1)
writer.write_u8(sp.mode)?;
writer.write_u8(sp.mode.into())?;
// 16 bits of optional content flags (2), most reserved for future use
let mut opt_flags: u16 = 0;
@@ -350,13 +410,11 @@ impl Readable for SlatepackBin {
// Version (2)
let slatepack = SlatepackVersion::read(reader)?;
// Mode (1)
let mode = reader.read_u8()?;
if mode > 1 {
return Err(ser::Error::UnexpectedData {
expected: vec![0, 1],
received: vec![mode],
});
}
let mode_value = reader.read_u8()?;
let mode = SlatepackMode::try_from(mode_value).map_err(|_| ser::Error::UnexpectedData {
expected: vec![0, 1],
received: vec![mode_value],
})?;
// optional content flags (2)
let opt_flags = reader.read_u16()?;
@@ -763,7 +821,7 @@ fn slatepack_bin_future() -> Result<(), grin_wallet_util::byte_ser::Error> {
}
// test encryption and encrypted metadata, which only gets written
// if mode == 1
// in AgeEncrypted mode
#[test]
fn slatepack_encrypted_meta() -> Result<(), Error> {
use crate::grin_core::global;
@@ -899,7 +957,7 @@ fn slatepack_decrypt_rejects_malformed_plaintexts() -> Result<(), Error> {
for plaintext in vec![vec![], vec![0], vec![0, 0, 0], vec![0xff; 4]] {
let mut slatepack = Slatepack {
mode: 1,
mode: SlatepackMode::AgeEncrypted,
payload: encrypt_plaintext_to_slatepack_recipient(&addr, &plaintext)?,
..Slatepack::default()
};
@@ -911,3 +969,26 @@ fn slatepack_decrypt_rejects_malformed_plaintexts() -> Result<(), Error> {
Ok(())
}
#[test]
fn rejects_passphrase_payload() -> Result<(), Error> {
let encryptor =
age::Encryptor::with_user_passphrase(age::secrecy::Secret::new("passphrase".to_string()));
let mut payload = vec![];
let mut writer = encryptor.wrap_output(&mut payload)?;
writer.write_all(b"payload")?;
writer.finish()?;
let mut slatepack = Slatepack {
mode: SlatepackMode::AgeEncrypted,
payload,
..Slatepack::default()
};
let key = edSecretKey::from_bytes(&[1; 32]);
assert!(matches!(
slatepack.try_decrypt_payload(Some(&key)),
Err(Error::SlatepackDeser(_))
));
Ok(())
}
+41
View File
@@ -100,6 +100,7 @@ fn contract_command_test_impl(test_dir: &str) -> Result<(), grin_wallet_controll
// Mine into wallet 1 so it has something to send
let mask1 = (&mask1_i).as_ref();
let mask2 = (&mask2_i).as_ref();
let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 5, false);
// Wallet 1 opens a contract sending 1 grin, leaving an unencrypted slatepack because
@@ -142,6 +143,46 @@ fn contract_command_test_impl(test_dir: &str) -> Result<(), grin_wallet_controll
];
execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?;
// Wallet 2 can also view a slatepack encrypted for its address
let mut recipient = None;
grin_wallet_controller::controller::owner_single_use(
wallet2.clone(),
mask2,
std::path::PathBuf::from(test_dir),
|api, m| {
recipient = Some(api.get_slatepack_address(m, 0)?.to_string());
Ok(())
},
)?;
std::fs::remove_file(file_name).unwrap();
let recipient = recipient.unwrap();
let arg_vec = vec![
"grin-wallet",
"-p",
"password1",
"contract",
"new",
"--send",
"1",
"--min_conf",
"1",
"--encrypt-for",
&recipient,
];
execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?;
let file_name = only_slatepack(test_dir, "wallet1");
let arg_vec = vec![
"grin-wallet",
"-p",
"password2",
"contract",
"view",
"-i",
&file_name,
];
execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?;
// A file that isn't there is reported, not panicked on
let arg_vec = vec![
"grin-wallet",