add contract proof options

This commit is contained in:
wiesche
2026-09-06 19:12:28 +02:00
parent 3f1d15fea0
commit e0e33eae42
10 changed files with 261 additions and 21 deletions
+132 -6
View File
@@ -24,6 +24,7 @@ use crate::libwallet::api_impl::types::update_tx_slate_state;
use crate::libwallet::contract::can_finalize;
use crate::libwallet::contract::types::{
ContractNewArgsAPI, ContractRevokeArgsAPI, ContractSetupArgsAPI, OutputSelectionArgs,
PaymentMemo, ProofArgs, ProofType,
};
use crate::libwallet::{
self, InitTxArgs, IssueInvoiceTxArgs, NodeClient, PaymentProof, Slate, SlateState,
@@ -1698,6 +1699,56 @@ pub struct ContractNewArgs {
pub outfile: Option<String>,
/// Select and lock outputs early
pub add_outputs: bool,
/// Early payment proof type
pub proof_type: Option<ProofType>,
/// Early payment proof memo
pub memo: Option<PaymentMemo>,
}
fn contract_proof_args(
proof_type: Option<ProofType>,
memo: Option<PaymentMemo>,
receiving: bool,
) -> Result<ProofArgs, Error> {
if memo.is_some() && proof_type.is_none() {
return Err(Error::ArgumentError(
"--memo requires --proof-type".to_string(),
));
}
if proof_type.is_some() && !receiving {
return Err(Error::ArgumentError(
"Early payment proofs require a positive --receive amount".to_string(),
));
}
Ok(match proof_type {
Some(proof_type) => ProofArgs {
suppress_proof: false,
proof_type,
memo,
..Default::default()
},
None => ProofArgs::default(),
})
}
fn set_proof_sender(
proof_args: &mut ProofArgs,
sender: Option<&SlatepackAddress>,
fallback: Option<&SlatepackAddress>,
) -> Result<(), Error> {
if !proof_args.suppress_proof {
proof_args.sender_address = Some(
sender
.or(fallback)
.ok_or_else(|| {
Error::ArgumentError(
"Early payment proofs require a Slatepack sender address".into(),
)
})?
.pub_key,
);
}
Ok(())
}
impl ContractNewArgs {
@@ -1739,7 +1790,11 @@ impl ContractNewArgs {
make_outputs: self.make_outputs.clone(),
..Default::default()
},
proof_args: Default::default(),
proof_args: contract_proof_args(
self.proof_type,
self.memo.clone(),
self.receive.unwrap_or(0) > 0,
)?,
},
..Default::default()
})
@@ -1756,8 +1811,13 @@ where
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let contract_new_args = args.to_api_args()?;
let mut contract_new_args = args.to_api_args()?;
let recipient = slatepack_recipient(args.counterparty_addr.as_deref())?;
set_proof_sender(
&mut contract_new_args.setup_args.proof_args,
recipient.as_ref(),
None,
)?;
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| {
@@ -1799,6 +1859,10 @@ pub struct ContractSetupArgs {
pub fee_rate: Option<u32>,
/// Override the output Slatepack file
pub outfile: Option<String>,
/// Early payment proof type
pub proof_type: Option<ProofType>,
/// Early payment proof memo
pub memo: Option<PaymentMemo>,
// Future features
/// Whether we should automatically sign a receive of any value
@@ -1841,6 +1905,11 @@ impl ContractSetupArgs {
make_outputs: self.make_outputs.clone(),
..Default::default()
},
proof_args: contract_proof_args(
self.proof_type,
self.memo.clone(),
self.receive.unwrap_or(0) > 0,
)?,
..Default::default()
})
}
@@ -1857,8 +1926,7 @@ where
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
// Args for signing are just setup args
let contract_sign_args = args.to_api_args()?;
let mut 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();
@@ -1867,6 +1935,12 @@ where
.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))?;
// Bind the proof to the Slatepack sender; --encrypt-for is only the fallback
set_proof_sender(
&mut contract_sign_args.proof_args,
sender.as_ref(),
recipient.as_ref(),
)?;
// 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();
@@ -2068,7 +2142,7 @@ mod contract_tests {
fn contract_sign_args() {
let args = ContractSetupArgs {
counterparty_addr: None,
receive: None,
receive: Some(1),
send: None,
as_json: false,
use_inputs: Some("commitment".to_string()),
@@ -2077,13 +2151,50 @@ mod contract_tests {
fee_rate: Some(2),
outfile: None,
add_outputs: false,
proof_type: Some(ProofType::Invoice),
memo: Some(PaymentMemo::new("payment".into()).unwrap()),
};
let api_args = args.to_api_args().unwrap();
let mut api_args = args.to_api_args().unwrap();
let key = SigningKey::from_bytes(&[1; 32]);
let sender = SlatepackAddress {
hrp: "tgrin".to_string(),
pub_key: VerifyingKey::from(&key),
};
let fallback = SlatepackAddress {
hrp: "tgrin".to_string(),
pub_key: VerifyingKey::from(&SigningKey::from_bytes(&[2; 32])),
};
set_proof_sender(&mut api_args.proof_args, Some(&sender), Some(&fallback)).unwrap();
assert_eq!(api_args.fee_rate, Some(2));
assert_eq!(api_args.proof_args.proof_type, ProofType::Invoice);
assert_eq!(api_args.proof_args.sender_address, Some(sender.pub_key));
assert_eq!(
api_args.proof_args.memo.as_ref().map(PaymentMemo::as_str),
Some("payment")
);
assert_eq!(
api_args.selection_args.use_inputs.as_deref(),
Some("commitment")
);
let mut invalid = args;
invalid.receive = None;
assert!(matches!(
invalid.to_api_args(),
Err(Error::ArgumentError(message))
if message == "Early payment proofs require a positive --receive amount"
));
invalid.receive = Some(0);
assert!(matches!(
invalid.to_api_args(),
Err(Error::ArgumentError(message))
if message == "Early payment proofs require a positive --receive amount"
));
invalid.proof_type = None;
assert!(matches!(
invalid.to_api_args(),
Err(Error::ArgumentError(message)) if message == "--memo requires --proof-type"
));
}
#[test]
@@ -2102,8 +2213,23 @@ mod contract_tests {
fee_rate: None,
outfile: None,
add_outputs: false,
proof_type: Some(ProofType::SenderNonce),
memo: Some(PaymentMemo::new("payment".into()).unwrap()),
};
let api_args = args.to_api_args().unwrap();
assert_eq!(
api_args.setup_args.proof_args.proof_type,
ProofType::SenderNonce
);
assert_eq!(
api_args
.setup_args
.proof_args
.memo
.as_ref()
.map(PaymentMemo::as_str),
Some("payment")
);
assert_eq!(
api_args.setup_args.selection_args.use_inputs.as_deref(),
Some("commitment")
@@ -27,7 +27,9 @@ use grin_wallet_libwallet as libwallet;
use grin_util::secp::{Secp256k1, Signature};
use impls::test_framework::{self};
use libwallet::contract::my_fee_contribution;
use libwallet::contract::types::{ContractNewArgsAPI, ContractSetupArgsAPI, ProofType};
use libwallet::contract::types::{
ContractNewArgsAPI, ContractSetupArgsAPI, PaymentMemo, ProofType,
};
use libwallet::{Slate, SlateState, Slatepacker, SlatepackerArgs, TxLogEntryType};
use std::sync::atomic::Ordering;
use std::thread;
@@ -94,6 +96,7 @@ fn contract_early_proofs_rsr_test_impl(
// Proofs are opt-in; enable and supply the sender address.
args.setup_args.proof_args.suppress_proof = false;
args.setup_args.proof_args.proof_type = proof_type;
args.setup_args.proof_args.memo = Some(PaymentMemo::new("RSR payment".into())?);
args.setup_args.proof_args.sender_address = sender_address;
slate = api.contract_new(m, args)?;
recipient_address = Some(api.get_slatepack_address(recv_mask, 0)?.pub_key);
@@ -223,6 +226,10 @@ fn contract_early_proofs_rsr_test_impl(
let early_proof = early_proof.unwrap();
assert_eq!(early_proof.proof_type, proof_type);
assert_eq!(early_proof.amount, 5_000_000_000);
assert_eq!(
early_proof.memo.as_ref().map(PaymentMemo::as_str),
Some("RSR payment")
);
assert_eq!(
early_proof
.witness_data
@@ -26,7 +26,7 @@ use grin_wallet_libwallet as libwallet;
use impls::test_framework::{self};
use libwallet::contract::my_fee_contribution;
use libwallet::contract::types::{ContractNewArgsAPI, ContractSetupArgsAPI};
use libwallet::contract::types::{ContractNewArgsAPI, ContractSetupArgsAPI, PaymentMemo};
use libwallet::{NodeVersionInfo, Slate, SlateState, Slatepacker, SlatepackerArgs, TxLogEntryType};
use std::sync::atomic::Ordering;
use std::thread;
@@ -112,6 +112,7 @@ fn contract_early_proofs_srs_test_impl(test_dir: &'static str) -> Result<(), lib
};
// Proofs are opt-in; enable and supply the sender address.
args.proof_args.suppress_proof = false;
args.proof_args.memo = Some(PaymentMemo::new("SRS payment".into())?);
args.proof_args.sender_address = sender_address;
slate = api.contract_sign(m, &slate, args)?;
recipient_address = Some(api.get_slatepack_address(recv_mask, 0)?.pub_key);
@@ -224,6 +225,10 @@ fn contract_early_proofs_srs_test_impl(test_dir: &'static str) -> Result<(), lib
let early_proof = early_proof.unwrap();
assert_eq!(early_proof.amount, 5_000_000_000);
assert_eq!(
early_proof.memo.as_ref().map(PaymentMemo::as_str),
Some("SRS payment")
);
let early_proof_json = serde_json::to_string(&early_proof).unwrap();
// Should have all proof fields filled out
+7 -8
View File
@@ -78,14 +78,13 @@ account selected with `--account`.
* Only one or two participants are supported. Larger contracts remain disabled because of
the [known multi-party attack](https://forum.grin.mw/t/grin-wallet-contract-prototype/9745/18)
* Early payment proofs are only implemented for contracts and are only available through
the API. Invoice proofs support both flows; sender-nonce proofs support RSR. Both require
the experimental Slate V5 format. The full proposal is described in
[Early Payment Proofs](https://github.com/mimblewimble/grin-rfcs/pull/70). Proof data is
stored in the wallet database and cannot be recovered from the wallet seed alone
* There are no contract-specific history, lookup or transport commands. Payment proof
memos cannot be set through the contract API or CLI. Early proofs support UTF-8 memos
up to 1024 bytes and bind their Blake2b hash
* Early payment proofs are available for contracts through the API and CLI. Use `--proof-type`
and optionally `--memo` (up to 1024 bytes of UTF-8 text). The proof binds the memo's Blake2b hash
* Invoice proofs work with SRS and RSR. Sender-nonce proofs only work with RSR. Both need
experimental Slate V5; see
[Early Payment Proofs](https://github.com/mimblewimble/grin-rfcs/pull/70)
* Proof data is stored in the wallet database and cannot be restored from the seed
* There are no contract-specific history, lookup or transport commands
* If writing the signed transaction file fails, the wallet state has already been saved.
Cancelling the transaction releases the locked inputs
+1 -1
View File
@@ -48,7 +48,7 @@ Separating side effects until the 'save_step' part would make these functions mu
- Choose the sender derivation path explicitly and keep encrypted outgoing files
identifiable locally.
- Decide whether `target_slate_version` should control Slatepack output or be removed.
- Add contract history, lookup by id, transport support and configurable proof memos.
- Add contract history, lookup and transport.
- Decide whether the foreign JSON-RPC API should expose `new` and `sign`.
- Add full API and RPC examples once the contract interface is stable.
- Separate side effects out from the computation, as described above.
+1
View File
@@ -513,6 +513,7 @@ where
let index = slate.find_index_matching_context(&keychain, context)?;
let mut early_proof = EarlyPaymentProof::from_slate(&slate, index, proof_args.sender_address)?;
early_proof.proof_type = proof_args.proof_type;
early_proof.memo = proof_args.memo.clone();
let derivation_index = match context.payment_proof_derivation_index {
Some(i) => i,
None => 0,
+4 -1
View File
@@ -16,7 +16,7 @@
use crate::error::Error;
use crate::grin_core::libtx::secp_ser;
pub use crate::slate::PaymentProofType as ProofType;
pub use crate::slate::{PaymentMemo, PaymentProofType as ProofType};
use crate::slate_versions::ser as dalek_ser;
use ed25519_dalek::VerifyingKey as DalekPublicKey;
@@ -95,6 +95,8 @@ pub struct ProofArgs {
pub suppress_proof: bool,
/// Requested early payment proof type
pub proof_type: ProofType,
/// Memo used when this step creates the payment proof
pub memo: Option<PaymentMemo>,
/// 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>,
@@ -107,6 +109,7 @@ impl Default for ProofArgs {
// invoice promise with no sender address, failing with NoSenderAddressProvided.
suppress_proof: true,
proof_type: ProofType::Invoice,
memo: None,
sender_address: None,
}
}
+21
View File
@@ -517,6 +517,17 @@ subcommands:
short: u
long: outfile
takes_value: true
- proof-type:
help: Create an early payment proof of this type (requires a positive --receive amount and --encrypt-for)
long: proof-type
possible_values:
- invoice
- sender-nonce
takes_value: true
- memo:
help: UTF-8 memo to bind to the early payment proof (max 1024 bytes)
long: memo
takes_value: true
- sign:
about: Sign a contract
args:
@@ -573,6 +584,16 @@ subcommands:
help: Don't broadcast the transaction if it was finalized
long: no-broadcast
takes_value: false
- proof-type:
help: Create an early payment proof of this type (requires a positive --receive amount and a Slatepack sender or --encrypt-for)
long: proof-type
possible_values:
- invoice
takes_value: true
- memo:
help: UTF-8 memo to bind to the early payment proof (max 1024 bytes)
long: memo
takes_value: true
- view:
about: View a contract
args:
+29
View File
@@ -27,6 +27,7 @@ use grin_wallet_api::Owner;
use grin_wallet_config::{GlobalWalletConfig, TorConfig, WalletConfig};
use grin_wallet_controller::{command, Error};
use grin_wallet_impls::{DefaultLCProvider, DefaultWalletImpl};
use grin_wallet_libwallet::contract::types::{PaymentMemo, ProofType};
use grin_wallet_libwallet::{self, Slate, SlatepackAddress, SlatepackArmor};
use grin_wallet_libwallet::{IssueInvoiceTxArgs, NodeClient, WalletInst, WalletLCProvider};
use linefeed::terminal::Signal;
@@ -1016,6 +1017,28 @@ fn parse_contract_fee_rate(args: &ArgMatches) -> Result<Option<u32>, ParseError>
.map_err(|_| ParseError::ArgumentError("Contract fee rate is too large".to_string()))
}
fn parse_contract_proof(
args: &ArgMatches,
) -> Result<(Option<ProofType>, Option<PaymentMemo>), ParseError> {
let proof_type = match args.value_of("proof-type") {
Some("invoice") => Some(ProofType::Invoice),
Some("sender-nonce") => Some(ProofType::SenderNonce),
Some(value) => {
return Err(ParseError::ArgumentError(format!(
"Unsupported proof type: {}",
value
)))
}
None => None,
};
let memo = args
.value_of("memo")
.map(|memo| PaymentMemo::new(memo.to_string()))
.transpose()
.map_err(|e| ParseError::ArgumentError(e.to_string()))?;
Ok((proof_type, memo))
}
pub fn parse_contract_new_args(
args: &ArgMatches,
account: &String,
@@ -1048,6 +1071,7 @@ pub fn parse_contract_new_args(
"minimum_confirmations",
)?;
let fee_rate = parse_contract_fee_rate(args)?;
let (proof_type, memo) = parse_contract_proof(args)?;
let outfile = parse_optional(args, "outfile")?;
let ttl_blocks = match args.value_of("ttl_blocks") {
Some(value) => {
@@ -1119,6 +1143,8 @@ pub fn parse_contract_new_args(
fee_rate,
ttl_blocks,
outfile,
proof_type,
memo,
})
}
@@ -1149,6 +1175,7 @@ pub fn parse_contract_setup_args(
None => None,
};
let fee_rate = parse_contract_fee_rate(args)?;
let (proof_type, memo) = parse_contract_proof(args)?;
let outfile = parse_optional(args, "outfile")?;
let no_payjoin = args.is_present("no-payjoin");
let use_inputs = match args.value_of("use-inputs") {
@@ -1194,6 +1221,8 @@ pub fn parse_contract_setup_args(
minimum_confirmations,
fee_rate,
outfile,
proof_type,
memo,
})
}
+52 -3
View File
@@ -29,6 +29,7 @@ use std::time::Duration;
use grin_core::core::Transaction;
use grin_keychain::ExtKeychain;
use grin_wallet_impls::DefaultLCProvider;
use grin_wallet_libwallet::contract::types::{PaymentMemo, ProofType};
mod common;
use common::{clean_output_dir, execute_command, initial_setup_wallet, instantiate_wallet, setup};
@@ -164,7 +165,7 @@ 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
// Wallet 2 can also view a proof-bearing slatepack encrypted for its address
let mut recipient = None;
grin_wallet_controller::controller::owner_single_use(
wallet2.clone(),
@@ -183,12 +184,17 @@ fn contract_command_test_impl(test_dir: &str) -> Result<(), grin_wallet_controll
"password1",
"contract",
"new",
"--send",
"--receive",
"1",
"--no-payjoin",
"--min_conf",
"1",
"--encrypt-for",
&recipient,
"--proof-type",
"sender-nonce",
"--memo",
"CLI payment",
];
execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?;
@@ -279,7 +285,7 @@ fn parses_contract_options() {
"grin-wallet",
"contract",
"new",
"--send",
"--receive",
"1",
"--min_conf",
"3",
@@ -289,6 +295,10 @@ fn parses_contract_options() {
"20",
"--outfile",
"new.slatepack",
"--proof-type",
"sender-nonce",
"--memo",
"new payment",
])
.unwrap();
let contract = args.subcommand_matches("contract").unwrap();
@@ -299,6 +309,36 @@ fn parses_contract_options() {
assert_eq!(parsed.fee_rate, Some(2));
assert_eq!(parsed.ttl_blocks, Some(20));
assert_eq!(parsed.outfile.as_deref(), Some("new.slatepack"));
assert_eq!(parsed.proof_type, Some(ProofType::SenderNonce));
assert_eq!(
parsed.memo.as_ref().map(PaymentMemo::as_str),
Some("new payment")
);
let memo = "a".repeat(PaymentMemo::MAX_LEN + 1);
let args = app
.clone()
.get_matches_from_safe(vec![
"grin-wallet",
"contract",
"new",
"--receive",
"1",
"--proof-type",
"invoice",
"--memo",
&memo,
])
.unwrap();
let new_args = args
.subcommand_matches("contract")
.unwrap()
.subcommand_matches("new")
.unwrap();
assert!(matches!(
grin_wallet::cmd::wallet_args::parse_contract_new_args(new_args, &account),
Err(grin_wallet::cmd::wallet_args::ParseError::ArgumentError(message))
if message.contains("Payment memo exceeds 1024 bytes")
));
let expected = grin_wallet_libwallet::contract::types::DEFAULT_MINIMUM_CONFIRMATIONS;
let args = app
@@ -384,6 +424,10 @@ fn parses_contract_options() {
"2",
"--outfile",
"sign.slatepack",
"--proof-type",
"invoice",
"--memo",
"sign payment",
])
.unwrap();
let contract = args.subcommand_matches("contract").unwrap();
@@ -393,6 +437,11 @@ fn parses_contract_options() {
assert_eq!(parsed.fee_rate, Some(2));
assert_eq!(parsed.outfile.as_deref(), Some("sign.slatepack"));
assert_eq!(parsed.use_inputs.as_deref(), Some("commitment"));
assert_eq!(parsed.proof_type, Some(ProofType::Invoice));
assert_eq!(
parsed.memo.as_ref().map(PaymentMemo::as_str),
Some("sign payment")
);
let args = app
.get_matches_from_safe(vec![