bsv-sdk 0.3.2

Pure Rust implementation of the BSV Blockchain SDK
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Dispatch overhead benchmark: RPITIT vs async-trait for WalletInterface.
//!
//! Measures the per-call overhead of dynamic dispatch (async-trait with
//! `Pin<Box<dyn Future + Send>>`) vs static dispatch (RPITIT / direct call)
//! for wallet interface methods.
//!
//! This benchmark is part of the Phase 10 object-safety evaluation for
//! WalletInterface and WalletWire traits.

use async_trait::async_trait;
use criterion::{criterion_group, criterion_main, Criterion};
use std::time::Duration;

use bsv::wallet::error::WalletError;
use bsv::wallet::interfaces::{
    AbortActionArgs, AbortActionResult, AcquireCertificateArgs, Certificate, CreateActionArgs,
    CreateActionResult, CreateHmacArgs, CreateHmacResult, CreateSignatureArgs,
    CreateSignatureResult, DecryptArgs, DecryptResult, DiscoverByAttributesArgs,
    DiscoverByIdentityKeyArgs, DiscoverCertificatesResult, EncryptArgs, EncryptResult,
    GetHeaderArgs, GetHeaderResult, GetHeightResult, GetNetworkResult, GetPublicKeyArgs,
    GetPublicKeyResult, GetVersionResult, InternalizeActionArgs, InternalizeActionResult,
    ListActionsArgs, ListActionsResult, ListCertificatesArgs, ListCertificatesResult,
    ListOutputsArgs, ListOutputsResult, ProveCertificateArgs, ProveCertificateResult,
    RelinquishCertificateArgs, RelinquishCertificateResult, RelinquishOutputArgs,
    RelinquishOutputResult, RevealCounterpartyKeyLinkageArgs, RevealCounterpartyKeyLinkageResult,
    RevealSpecificKeyLinkageArgs, RevealSpecificKeyLinkageResult, SignActionArgs, SignActionResult,
    VerifyHmacArgs, VerifyHmacResult, VerifySignatureArgs, VerifySignatureResult, WalletInterface,
};
use bsv::wallet::types::Protocol;

// ---------------------------------------------------------------------------
// NoOpWallet: minimal WalletInterface impl returning default/empty results
// ---------------------------------------------------------------------------

struct NoOpWallet;

#[async_trait]
impl WalletInterface for NoOpWallet {
    async fn create_action(
        &self,
        _args: CreateActionArgs,
        _originator: Option<&str>,
    ) -> Result<CreateActionResult, WalletError> {
        Ok(CreateActionResult {
            txid: None,
            tx: None,
            no_send_change: vec![],
            send_with_results: vec![],
            signable_transaction: None,
        })
    }

    async fn sign_action(
        &self,
        _args: SignActionArgs,
        _originator: Option<&str>,
    ) -> Result<SignActionResult, WalletError> {
        Ok(SignActionResult {
            txid: None,
            tx: None,
            send_with_results: vec![],
        })
    }

    async fn abort_action(
        &self,
        _args: AbortActionArgs,
        _originator: Option<&str>,
    ) -> Result<AbortActionResult, WalletError> {
        Ok(AbortActionResult { aborted: true })
    }

    async fn list_actions(
        &self,
        _args: ListActionsArgs,
        _originator: Option<&str>,
    ) -> Result<ListActionsResult, WalletError> {
        Ok(ListActionsResult {
            total_actions: 0,
            actions: vec![],
        })
    }

    async fn internalize_action(
        &self,
        _args: InternalizeActionArgs,
        _originator: Option<&str>,
    ) -> Result<InternalizeActionResult, WalletError> {
        Ok(InternalizeActionResult { accepted: true })
    }

    async fn list_outputs(
        &self,
        _args: ListOutputsArgs,
        _originator: Option<&str>,
    ) -> Result<ListOutputsResult, WalletError> {
        Ok(ListOutputsResult {
            total_outputs: 0,
            beef: None,
            outputs: vec![],
        })
    }

    async fn relinquish_output(
        &self,
        _args: RelinquishOutputArgs,
        _originator: Option<&str>,
    ) -> Result<RelinquishOutputResult, WalletError> {
        Ok(RelinquishOutputResult { relinquished: true })
    }

    async fn get_public_key(
        &self,
        _args: GetPublicKeyArgs,
        _originator: Option<&str>,
    ) -> Result<GetPublicKeyResult, WalletError> {
        Ok(GetPublicKeyResult {
            public_key: bsv::primitives::public_key::PublicKey::from_private_key(
                &bsv::primitives::private_key::PrivateKey::from_hex("1").expect("valid hex"),
            ),
        })
    }

    async fn reveal_counterparty_key_linkage(
        &self,
        _args: RevealCounterpartyKeyLinkageArgs,
        _originator: Option<&str>,
    ) -> Result<RevealCounterpartyKeyLinkageResult, WalletError> {
        Err(WalletError::NotImplemented(
            "reveal_counterparty_key_linkage".into(),
        ))
    }

    async fn reveal_specific_key_linkage(
        &self,
        _args: RevealSpecificKeyLinkageArgs,
        _originator: Option<&str>,
    ) -> Result<RevealSpecificKeyLinkageResult, WalletError> {
        Err(WalletError::NotImplemented(
            "reveal_specific_key_linkage".into(),
        ))
    }

    async fn encrypt(
        &self,
        _args: EncryptArgs,
        _originator: Option<&str>,
    ) -> Result<EncryptResult, WalletError> {
        Ok(EncryptResult {
            ciphertext: vec![0u8; 32],
        })
    }

    async fn decrypt(
        &self,
        _args: DecryptArgs,
        _originator: Option<&str>,
    ) -> Result<DecryptResult, WalletError> {
        Ok(DecryptResult {
            plaintext: vec![0u8; 32],
        })
    }

    async fn create_hmac(
        &self,
        _args: CreateHmacArgs,
        _originator: Option<&str>,
    ) -> Result<CreateHmacResult, WalletError> {
        Ok(CreateHmacResult {
            hmac: vec![0u8; 32],
        })
    }

    async fn verify_hmac(
        &self,
        _args: VerifyHmacArgs,
        _originator: Option<&str>,
    ) -> Result<VerifyHmacResult, WalletError> {
        Ok(VerifyHmacResult { valid: true })
    }

    async fn create_signature(
        &self,
        _args: CreateSignatureArgs,
        _originator: Option<&str>,
    ) -> Result<CreateSignatureResult, WalletError> {
        Ok(CreateSignatureResult {
            signature: vec![0u8; 64],
        })
    }

    async fn verify_signature(
        &self,
        _args: VerifySignatureArgs,
        _originator: Option<&str>,
    ) -> Result<VerifySignatureResult, WalletError> {
        Ok(VerifySignatureResult { valid: true })
    }

    async fn acquire_certificate(
        &self,
        _args: AcquireCertificateArgs,
        _originator: Option<&str>,
    ) -> Result<Certificate, WalletError> {
        Err(WalletError::NotImplemented("acquire_certificate".into()))
    }

    async fn list_certificates(
        &self,
        _args: ListCertificatesArgs,
        _originator: Option<&str>,
    ) -> Result<ListCertificatesResult, WalletError> {
        Ok(ListCertificatesResult {
            total_certificates: 0,
            certificates: vec![],
        })
    }

    async fn prove_certificate(
        &self,
        _args: ProveCertificateArgs,
        _originator: Option<&str>,
    ) -> Result<ProveCertificateResult, WalletError> {
        Err(WalletError::NotImplemented("prove_certificate".into()))
    }

    async fn relinquish_certificate(
        &self,
        _args: RelinquishCertificateArgs,
        _originator: Option<&str>,
    ) -> Result<RelinquishCertificateResult, WalletError> {
        Ok(RelinquishCertificateResult { relinquished: true })
    }

    async fn discover_by_identity_key(
        &self,
        _args: DiscoverByIdentityKeyArgs,
        _originator: Option<&str>,
    ) -> Result<DiscoverCertificatesResult, WalletError> {
        Ok(DiscoverCertificatesResult {
            total_certificates: 0,
            certificates: vec![],
        })
    }

    async fn discover_by_attributes(
        &self,
        _args: DiscoverByAttributesArgs,
        _originator: Option<&str>,
    ) -> Result<DiscoverCertificatesResult, WalletError> {
        Ok(DiscoverCertificatesResult {
            total_certificates: 0,
            certificates: vec![],
        })
    }

    async fn is_authenticated(
        &self,
        _originator: Option<&str>,
    ) -> Result<bsv::wallet::interfaces::AuthenticatedResult, WalletError> {
        Ok(bsv::wallet::interfaces::AuthenticatedResult {
            authenticated: true,
        })
    }

    async fn wait_for_authentication(
        &self,
        _originator: Option<&str>,
    ) -> Result<bsv::wallet::interfaces::AuthenticatedResult, WalletError> {
        Ok(bsv::wallet::interfaces::AuthenticatedResult {
            authenticated: true,
        })
    }

    async fn get_height(&self, _originator: Option<&str>) -> Result<GetHeightResult, WalletError> {
        Ok(GetHeightResult { height: 800000 })
    }

    async fn get_header_for_height(
        &self,
        _args: GetHeaderArgs,
        _originator: Option<&str>,
    ) -> Result<GetHeaderResult, WalletError> {
        Ok(GetHeaderResult {
            header: vec![0u8; 80],
        })
    }

    async fn get_network(
        &self,
        _originator: Option<&str>,
    ) -> Result<GetNetworkResult, WalletError> {
        Ok(GetNetworkResult {
            network: bsv::wallet::interfaces::Network::Mainnet,
        })
    }

    async fn get_version(
        &self,
        _originator: Option<&str>,
    ) -> Result<GetVersionResult, WalletError> {
        Ok(GetVersionResult {
            version: "0.1.3".into(),
        })
    }
}

// ---------------------------------------------------------------------------
// WalletInterfaceBoxed: async-trait version for comparison
// ---------------------------------------------------------------------------

/// A minimal trait using `#[async_trait]` with a single method matching
/// `WalletInterface::get_public_key`. This creates the full boxing +
/// dynamic dispatch overhead without modifying the real WalletInterface trait.
#[async_trait]
trait WalletInterfaceBoxed: Send + Sync {
    async fn get_public_key_boxed(
        &self,
        args: GetPublicKeyArgs,
        originator: Option<&str>,
    ) -> Result<GetPublicKeyResult, WalletError>;
}

#[async_trait]
impl WalletInterfaceBoxed for NoOpWallet {
    async fn get_public_key_boxed(
        &self,
        _args: GetPublicKeyArgs,
        _originator: Option<&str>,
    ) -> Result<GetPublicKeyResult, WalletError> {
        Ok(GetPublicKeyResult {
            public_key: bsv::primitives::public_key::PublicKey::from_private_key(
                &bsv::primitives::private_key::PrivateKey::from_hex("1").expect("valid hex"),
            ),
        })
    }
}

// ---------------------------------------------------------------------------
// Helper: build a GetPublicKeyArgs for benchmarking
// ---------------------------------------------------------------------------

fn make_get_pk_args() -> GetPublicKeyArgs {
    GetPublicKeyArgs {
        identity_key: false,
        protocol_id: Some(Protocol {
            protocol: "tests".into(),
            security_level: 2,
        }),
        key_id: Some("bench-key".into()),
        counterparty: None,
        privileged: false,
        privileged_reason: None,
        for_self: Some(false),
        seek_permission: None,
    }
}

// ---------------------------------------------------------------------------
// Generic caller for RPITIT (static dispatch through monomorphization)
// ---------------------------------------------------------------------------

async fn call_rpitit_generic<W: WalletInterface>(w: &W) -> GetPublicKeyResult {
    let args = make_get_pk_args();
    w.get_public_key(args, None)
        .await
        .expect("no-op should succeed")
}

// ---------------------------------------------------------------------------
// Dynamic dispatch caller for async-trait (virtual dispatch via vtable)
// ---------------------------------------------------------------------------

async fn call_boxed_dyn(w: &dyn WalletInterfaceBoxed) -> GetPublicKeyResult {
    let args = make_get_pk_args();
    w.get_public_key_boxed(args, None)
        .await
        .expect("no-op should succeed")
}

// ---------------------------------------------------------------------------
// Benchmarks
// ---------------------------------------------------------------------------

fn dispatch_benchmarks(c: &mut Criterion) {
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("tokio runtime");

    let mut group = c.benchmark_group("dispatch_bench");
    group.measurement_time(Duration::from_secs(5));
    group.sample_size(100);
    group.warm_up_time(Duration::from_secs(2));

    let wallet = NoOpWallet;

    // 1. Direct call on concrete type (RPITIT baseline)
    group.bench_function("rpitit_direct", |bencher| {
        bencher.iter(|| {
            rt.block_on(async {
                let args = make_get_pk_args();
                criterion::black_box(
                    wallet
                        .get_public_key(args, None)
                        .await
                        .expect("no-op should succeed"),
                )
            })
        });
    });

    // 2. Generic function call (RPITIT generic dispatch / monomorphization)
    group.bench_function("rpitit_generic", |bencher| {
        bencher.iter(|| {
            rt.block_on(async { criterion::black_box(call_rpitit_generic(&wallet).await) })
        });
    });

    // 3. Dynamic dispatch via async-trait boxed future (dyn WalletInterfaceBoxed)
    let wallet_boxed: &dyn WalletInterfaceBoxed = &wallet;
    group.bench_function("async_trait_dyn", |bencher| {
        bencher.iter(|| {
            rt.block_on(async { criterion::black_box(call_boxed_dyn(wallet_boxed).await) })
        });
    });

    group.finish();
}

criterion_group!(benches, dispatch_benchmarks);
criterion_main!(benches);