Sync a wallet with Kyoto¶
BIP157 and BIP158 define a protocol for light clients to sync with the Bitcoin network without downloading the entire set of blocks in the chain of most work. These proposals define compact block filters, which allow a client to download a small commitment for the scripts contained in each block. These commitments, or filters, may be checked for inclusion of scripts owned by a user. In the event of a match, the light client may download and verify a block indeed contains a relevant transaction. Syncing via compact block filters offers privacy advantages over other chain sources, as the nodes serving the blocks to the client are only aware that the client is interested in an entire block, which may contain thousands of transactions.
One such implementation of this protocol is Kyoto, which is a node and client for compact block filter based syncing. The bdk_kyoto crate supports an integration between Kyoto and bdk_wallet, so developers using bdk_wallet have a simple option to provide privacy-preserving and memory-conservative wallet syncing for their users.
The following example uses the bdk_kyoto crate to recover and update a bdk_wallet using compact block filters.
Add required bdk dependencies to your Cargo.toml file¶
[package]
name = "kyoto"
version = "0.1.0"
edition = "2021"
[dependencies]
bdk_kyoto = "0.19.0"
bdk_wallet = "3.1.0"
tokio = { version = "1", features = ["full"], default-features = false }
tracing = "0.1"
tracing-subscriber = "0.3"
Create and sync the wallet¶
use bdk_kyoto::builder::{Builder, BuilderExt};
use bdk_kyoto::state::Idle;
use bdk_kyoto::wallets::Single;
use bdk_kyoto::{HashCheckpoint, Info, LightClient, Receiver, SyncConfig, TrustedPeer, Warning};
use bdk_wallet::bitcoin::params::Params;
use bdk_wallet::bitcoin::Network;
use bdk_wallet::{KeychainKind, Wallet};
use tokio::select;
const RECEIVE: &str = "tr([7d94197e/86'/1'/0']tpubDCyQVJj8KzjiQsFjmb3KwECVXPvMwvAxxZGCP9XmWSopmjW3bCV3wD7TgxrUhiGSueDS1MU5X1Vb1YjYcp8jitXc5fXfdC1z68hDDEyKRNr/0/*)";
const CHANGE: &str = "tr([7d94197e/86'/1'/0']tpubDCyQVJj8KzjiQsFjmb3KwECVXPvMwvAxxZGCP9XmWSopmjW3bCV3wD7TgxrUhiGSueDS1MU5X1Vb1YjYcp8jitXc5fXfdC1z68hDDEyKRNr/1/*)";
const RECOVERY_LOOKAHEAD: u32 = 50;
const NUM_CONNECTIONS: u8 = 1;
const NETWORK: Network = Network::Regtest;
#[tokio::main]
async fn main() {
// Initialize tracing
let subscriber = tracing_subscriber::FmtSubscriber::new();
tracing::subscriber::set_global_default(subscriber).unwrap();
// Apply the recovery lookahead to the wallet
let mut wallet = Wallet::create(RECEIVE, CHANGE)
.network(NETWORK)
.lookahead(RECOVERY_LOOKAHEAD)
.create_wallet_no_persist()
.unwrap();
// Recover the wallet starting from a known checkpoint in the chain.
let checkpoint = HashCheckpoint::from_genesis(Params::REGTEST);
// Signet
// let checkpoint = HashCheckpoint::new(
// 300_000,
// "000000073002e4e1de008de89ee41db4baf8734c0f4e5ba9447bb0f1a301b02c"
// .parse::<BlockHash>()
// .unwrap(),
// );
let sync_config = SyncConfig::wallet_recovery_sync(checkpoint).build();
let peer = TrustedPeer::from_hostname("127.0.0.1", 18444);
// Build a light client and subscribe to receive log and wallet update channels.
let idle_client: LightClient<Idle, Single> = Builder::new(NETWORK)
.required_peers(NUM_CONNECTIONS)
.add_peer(peer)
.build_with_wallet(&wallet, sync_config)
.unwrap();
let (subscribed_client, log_subscribers, mut update_subscriber) = idle_client.subscribe();
// start() activates the client and runs the underlying node on a tokio task.
let client = subscribed_client.start();
// Trace the logs with a custom function.
tokio::task::spawn(async move {
trace_logs(
log_subscribers.info_subscriber,
log_subscribers.warning_subscriber,
)
.await
});
// Extract a requester for shutdown later; this consumes the active client.
let requester = client.requester();
// Sync and apply updates to the wallet. We can do this a continual loop while the application is running.
// Often this would occur on a separate thread than the underlying application user interface.
let update = update_subscriber.update().await.unwrap();
wallet.apply_update(update).unwrap();
tracing::info!("Tx count: {}", wallet.transactions().count());
tracing::info!("Balance: {}", wallet.balance().total().to_sat());
let last_revealed_external = wallet.derivation_index(KeychainKind::External);
tracing::info!("Last revealed external: {:?}", last_revealed_external);
tracing::info!("Local chain tip: {}", wallet.local_chain().tip().height());
let next = wallet.reveal_next_address(KeychainKind::External).address;
tracing::info!("Next receiving address: {next}");
requester.shutdown().unwrap();
}
/// Implement a custom logger that prints log messages to the console.
async fn trace_logs(mut info_rx: Receiver<Info>, mut warn_rx: Receiver<Warning>) {
loop {
select! {
warn = warn_rx.recv() => {
if let Some(warn) = warn {
tracing::warn!("{warn}")
}
}
info = info_rx.recv() => {
if let Some(info) = info {
tracing::info!("{info}")
}
}
}
}
}
A note on unconfirmed transactions, recoveries, sync and full-scan¶
The entire set of scripts is checked against each block filter as new blocks are gossiped to the Kyoto node. Because the scripts are not checked iteratively, there is not a semantic difference between "sync" and "full scan". Rather, Kyoto checks filters against the scripts revealed by each keychain in the wallet, plus the lookahead number of scripts beyond the last revealed index. How the sync starts is chosen with a SyncConfig: new_wallet_sync for a wallet that has never been used, sync_from_last_checkpoint for a wallet that has synced before, and wallet_recovery_sync to recover a wallet from a checkpoint in the chain. During a recovery, each block that pays one of the wallet's scripts reveals that script's index, moving the lookahead forward. The lookahead therefore acts as the gap limit of the recovery, and should be set larger for wallets that may have handed out many addresses before receiving payments to them.
Unconfirmed transactions pose a problem for light clients, as connections are untrusted. As such, users will be unaware of transactions they have received until they are confirmed in a block. While this tradeoff may be cumbersome, the benefits may outweigh the costs for privacy-conscious users.