Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ members = [
"spdk-wallet",
"silentpayments",
"scanners/local",
"psbt"
]
resolver = "3"

Expand All @@ -15,15 +16,16 @@ spdk-wallet = { path = "spdk-wallet" }
silentpayments = { path = "silentpayments" }
backend-blindbit-v1 = { path = "chain/blindbit-v1" }
local-scanner = { path = "scanners/local" }
psbt = { path = "psbt" }

# Core dependencies - shared across crates
anyhow = "1.0"
bech32 = "0.9"
serde = { version = "1.0.188", features = ["derive"] }
serde_json = "1.0.107"
bip321 = { git = "https://gitlab.com/Sosthene00/bark.git", rev = "83ab79264159869503b16fa475e0ed61ffa33174", default-features = false }
bitcoin = { version = "0.32.8", features = ["serde", "rand", "base64"] }
bitcoin_hashes = "0.13.0"
bip321 = { git="https://gitlab.com/Sosthene00/bark.git", rev="83ab79264159869503b16fa475e0ed61ffa33174", default-features = false }
bitcoin = { version = "0.32.8", features = ["serde", "rand-std", "base64"] }
bitcoin_hashes = "0.14"
rayon = "1.10.0"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
futures = "0.3"
Expand All @@ -36,6 +38,21 @@ reqwest = { version = "0.12.4", features = [
"rustls-tls",
"gzip",
], default-features = false }
psbt-v2 = { git = "https://gitea.bitcoin.ninja/sosthene/rust-psbt.git", rev = "e7c2264c50d0f5c0b82c87af7884fb1f9296b971", features = ["silent-payments", "miniscript"] }
# DLEQ (BIP-374) backend decision (2026-09):
# We use rust-dleq's pure-Rust `standalone` backend (the default in `silentpayments`
# and `psbt`), pinned to this fork. It is verified against the official BIP-374
# test vectors (byte-identical proofs; all negative cases reject).
#
# The `dleq-native` path (vendored libsecp256k1) is deferred: it builds its own
# libsecp256k1.a alongside secp256k1-sys's, and unifying them would mean forking
# rust-secp256k1 and hand-porting its context/memory patches onto the moving
# libsecp PR #1802 branch — not worth it for a stopgap.
#
# Revisit when secp256k1 PR #1802 (or #1651) merges and rust-secp256k1 ships the
# DLEQ module. Also watch bips#2262 (challenge `e` as scalar) — if it lands, both
# the C and standalone impls plus the test vectors change.
rust-dleq = { git = "https://github.com/Sosthene00/rust-dleq.git", rev = "097644a14d87c454e9bd9895de2e60992ff1ba93", default-features = false }
secp256k1 = { version = "0.29.0" }

[workspace.package]
Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@
> [!WARNING]
> SPDK currently relies on cryptography that is not professionally reviewed. Be mindful of this when using SPDK with real funds.

SPDK is a library that can be used to build silent payment-based wallets. It consists of 4 sub-crates:
SPDK is a library that can be used to build silent payment-based wallets. It consists of these sub-crates:

- **spdk-core**, an internal library that is used for organizing crates within this workspace.
- Defines a `ChainBackend` trait, that can be used be consumers (e.g. backend-blindbit-v1) to provide chain data.
- Defines an `Updater` trait, that can be used by wallets to receive updates while scanning the chain.
- **backend-blindbit-v1**, a chain backend that implements a [bip352 light client](https://github.com/setavenger/BIP0352-light-client-specification).
- **local-scanner**, an implementation of the `Scanner` trait that scans through a `ChainBackend`.
- **silentpayments**, the cryptography library that implements silent-payment related operations. Note: although this library passes the test vectors from the BIP, it is not professionally reviewed for security.
- **spdk-wallet**, a high-level crate that implements a `Client` and a `Scanner`. These can be used to scan the chain for incoming payments, and creating and signing transactions.
- **psbt**, BIP-375 extensions (`signer`, `extractor`) for the `psbt-v2` crate. `Psbt` and the upstream PSBT roles are in `psbt-v2`.
- **spdk-wallet**, a high-level crate that implements a `Client` and a `Scanner`. These can be used to scan the chain for incoming payments, and creating and signing transactions. It reexports `signer`, `extractor`, and `psbt-v2`.

## How to use

Expand Down
24 changes: 24 additions & 0 deletions psbt/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[package]
name = "psbt"
version = "0.1.0"
edition = "2021"
repository.workspace = true

[lib]
crate-type = ["lib", "staticlib", "cdylib"]

[features]
default = ["dleq-standalone"]
dleq-native = ["rust-dleq/native"]
dleq-standalone = ["rust-dleq/standalone"]

[dependencies]
bitcoin.workspace = true
silentpayments.workspace = true
secp256k1.workspace = true
psbt-v2.workspace = true
rust-dleq.workspace = true

[dev-dependencies]
serde.workspace = true
serde_json.workspace = true
151 changes: 151 additions & 0 deletions psbt/src/extractor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
//! BIP-375 Transaction Extractor.
//!
//! BIP-375: "For silent payment capable PSBTs, the transaction extractor should compute all
//! output scripts for silent payment codes and verify they are correct using the ECDH shares and
//! DLEQ proofs, otherwise fail."
//!
//! `psbt_v2::Extractor` leaves that check to the caller, because it needs BIP-352 output
//! derivation and BIP-374 proof verification. This role performs it before extracting.

use std::fmt;

use bitcoin::Transaction;
use psbt_v2::{ExtractError, ExtractTxFeeRateError, Extractor, Psbt};
use secp256k1::{Secp256k1, Signing, Verification};
use silentpayments::TransactionInputs;
use silentpayments::utils::OutPoint as SpOutPoint;
use silentpayments::utils::receiving::get_pubkey_from_input;

use super::signer::{SpSignerError, derive_sp_output_scripts_from_inputs, funding_output};

#[derive(Debug)]
pub enum SpExtractorError {
/// The public key of a finalized input could not be recovered from its scriptSig and
/// witness.
InputPubkey {
vin: usize,
error: silentpayments::Error,
},
/// The silent payment output scripts could not be derived from the ECDH shares.
Derive(SpSignerError),
/// A silent payment output does not match the script derived from the ECDH shares.
OutputScriptMismatch { index: usize },
/// rust-psbt refused to build an extractor for the PSBT.
Extractor(ExtractError),
/// rust-psbt failed to extract the transaction.
ExtractTx(ExtractTxFeeRateError),
}

impl fmt::Display for SpExtractorError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use SpExtractorError as E;
match self {
E::InputPubkey { vin, error } => {
write!(f, "input {vin}: cannot recover its public key: {error}")
}
E::Derive(e) => write!(f, "cannot derive silent payment output scripts: {e}"),
E::OutputScriptMismatch { index } => write!(
f,
"silent payment output {index} does not match the script derived from the ECDH shares"
),
E::Extractor(e) => write!(f, "cannot extract: {e}"),
E::ExtractTx(e) => write!(f, "cannot extract the transaction: {e}"),
}
}
}

impl std::error::Error for SpExtractorError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use SpExtractorError as E;
match self {
E::InputPubkey { error, .. } => Some(error),
E::Derive(e) => Some(e),
E::Extractor(e) => Some(e),
E::ExtractTx(e) => Some(e),
E::OutputScriptMismatch { .. } => None,
}
}
}

impl From<SpSignerError> for SpExtractorError {
fn from(value: SpSignerError) -> Self {
Self::Derive(value)
}
}

pub trait SpExtractorExt {
/// Derives every silent payment output script from the ECDH shares and DLEQ proofs and
/// checks it against the PSBT, as BIP-375 requires of the Transaction Extractor.
///
/// The Input Finalizer clears the fields the Signer reads input public keys from, so they
/// are recovered from the final scriptSig and witness, as a BIP-352 receiver does.
fn verify_sp_output_scripts<C>(&self, secp: &Secp256k1<C>) -> Result<(), SpExtractorError>
where
C: Signing + Verification;

/// Verifies the silent payment output scripts, then extracts the transaction with
/// `psbt_v2::Extractor`.
fn extract_tx<C>(self, secp: &Secp256k1<C>) -> Result<Transaction, SpExtractorError>
where
C: Signing + Verification;
}

impl SpExtractorExt for Psbt {
fn verify_sp_output_scripts<C>(&self, secp: &Secp256k1<C>) -> Result<(), SpExtractorError>
where
C: Signing + Verification,
{
if self
.outputs
.iter()
.all(|output| output.sp_v0_info.is_none())
{
return Ok(());
}

let mut transaction_inputs = TransactionInputs::with_capacity(self.global.input_count.into());
for (vin, input) in self.inputs.iter().enumerate() {
let outpoint = SpOutPoint::from_txid_and_vout(
&input.previous_txid.to_string(),
input.spent_output_index.into(),
)
.map_err(SpSignerError::from)?;
let spk = &funding_output(input)
.map_err(SpSignerError::from)?
.script_pubkey;
let script_sig = input
.final_script_sig
.as_ref()
.map(|script| script.as_bytes())
.unwrap_or_default();
let witness = input
.final_script_witness
.as_ref()
.map(|witness| witness.to_vec())
.unwrap_or_default();
let pubkey = get_pubkey_from_input(script_sig, &witness, spk.as_bytes())
.map_err(|error| SpExtractorError::InputPubkey { vin, error })?;
transaction_inputs.push(outpoint, spk.to_bytes(), pubkey);
}

for (index, script) in
derive_sp_output_scripts_from_inputs(self, secp, &transaction_inputs)?
{
if self.outputs[index].script_pubkey != script {
return Err(SpExtractorError::OutputScriptMismatch { index });
}
}
Ok(())
}

fn extract_tx<C>(self, secp: &Secp256k1<C>) -> Result<Transaction, SpExtractorError>
where
C: Signing + Verification,
{
self.verify_sp_output_scripts(secp)?;
Extractor::new(self)
.map_err(SpExtractorError::Extractor)?
.extract_tx()
.map_err(SpExtractorError::ExtractTx)
}
}
12 changes: 12 additions & 0 deletions psbt/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//! BIP-375 extensions for `psbt-v2` PSBTs.
//!
//! - [`signer`]: ECDH shares and silent-payment output derivation.
//! - [`extractor`]: output-script check before extraction.
//!
//! `Psbt` and the upstream signer, finalizer, and extractor types are in `psbt-v2`.
//!
//! A combiner for concurrent signers is not implemented. It would merge ECDH shares, DLEQ
//! proofs, and signatures, and reject conflicting values for the same field.

pub mod extractor;
pub mod signer;
Loading
Loading