Skip to content

Commit

Permalink
replaced test_mempool_accept's param with Vec<u8>
Browse files Browse the repository at this point in the history
  • Loading branch information
BitcoinZavior committed Sep 30, 2023
1 parent e2c1796 commit 0b0cc4f
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 38 deletions.
Binary file modified pdk-python/src/pdkpython/libpdk_ffi.dylib
Binary file not shown.
24 changes: 2 additions & 22 deletions pdk-python/src/pdkpython/pdk_ffi.py
Original file line number Diff line number Diff line change
Expand Up @@ -3028,7 +3028,7 @@ def write(cls, cb, buf):
# Declaration and FfiConverters for CanBroadcast Callback Interface

class CanBroadcast:
def test_mempool_accept(self, tx_hex: "typing.List[str]"):
def test_mempool_accept(self, tx: "typing.List[int]"):
raise NotImplementedError


Expand All @@ -3037,7 +3037,7 @@ def py_foreignCallbackCallbackInterfaceCanBroadcast(handle, method, args_data, a

def invoke_test_mempool_accept(python_callback, args_stream, buf_ptr):
def makeCall():return python_callback.test_mempool_accept(
FfiConverterSequenceString.read(args_stream)
FfiConverterSequenceUInt8.read(args_stream)
)

def makeCallAndHandleReturn():
Expand Down Expand Up @@ -3349,26 +3349,6 @@ def read(cls, buf):



class FfiConverterSequenceString(FfiConverterRustBuffer):
@classmethod
def write(cls, value, buf):
items = len(value)
buf.writeI32(items)
for item in value:
FfiConverterString.write(item, buf)

@classmethod
def read(cls, buf):
count = buf.readI32()
if count < 0:
raise InternalError("Unexpected negative sequence length")

return [
FfiConverterString.read(buf) for i in range(count)
]



class FfiConverterMapUInt64TypeOutPoint(FfiConverterRustBuffer):
@classmethod
def write(cls, items, buf):
Expand Down
2 changes: 1 addition & 1 deletion src/pdk_ffi.udl
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ interface Transaction{

callback interface CanBroadcast {
[Throws=PayjoinError]
boolean test_mempool_accept(sequence<string> tx_hex);
boolean test_mempool_accept( sequence<u8> tx );
};

interface UncheckedProposal{
Expand Down
39 changes: 29 additions & 10 deletions src/receive.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
use crate::{
transaction::{PartiallySignedTransaction, Transaction},
Address, OutPoint, PayjoinError, ScriptBuf, TxOut,
use std::{
collections::HashMap,
sync::{Arc, Mutex, MutexGuard},
};

use payjoin::receive::{
MaybeInputsOwned as PdkMaybeInputsOwned, MaybeInputsSeen as PdkMaybeInputsSeen,
MaybeMixedInputScripts as PdkMaybeMixedInputScripts, OutputsUnknown as PdkOutputsUnknown,
PayjoinProposal as PdkPayjoinProposal, UncheckedProposal as PdkUncheckedProposal,
};
use payjoin::Error as PdkError;
use std::{
collections::HashMap,
sync::{Arc, Mutex, MutexGuard},

use crate::{
transaction::{PartiallySignedTransaction, Transaction},
Address, OutPoint, PayjoinError, ScriptBuf, TxOut,
};

pub trait CanBroadcast: Send + Sync {
fn test_mempool_accept(&self, tx_hex: Vec<String>) -> Result<bool, PayjoinError>;
fn test_mempool_accept(&self, tx: Vec<u8>) -> Result<bool, PayjoinError>;
}

#[derive(Clone)]
Expand All @@ -37,6 +39,7 @@ impl payjoin::receive::Headers for Headers {
self.0.get(key).map(|e| e.as_str())
}
}

/// The sender’s original PSBT and optional parameters
///
/// This type is used to proces the request. It is returned by UncheckedProposal::from_request().
Expand All @@ -51,6 +54,7 @@ impl From<PdkUncheckedProposal> for UncheckedProposal {
Self { internal: Mutex::new(Some(value)) }
}
}

impl UncheckedProposal {
pub fn get_configuration(
&self,
Expand Down Expand Up @@ -96,9 +100,9 @@ impl UncheckedProposal {
) -> Result<Arc<MaybeInputsOwned>, PayjoinError> {
let (proposal, _) = Self::get_configuration(self);
let res = proposal.unwrap().check_can_broadcast(|tx| {
let raw_tx = hex::encode(payjoin::bitcoin::consensus::encode::serialize(&tx));
let mempool_results = can_broadcast.test_mempool_accept(vec![raw_tx]);
match mempool_results {
match can_broadcast
.test_mempool_accept(payjoin::bitcoin::consensus::encode::serialize(&tx))
{
Ok(e) => Ok(e),
Err(e) => Err(PdkError::Server(e.into())),
}
Expand Down Expand Up @@ -127,6 +131,7 @@ impl UncheckedProposal {
pub struct MaybeInputsOwned {
internal: Mutex<Option<PdkMaybeInputsOwned>>,
}

impl From<PdkMaybeInputsOwned> for MaybeInputsOwned {
fn from(value: PdkMaybeInputsOwned) -> Self {
MaybeInputsOwned { internal: Mutex::new(Some(value)) }
Expand All @@ -136,6 +141,7 @@ impl From<PdkMaybeInputsOwned> for MaybeInputsOwned {
pub trait IsScriptOwned: Send + Sync {
fn is_owned(&self, script: Arc<ScriptBuf>) -> Result<bool, PayjoinError>;
}

impl MaybeInputsOwned {
fn get_owned_inputs(
&self,
Expand Down Expand Up @@ -169,11 +175,13 @@ impl MaybeInputsOwned {
pub struct MaybeMixedInputScripts {
internal: Mutex<Option<PdkMaybeMixedInputScripts>>,
}

impl From<PdkMaybeMixedInputScripts> for MaybeMixedInputScripts {
fn from(value: PdkMaybeMixedInputScripts) -> Self {
MaybeMixedInputScripts { internal: Mutex::new(Some(value)) }
}
}

impl MaybeMixedInputScripts {
fn get_input_scripts(
&self,
Expand All @@ -192,6 +200,7 @@ impl MaybeMixedInputScripts {
}
}
}

pub trait IsOutputKnown {
fn is_known(&self, outpoint: OutPoint) -> Result<bool, PayjoinError>;
}
Expand All @@ -202,11 +211,13 @@ pub trait IsOutputKnown {
pub struct MaybeInputsSeen {
internal: Mutex<Option<PdkMaybeInputsSeen>>,
}

impl From<PdkMaybeInputsSeen> for MaybeInputsSeen {
fn from(value: PdkMaybeInputsSeen) -> Self {
MaybeInputsSeen { internal: Mutex::new(Some(value)) }
}
}

impl MaybeInputsSeen {
fn get_inputs(&self) -> (Option<PdkMaybeInputsSeen>, MutexGuard<Option<PdkMaybeInputsSeen>>) {
let mut data_guard = self.internal.lock().unwrap();
Expand All @@ -229,13 +240,15 @@ impl MaybeInputsSeen {
}
}
}

/// The receiver has not yet identified which outputs belong to the receiver.
///
/// Only accept PSBTs that send us money. Identify those outputs with identify_receiver_outputs() to proceed
pub struct OutputsUnknown {
internal: Mutex<Option<PdkOutputsUnknown>>,
}

impl From<PdkOutputsUnknown> for OutputsUnknown {
fn from(value: PdkOutputsUnknown) -> Self {
OutputsUnknown { internal: Mutex::new(Some(value)) }
Expand Down Expand Up @@ -272,11 +285,13 @@ impl OutputsUnknown {
pub struct PayjoinProposal {
internal: Mutex<Option<PdkPayjoinProposal>>,
}

impl From<PdkPayjoinProposal> for PayjoinProposal {
fn from(value: PdkPayjoinProposal) -> Self {
PayjoinProposal { internal: Mutex::new(Some(value)) }
}
}

impl PayjoinProposal {
fn get_proposal(&self) -> Option<PdkPayjoinProposal> {
let mut data_guard = self.internal.lock().unwrap();
Expand Down Expand Up @@ -392,13 +407,17 @@ mod test {
let proposal = get_proposal_from_test_vector();
assert!(proposal.is_ok(), "OriginalPSBT should be a valid request");
}

struct MockScriptOwned {}

struct MockOutputOwned {}

impl IsOutputKnown for MockOutputOwned {
fn is_known(&self, _: OutPoint) -> Result<bool, PayjoinError> {
Ok(false)
}
}

impl IsScriptOwned for MockScriptOwned {
fn is_owned(&self, script: Arc<ScriptBuf>) -> Result<bool, PayjoinError> {
{
Expand Down
11 changes: 6 additions & 5 deletions src/test/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use log::{debug, log_enabled, Level};
use payjoin::bitcoin;
use payjoin::bitcoin::base64;

use crate::bitcoin::consensus::encode::serialize_hex;
use crate::receive::{Headers, IsOutputKnown, IsScriptOwned, UncheckedProposal};
use crate::send::{Configuration, Request};
use crate::transaction::PartiallySignedTransaction;
Expand Down Expand Up @@ -42,14 +43,14 @@ fn integration_test() {
);

assert_eq!(
payjoin::bitcoin::Amount::from_btc(50.0).unwrap(),
bitcoin::Amount::from_btc(50.0).unwrap(),
sender.get_balances().unwrap().mine.trusted,
"sender doesn't own bitcoin"
);

// Receiver creates the payjoin URI
let pj_receiver_address = receiver.get_new_address(None, None).unwrap().assume_checked();
let amount = payjoin::bitcoin::Amount::from_btc(1.0).unwrap();
let amount = bitcoin::Amount::from_btc(1.0).unwrap();
let pj_uri_string = format!(
"{}?amount={}&pj=https://example.com",
pj_receiver_address.to_qr_uri(),
Expand All @@ -67,7 +68,7 @@ fn integration_test() {
debug!("outputs: {:?}", outputs);
let options = bitcoincore_rpc::json::WalletCreateFundedPsbtOptions {
lock_unspent: Some(true),
fee_rate: Some(payjoin::bitcoin::Amount::from_sat(2000)),
fee_rate: Some(bitcoin::Amount::from_sat(2000)),
..Default::default()
};
let psbt = sender
Expand Down Expand Up @@ -206,8 +207,8 @@ fn handle_pj_request(
struct TestBroadcast(Arc<bitcoincore_rpc::Client>);

impl crate::receive::CanBroadcast for TestBroadcast {
fn test_mempool_accept(&self, tx_hex: Vec<String>) -> Result<bool, PayjoinError> {
match self.0.test_mempool_accept(&tx_hex) {
fn test_mempool_accept(&self, tx: Vec<u8>) -> Result<bool, PayjoinError> {
match self.0.test_mempool_accept(&[serialize_hex(&tx)]) {
Ok(e) => Ok(match e.first() {
Some(e) => e.allowed,
None => panic!("No Mempool Result"),
Expand Down

0 comments on commit 0b0cc4f

Please sign in to comment.