bdkffi/bitcoin.rs
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 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
use crate::error::{
AddressParseError, Bip32Error, ExtractTxError, FeeRateError, FromScriptError, HashParseError,
PsbtError, PsbtParseError, TransactionError,
};
use crate::error::{ParseAmountError, PsbtFinalizeError};
use crate::keys::DerivationPath;
use crate::{impl_from_core_type, impl_hash_like, impl_into_core_type};
use bdk_wallet::bitcoin::address::NetworkChecked;
use bdk_wallet::bitcoin::address::NetworkUnchecked;
use bdk_wallet::bitcoin::address::{Address as BdkAddress, AddressData as BdkAddressData};
use bdk_wallet::bitcoin::blockdata::block::Block as BdkBlock;
use bdk_wallet::bitcoin::blockdata::block::Header as BdkHeader;
use bdk_wallet::bitcoin::consensus::encode::deserialize;
use bdk_wallet::bitcoin::consensus::encode::serialize;
use bdk_wallet::bitcoin::consensus::Decodable;
use bdk_wallet::bitcoin::hashes::sha256::Hash as BitcoinSha256Hash;
use bdk_wallet::bitcoin::hashes::sha256d::Hash as BitcoinDoubleSha256Hash;
use bdk_wallet::bitcoin::io::Cursor;
use bdk_wallet::bitcoin::psbt::Input as BdkInput;
use bdk_wallet::bitcoin::psbt::Output as BdkOutput;
use bdk_wallet::bitcoin::secp256k1::Secp256k1;
use std::collections::HashMap;
use std::convert::TryFrom;
use bdk_wallet::bitcoin::bip32::ChildNumber as BdkChildNumber;
use bdk_wallet::bitcoin::taproot::LeafNode as BdkLeafNode;
use bdk_wallet::bitcoin::taproot::NodeInfo as BdkNodeInfo;
use bdk_wallet::bitcoin::taproot::TapTree as BdkTapTree;
use bdk_wallet::bitcoin::Amount as BdkAmount;
use bdk_wallet::bitcoin::BlockHash as BitcoinBlockHash;
use bdk_wallet::bitcoin::FeeRate as BdkFeeRate;
use bdk_wallet::bitcoin::OutPoint as BdkOutPoint;
use bdk_wallet::bitcoin::Psbt as BdkPsbt;
use bdk_wallet::bitcoin::ScriptBuf as BdkScriptBuf;
use bdk_wallet::bitcoin::Transaction as BdkTransaction;
use bdk_wallet::bitcoin::TxIn as BdkTxIn;
use bdk_wallet::bitcoin::TxOut as BdkTxOut;
use bdk_wallet::bitcoin::Txid as BitcoinTxid;
use bdk_wallet::bitcoin::Weight;
use bdk_wallet::bitcoin::Wtxid as BitcoinWtxid;
use bdk_wallet::miniscript::psbt::PsbtExt;
use bdk_wallet::serde_json;
use std::fmt::Display;
use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::ops::Deref;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
pub type DescriptorType = bdk_wallet::miniscript::descriptor::DescriptorType;
pub type Network = bdk_wallet::bitcoin::Network;
/// A reference to an unspent output by TXID and output index.
#[derive(Debug, Clone, Eq, PartialEq, std::hash::Hash, uniffi:: Record)]
pub struct OutPoint {
/// The transaction.
pub txid: Arc<Txid>,
/// The index of the output in the transaction.
pub vout: u32,
}
impl From<&BdkOutPoint> for OutPoint {
fn from(outpoint: &BdkOutPoint) -> Self {
OutPoint {
txid: Arc::new(Txid(outpoint.txid)),
vout: outpoint.vout,
}
}
}
impl From<BdkOutPoint> for OutPoint {
fn from(value: BdkOutPoint) -> Self {
Self {
txid: Arc::new(Txid(value.txid)),
vout: value.vout,
}
}
}
impl From<OutPoint> for BdkOutPoint {
fn from(outpoint: OutPoint) -> Self {
BdkOutPoint {
txid: BitcoinTxid::from_raw_hash(outpoint.txid.0.to_raw_hash()),
vout: outpoint.vout,
}
}
}
/// The cryptocurrency network to act on.
///
/// This is an exhaustive enum, meaning that we cannot add any future networks without defining a
/// new, incompatible version of this type. If you are using this type directly and wish to support
/// the new network, this will be a breaking change to your APIs and likely require changes in your
/// code.
///
/// If you are concerned about forward compatibility, consider using T: Into<Params> instead of this
/// type as a parameter to functions in your public API, or directly using the Params type.
#[uniffi::remote(Enum)]
pub enum Network {
Bitcoin,
Testnet,
Testnet4,
Signet,
Regtest,
}
/// An [`OutPoint`] used as a key in a hash map.
///
/// Due to limitations in generating the foreign language bindings, we cannot use [`OutPoint`] as a
/// key for hash maps.
#[derive(Debug, PartialEq, Eq, std::hash::Hash, uniffi::Object)]
#[uniffi::export(Debug, Eq, Hash)]
pub struct HashableOutPoint(pub(crate) OutPoint);
#[uniffi::export]
impl HashableOutPoint {
/// Create a key for a key-value store from an [`OutPoint`]
#[uniffi::constructor]
pub fn new(outpoint: OutPoint) -> Self {
Self(outpoint)
}
/// Get the internal [`OutPoint`]
pub fn outpoint(&self) -> OutPoint {
self.0.clone()
}
}
/// Represents fee rate.
///
/// This is an integer type representing fee rate in sat/kwu. It provides protection against mixing
/// up the types as well as basic formatting features.
#[derive(Clone, Debug, uniffi::Object)]
#[uniffi::export(Display)]
pub struct FeeRate(pub(crate) BdkFeeRate);
#[uniffi::export]
impl FeeRate {
/// Constructs `FeeRate` from satoshis per virtual bytes.
#[uniffi::constructor]
pub fn from_sat_per_vb(sat_vb: u64) -> Result<Self, FeeRateError> {
let fee_rate: Option<BdkFeeRate> = BdkFeeRate::from_sat_per_vb(sat_vb);
match fee_rate {
Some(fee_rate) => Ok(FeeRate(fee_rate)),
None => Err(FeeRateError::ArithmeticOverflow),
}
}
/// Constructs `FeeRate` from satoshis per 1000 weight units.
#[uniffi::constructor]
pub fn from_sat_per_kwu(sat_kwu: u64) -> Self {
FeeRate(BdkFeeRate::from_sat_per_kwu(sat_kwu))
}
/// Converts to sat/vB rounding up.
pub fn to_sat_per_vb_ceil(&self) -> u64 {
self.0.to_sat_per_vb_ceil()
}
/// Converts to sat/vB rounding down.
pub fn to_sat_per_vb_floor(&self) -> u64 {
self.0.to_sat_per_vb_floor()
}
/// Returns raw fee rate.
pub fn to_sat_per_kwu(&self) -> u64 {
self.0.to_sat_per_kwu()
}
/// Calculates fee in satoshis by multiplying this fee rate by weight, in virtual bytes, returning `None` if overflow occurred.
///
/// This is equivalent to converting vb to weight using Weight::from_vb and then calling Self::fee_wu(weight).
pub fn fee_vb(&self, vb: u64) -> Option<Arc<Amount>> {
let rust_amount: BdkAmount = self.0.fee_vb(vb)?;
let amount: Amount = rust_amount.into();
Some(Arc::new(amount))
// The whole code above should be replaceable by the following line:
// self.0.fee_vb(vb).map(Arc::new(Amount::from))
// But in practice you get uniffi compilation errors on it. Not sure what is going on with it,
// but the code we use works just as well.
}
/// Calculates fee by multiplying this fee rate by weight, in weight units, returning `None` if overflow occurred.
///
/// This is equivalent to Self::checked_mul_by_weight().
pub fn fee_wu(&self, wu: u64) -> Option<Arc<Amount>> {
let weight: Weight = Weight::from_wu(wu);
let rust_amount: BdkAmount = self.0.fee_wu(weight)?;
let amount: Amount = rust_amount.into();
Some(Arc::new(amount))
}
}
impl Display for FeeRate {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:#}", self.0)
}
}
impl_from_core_type!(BdkFeeRate, FeeRate);
impl_into_core_type!(FeeRate, BdkFeeRate);
/// The Amount type can be used to express Bitcoin amounts that support arithmetic and conversion
/// to various denominations. The operations that Amount implements will panic when overflow or
/// underflow occurs. Also note that since the internal representation of amounts is unsigned,
/// subtracting below zero is considered an underflow and will cause a panic.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Object)]
pub struct Amount(pub(crate) BdkAmount);
#[uniffi::export]
impl Amount {
/// Create an Amount with satoshi precision and the given number of satoshis.
#[uniffi::constructor]
pub fn from_sat(satoshi: u64) -> Self {
Amount(BdkAmount::from_sat(satoshi))
}
/// Convert from a value expressing bitcoins to an Amount.
#[uniffi::constructor]
pub fn from_btc(btc: f64) -> Result<Self, ParseAmountError> {
let bitcoin_amount = BdkAmount::from_btc(btc).map_err(ParseAmountError::from)?;
Ok(Amount(bitcoin_amount))
}
/// Get the number of satoshis in this Amount.
pub fn to_sat(&self) -> u64 {
self.0.to_sat()
}
/// Express this Amount as a floating-point value in Bitcoin. Please be aware of the risk of
/// using floating-point numbers.
pub fn to_btc(&self) -> f64 {
self.0.to_btc()
}
}
impl_from_core_type!(BdkAmount, Amount);
impl_into_core_type!(Amount, BdkAmount);
/// A bitcoin script: https://en.bitcoin.it/wiki/Script
#[derive(Clone, Debug, uniffi::Object)]
#[uniffi::export(Display)]
pub struct Script(pub(crate) BdkScriptBuf);
#[uniffi::export]
impl Script {
/// Interpret an array of bytes as a bitcoin script.
#[uniffi::constructor]
pub fn new(raw_output_script: Vec<u8>) -> Self {
let script: BdkScriptBuf = raw_output_script.into();
Script(script)
}
/// Convert a script into an array of bytes.
pub fn to_bytes(&self) -> Vec<u8> {
self.0.to_bytes()
}
}
impl_from_core_type!(BdkScriptBuf, Script);
impl_into_core_type!(Script, BdkScriptBuf);
impl Display for Script {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt_asm(f)
}
}
/// Bitcoin block header.
/// Contains all the block’s information except the actual transactions, but including a root of a merkle tree
/// committing to all transactions in the block.
#[derive(uniffi::Record)]
pub struct Header {
/// Block version, now repurposed for soft fork signalling.
pub version: i32,
/// Reference to the previous block in the chain.
pub prev_blockhash: Arc<BlockHash>,
/// The root hash of the merkle tree of transactions in the block.
pub merkle_root: Arc<TxMerkleNode>,
/// The timestamp of the block, as claimed by the miner.
pub time: u32,
/// The target value below which the blockhash must lie.
pub bits: u32,
/// The nonce, selected to obtain a low enough blockhash.
pub nonce: u32,
}
impl From<BdkHeader> for Header {
fn from(bdk_header: BdkHeader) -> Self {
Header {
version: bdk_header.version.to_consensus(),
prev_blockhash: Arc::new(BlockHash(bdk_header.prev_blockhash)),
merkle_root: Arc::new(TxMerkleNode(bdk_header.merkle_root.to_raw_hash())),
time: bdk_header.time,
bits: bdk_header.bits.to_consensus(),
nonce: bdk_header.nonce,
}
}
}
/// Bitcoin block.
/// A collection of transactions with an attached proof of work.
#[derive(uniffi::Record)]
pub struct Block {
pub header: Header,
pub txdata: Vec<Arc<Transaction>>,
}
impl From<BdkBlock> for Block {
fn from(bdk_block: BdkBlock) -> Self {
Block {
header: bdk_block.header.into(),
txdata: bdk_block
.txdata
.into_iter()
.map(|tx| Arc::new(tx.into()))
.collect(),
}
}
}
/// The type of address.
#[derive(Debug, uniffi::Enum)]
pub enum AddressData {
/// Legacy.
P2pkh { pubkey_hash: String },
/// Wrapped Segwit
P2sh { script_hash: String },
/// Segwit
Segwit { witness_program: WitnessProgram },
}
/// The version and program of a Segwit address.
#[derive(Debug, uniffi::Record)]
pub struct WitnessProgram {
/// Version. For example 1 for Taproot.
pub version: u8,
/// The witness program.
pub program: Vec<u8>,
}
/// A bitcoin address
#[derive(Debug, PartialEq, Eq, uniffi::Object)]
#[uniffi::export(Eq, Display)]
pub struct Address(pub(crate) BdkAddress<NetworkChecked>);
#[uniffi::export]
impl Address {
/// Parse a string as an address for the given network.
#[uniffi::constructor]
pub fn new(address: String, network: Network) -> Result<Self, AddressParseError> {
let parsed_address = address.parse::<bdk_wallet::bitcoin::Address<NetworkUnchecked>>()?;
let network_checked_address = parsed_address.require_network(network)?;
Ok(Address(network_checked_address))
}
/// Parse a script as an address for the given network
#[uniffi::constructor]
pub fn from_script(script: Arc<Script>, network: Network) -> Result<Self, FromScriptError> {
let address = BdkAddress::from_script(&script.0.clone(), network)?;
Ok(Address(address))
}
/// Return the `scriptPubKey` underlying an address.
pub fn script_pubkey(&self) -> Arc<Script> {
Arc::new(Script(self.0.script_pubkey()))
}
/// Return a BIP-21 URI string for this address.
pub fn to_qr_uri(&self) -> String {
self.0.to_qr_uri()
}
/// Is the address valid for the provided network
pub fn is_valid_for_network(&self, network: Network) -> bool {
let address_str = self.0.to_string();
if let Ok(unchecked_address) = address_str.parse::<BdkAddress<NetworkUnchecked>>() {
unchecked_address.is_valid_for_network(network)
} else {
false
}
}
/// Return the data for the address.
pub fn to_address_data(&self) -> AddressData {
match self.0.to_address_data() {
BdkAddressData::P2pkh { pubkey_hash } => AddressData::P2pkh {
pubkey_hash: pubkey_hash.to_string(),
},
BdkAddressData::P2sh { script_hash } => AddressData::P2sh {
script_hash: script_hash.to_string(),
},
BdkAddressData::Segwit { witness_program } => AddressData::Segwit {
witness_program: WitnessProgram {
version: witness_program.version().to_num(),
program: witness_program.program().as_bytes().to_vec(),
},
},
// AddressData is marked #[non_exhaustive] in bitcoin crate
_ => unimplemented!("Unsupported address type"),
}
}
}
impl Display for Address {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl_from_core_type!(BdkAddress, Address);
impl_into_core_type!(Address, BdkAddress);
/// Bitcoin transaction.
/// An authenticated movement of coins.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Object)]
#[uniffi::export(Eq, Display)]
pub struct Transaction(BdkTransaction);
#[uniffi::export]
impl Transaction {
/// Creates a new `Transaction` instance from serialized transaction bytes.
#[uniffi::constructor]
pub fn new(transaction_bytes: Vec<u8>) -> Result<Self, TransactionError> {
let mut decoder = Cursor::new(transaction_bytes);
let tx: BdkTransaction = BdkTransaction::consensus_decode(&mut decoder)?;
Ok(Transaction(tx))
}
/// Computes the Txid.
/// Hashes the transaction excluding the segwit data (i.e. the marker, flag bytes, and the witness fields themselves).
pub fn compute_txid(&self) -> Arc<Txid> {
Arc::new(Txid(self.0.compute_txid()))
}
/// Compute the Wtxid, which includes the witness in the transaction hash.
pub fn compute_wtxid(&self) -> Arc<Wtxid> {
Arc::new(Wtxid(self.0.compute_wtxid()))
}
/// Returns the weight of this transaction, as defined by BIP-141.
///
/// > Transaction weight is defined as Base transaction size * 3 + Total transaction size (ie.
/// > the same method as calculating Block weight from Base size and Total size).
///
/// For transactions with an empty witness, this is simply the consensus-serialized size times
/// four. For transactions with a witness, this is the non-witness consensus-serialized size
/// multiplied by three plus the with-witness consensus-serialized size.
///
/// For transactions with no inputs, this function will return a value 2 less than the actual
/// weight of the serialized transaction. The reason is that zero-input transactions, post-segwit,
/// cannot be unambiguously serialized; we make a choice that adds two extra bytes. For more
/// details see [BIP 141](https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki)
/// which uses a "input count" of `0x00` as a `marker` for a Segwit-encoded transaction.
///
/// If you need to use 0-input transactions, we strongly recommend you do so using the PSBT
/// API. The unsigned transaction encoded within PSBT is always a non-segwit transaction
/// and can therefore avoid this ambiguity.
#[inline]
pub fn weight(&self) -> u64 {
self.0.weight().to_wu()
}
/// Returns the total transaction size
///
/// Total transaction size is the transaction size in bytes serialized as described in BIP144,
/// including base data and witness data.
pub fn total_size(&self) -> u64 {
self.0.total_size() as u64
}
/// Returns the "virtual size" (vsize) of this transaction.
///
/// Will be `ceil(weight / 4.0)`. Note this implements the virtual size as per [`BIP141`], which
/// is different to what is implemented in Bitcoin Core.
/// > Virtual transaction size is defined as Transaction weight / 4 (rounded up to the next integer).
///
/// [`BIP141`]: https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki
#[inline]
pub fn vsize(&self) -> u64 {
self.0.vsize() as u64
}
/// Checks if this is a coinbase transaction.
/// The first transaction in the block distributes the mining reward and is called the coinbase transaction.
/// It is impossible to check if the transaction is first in the block, so this function checks the structure
/// of the transaction instead - the previous output must be all-zeros (creates satoshis “out of thin air”).
pub fn is_coinbase(&self) -> bool {
self.0.is_coinbase()
}
/// Returns `true` if the transaction itself opted in to be BIP-125-replaceable (RBF).
///
/// # Warning
///
/// **Incorrectly relying on RBF may lead to monetary loss!**
///
/// This **does not** cover the case where a transaction becomes replaceable due to ancestors
/// being RBF. Please note that transactions **may be replaced** even if they **do not** include
/// the RBF signal: <https://bitcoinops.org/en/newsletters/2022/10/19/#transaction-replacement-option>.
pub fn is_explicitly_rbf(&self) -> bool {
self.0.is_explicitly_rbf()
}
/// Returns `true` if this transactions nLockTime is enabled ([BIP-65]).
///
/// [BIP-65]: https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki
pub fn is_lock_time_enabled(&self) -> bool {
self.0.is_lock_time_enabled()
}
/// The protocol version, is currently expected to be 1 or 2 (BIP 68).
pub fn version(&self) -> i32 {
self.0.version.0
}
/// Serialize transaction into consensus-valid format. See https://docs.rs/bitcoin/latest/bitcoin/struct.Transaction.html#serialization-notes for more notes on transaction serialization.
pub fn serialize(&self) -> Vec<u8> {
serialize(&self.0)
}
/// List of transaction inputs.
pub fn input(&self) -> Vec<TxIn> {
self.0.input.iter().map(|tx_in| tx_in.into()).collect()
}
/// List of transaction outputs.
pub fn output(&self) -> Vec<TxOut> {
self.0.output.iter().map(|tx_out| tx_out.into()).collect()
}
/// Block height or timestamp. Transaction cannot be included in a block until this height/time.
///
/// /// ### Relevant BIPs
///
/// * [BIP-65 OP_CHECKLOCKTIMEVERIFY](https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki)
/// * [BIP-113 Median time-past as endpoint for lock-time calculations](https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki)
pub fn lock_time(&self) -> u32 {
self.0.lock_time.to_consensus_u32()
}
}
impl From<BdkTransaction> for Transaction {
fn from(tx: BdkTransaction) -> Self {
Transaction(tx)
}
}
impl From<&BdkTransaction> for Transaction {
fn from(tx: &BdkTransaction) -> Self {
Transaction(tx.clone())
}
}
impl From<&Transaction> for BdkTransaction {
fn from(tx: &Transaction) -> Self {
tx.0.clone()
}
}
impl Display for Transaction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.0)
}
}
#[derive(Clone, Debug, uniffi::Record)]
pub struct TapScriptEntry {
/// script (reuse existing `Script` FFI type)
pub script: Arc<Script>,
/// leaf version
pub leaf_version: u8,
}
#[derive(Clone, Debug, uniffi::Record)]
pub struct TapKeyOrigin {
/// leaf hashes as hex strings
pub tap_leaf_hashes: Vec<String>,
/// key source
pub key_source: KeySource,
}
#[derive(Clone, Debug, uniffi::Record)]
pub struct KeySource {
/// A fingerprint
pub fingerprint: String,
/// A BIP-32 derivation path.
pub path: Arc<DerivationPath>,
}
#[derive(Clone, Debug, Hash, Eq, PartialEq, uniffi::Record)]
pub struct Key {
/// The type of this PSBT key.
pub type_value: u8,
/// The key itself in raw byte form.
/// `<key> := <keylen> <keytype> <keydata>`
pub key: Vec<u8>,
}
#[derive(Clone, Debug, Hash, Eq, PartialEq, uniffi::Record)]
pub struct ProprietaryKey {
/// Proprietary type prefix used for grouping together keys under some
/// application and avoid namespace collision
pub prefix: Vec<u8>,
/// Custom proprietary subtype
pub subtype: u8,
/// Additional key bytes (like serialized public key data etc)
pub key: Vec<u8>,
}
#[derive(Clone, Debug, Hash, Eq, PartialEq, uniffi::Record)]
pub struct ControlBlock {
/// The internal key.
pub internal_key: Vec<u8>,
/// The merkle proof of a script associated with this leaf.
pub merkle_branch: Vec<String>,
/// The parity of the output key (NOT THE INTERNAL KEY WHICH IS ALWAYS XONLY).
pub output_key_parity: u8,
/// The tapleaf version.
pub leaf_version: u8,
}
#[derive(Clone, Debug, Hash, Eq, PartialEq, uniffi::Record)]
pub struct TapScriptSigKey {
/// An x-only public key, used for verification of Taproot signatures and serialized according to BIP-340.
pub xonly_pubkey: String,
/// Taproot-tagged hash with tag "TapLeaf".
/// This is used for computing tapscript script spend hash.
pub tap_leaf_hash: String,
}
/// A key-value map for an input of the corresponding index in the unsigned transaction.
#[derive(Clone, Debug, uniffi::Record)]
pub struct Input {
/// The non-witness transaction this input spends from. Should only be
/// `Option::Some` for inputs which spend non-segwit outputs or
/// if it is unknown whether an input spends a segwit output.
pub non_witness_utxo: Option<Arc<Transaction>>,
/// The transaction output this input spends from. Should only be
/// `Option::Some` for inputs which spend segwit outputs,
/// including P2SH embedded ones.
pub witness_utxo: Option<TxOut>,
/// A map from public keys to their corresponding signature as would be
/// pushed to the stack from a scriptSig or witness for a non-taproot inputs.
pub partial_sigs: HashMap<String, Vec<u8>>,
/// The sighash type to be used for this input. Signatures for this input
/// must use the sighash type.
pub sighash_type: Option<String>,
/// The redeem script for this input.
pub redeem_script: Option<Arc<Script>>,
/// The witness script for this input.
pub witness_script: Option<Arc<Script>>,
/// A map from public keys needed to sign this input to their corresponding
/// master key fingerprints and derivation paths.
pub bip32_derivation: HashMap<String, KeySource>,
/// The finalized, fully-constructed scriptSig with signatures and any other
/// scripts necessary for this input to pass validation.
pub final_script_sig: Option<Arc<Script>>,
/// The finalized, fully-constructed scriptWitness with signatures and any
/// other scripts necessary for this input to pass validation.
pub final_script_witness: Option<Vec<Vec<u8>>>,
/// RIPEMD160 hash to preimage map.
pub ripemd160_preimages: HashMap<String, Vec<u8>>,
/// SHA256 hash to preimage map.
pub sha256_preimages: HashMap<String, Vec<u8>>,
/// HASH160 hash to preimage map.
pub hash160_preimages: HashMap<String, Vec<u8>>,
/// HASH256 hash to preimage map.
pub hash256_preimages: HashMap<String, Vec<u8>>,
/// Serialized taproot signature with sighash type for key spend.
pub tap_key_sig: Option<Vec<u8>>,
/// Map of `<xonlypubkey>|<leafhash>` with signature.
pub tap_script_sigs: HashMap<TapScriptSigKey, Vec<u8>>,
/// Map of Control blocks to Script version pair.
pub tap_scripts: HashMap<ControlBlock, TapScriptEntry>,
/// Map of tap root x only keys to origin info and leaf hashes contained in it.
pub tap_key_origins: HashMap<String, TapKeyOrigin>,
/// Taproot Internal key.
pub tap_internal_key: Option<String>,
/// Taproot Merkle root.
pub tap_merkle_root: Option<String>,
/// Proprietary key-value pairs for this input.
pub proprietary: HashMap<ProprietaryKey, Vec<u8>>,
/// Unknown key-value pairs for this input.
pub unknown: HashMap<Key, Vec<u8>>,
}
impl From<&BdkInput> for Input {
fn from(input: &BdkInput) -> Self {
Input {
non_witness_utxo: input
.non_witness_utxo
.as_ref()
.map(|tx| Arc::new(Transaction(tx.clone()))),
witness_utxo: input.witness_utxo.as_ref().map(TxOut::from),
partial_sigs: input
.partial_sigs
.iter()
.map(|(k, v)| (k.to_string(), v.to_vec()))
.collect(),
sighash_type: input.sighash_type.as_ref().map(|s| s.to_string()),
redeem_script: input
.redeem_script
.as_ref()
.map(|s| Arc::new(Script(s.clone()))),
witness_script: input
.witness_script
.as_ref()
.map(|s| Arc::new(Script(s.clone()))),
bip32_derivation: input
.bip32_derivation
.iter()
.map(|(pk, (fingerprint, deriv_path))| {
(
pk.to_string(),
KeySource {
fingerprint: fingerprint.to_string(),
path: Arc::new(deriv_path.clone().into()),
},
)
})
.collect(),
final_script_sig: input
.final_script_sig
.as_ref()
.map(|s| Arc::new(Script(s.clone()))),
final_script_witness: input.final_script_witness.as_ref().map(|w| w.to_vec()),
ripemd160_preimages: input
.ripemd160_preimages
.iter()
.map(|(k, v)| (k.to_string(), v.clone()))
.collect(),
sha256_preimages: input
.sha256_preimages
.iter()
.map(|(k, v)| (k.to_string(), v.clone()))
.collect(),
hash160_preimages: input
.hash160_preimages
.iter()
.map(|(k, v)| (k.to_string(), v.clone()))
.collect(),
hash256_preimages: input
.hash256_preimages
.iter()
.map(|(k, v)| (k.to_string(), v.clone()))
.collect(),
tap_key_sig: input.tap_key_sig.as_ref().map(|s| s.serialize().to_vec()),
tap_script_sigs: input
.tap_script_sigs
.iter()
.map(|(k, v)| {
let key = TapScriptSigKey {
xonly_pubkey: k.0.to_string(),
tap_leaf_hash: k.1.to_string(),
};
(key, v.to_vec())
})
.collect(),
tap_scripts: input
.tap_scripts
.iter()
.map(|(k, v)| {
let key = ControlBlock {
internal_key: k.internal_key.serialize().to_vec(),
merkle_branch: k.merkle_branch.iter().map(|h| h.to_string()).collect(),
output_key_parity: k.output_key_parity.to_u8(),
leaf_version: k.leaf_version.to_consensus(),
};
let entry = TapScriptEntry {
script: Arc::new(v.0.clone().into()),
leaf_version: v.1.to_consensus(),
};
(key, entry)
})
.collect(),
tap_key_origins: input
.tap_key_origins
.iter()
.map(|(k, v)| {
let key = k.to_string();
let value = TapKeyOrigin {
tap_leaf_hashes: v.0.iter().map(|h| h.to_string()).collect(),
key_source: KeySource {
// Unnecessary spaces being added by fmt. We use #[rustfmt::skip] to avoid them for now.
#[rustfmt::skip]
fingerprint: v.1.0.to_string(),
#[rustfmt::skip]
path: Arc::new(v.1.1.clone().into()),
},
};
(key, value)
})
.collect(),
tap_internal_key: input.tap_internal_key.as_ref().map(|k| k.to_string()),
tap_merkle_root: input.tap_merkle_root.as_ref().map(|k| k.to_string()),
proprietary: input
.proprietary
.iter()
.map(|(k, v)| {
(
ProprietaryKey {
prefix: k.prefix.clone(),
subtype: k.subtype,
key: k.key.clone(),
},
v.to_vec(),
)
})
.collect(),
unknown: input
.unknown
.iter()
.map(|(k, v)| {
(
Key {
key: k.key.clone(),
type_value: k.type_value,
},
v.to_vec(),
)
})
.collect(),
}
}
}
/// Store information about taproot leaf node.
#[derive(Debug, uniffi::Object)]
#[uniffi::export(Display)]
pub struct LeafNode(BdkLeafNode);
#[uniffi::export]
impl LeafNode {
/// Returns the depth of this script leaf in the tap tree.
pub fn depth(&self) -> u8 {
self.0.depth()
}
/// Computes a leaf hash for this ScriptLeaf if the leaf is known.
/// This TapLeafHash is useful while signing taproot script spends.
/// See LeafNode::node_hash for computing the TapNodeHash which returns the hidden node hash if the node is hidden.
pub fn leaf_hash(&self) -> Option<String> {
self.0.leaf_hash().map(|h| h.to_string())
}
/// Computes the [`TapNodeHash`] for this [`ScriptLeaf`]. This returns the
/// leaf hash if the leaf is known and the hidden node hash if the leaf is
/// hidden.
/// See also, [`bdk_electrum::bdk_core::bitcoin::taproot::LeafNode::leaf_hash`].
pub fn node_hash(&self) -> String {
self.0.node_hash().to_string()
}
/// Returns reference to the leaf script if the leaf is known.
pub fn script(&self) -> Option<Arc<Script>> {
self.0.script().map(|s| Arc::new(Script(s.to_owned())))
}
/// Returns leaf version of the script if the leaf is known.
pub fn leaf_version(&self) -> Option<u8> {
self.0.leaf_version().map(|n| n.to_consensus())
}
/// Returns reference to the merkle proof (hashing partners) to get this
/// node in form of [`TaprootMerkleBranch`].
pub fn merkle_branch(&self) -> Vec<String> {
self.0
.merkle_branch()
.to_vec()
.iter()
.map(|h| h.to_string())
.collect()
}
}
impl Display for LeafNode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
/// Taproot Tree representing a complete binary tree without any hidden nodes.
///
/// This is in contrast to NodeInfo, which allows hidden nodes. The implementations for Eq, PartialEq and Hash compare the merkle root of the tree
#[derive(Debug, uniffi::Object)]
#[uniffi::export(Display)]
pub struct TapTree(BdkTapTree);
#[uniffi::export]
impl TapTree {
/// Returns the root TapNodeHash of this tree.
pub fn root_hash(&self) -> String {
self.0.root_hash().to_string()
}
/// Gets the reference to inner NodeInfo of this tree root.
pub fn node_info(&self) -> Arc<NodeInfo> {
Arc::new(NodeInfo(self.0.node_info().clone()))
}
}
impl Display for TapTree {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
/// Represents the node information in taproot tree. In contrast to TapTree, this is allowed to have hidden leaves as children.
///
/// Helper type used in merkle tree construction allowing one to build sparse merkle trees. The node represents part of the tree that has information about all of its descendants. See how TaprootBuilder works for more details.
/// You can use TaprootSpendInfo::from_node_info to a get a TaprootSpendInfo from the merkle root NodeInfo.
#[derive(Debug, uniffi::Object)]
#[uniffi::export(Display)]
pub struct NodeInfo(BdkNodeInfo);
#[uniffi::export]
impl NodeInfo {
/// Creates an iterator over all leaves (including hidden leaves) in the tree.
pub fn leaf_nodes(&self) -> Vec<Arc<LeafNode>> {
self.0
.leaf_nodes()
.map(|ln| Arc::new(LeafNode(ln.clone())))
.collect()
}
/// Returns the root TapNodeHash of this node info.
pub fn node_hash(&self) -> String {
self.0.node_hash().to_string()
}
}
impl Display for NodeInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
/// A key-value map for an output of the corresponding index in the unsigned
/// transaction.
#[derive(Debug, uniffi::Record)]
pub struct Output {
/// The redeem script for this output.
pub redeem_script: Option<Arc<Script>>,
/// The witness script for this output.
pub witness_script: Option<Arc<Script>>,
/// Map of public keys needed to spend this output to their corresponding
/// master key fingerprints and derivation paths.
pub bip32_derivation: HashMap<String, KeySource>,
/// Taproot Internal key.
pub tap_internal_key: Option<String>,
/// Taproot Output tree (structured record).
pub tap_tree: Option<Arc<TapTree>>,
/// Map of tap root x only keys to origin info and leaf hashes contained in it.
pub tap_key_origins: HashMap<String, TapKeyOrigin>,
/// Proprietary key-value pairs for this output.
pub proprietary: HashMap<ProprietaryKey, Vec<u8>>,
/// Unknown key-value pairs for this output.
pub unknown: HashMap<Key, Vec<u8>>,
}
impl From<&BdkOutput> for Output {
fn from(output: &BdkOutput) -> Self {
Output {
redeem_script: output
.redeem_script
.as_ref()
.map(|s| Arc::new(Script(s.clone()))),
witness_script: output
.witness_script
.as_ref()
.map(|s| Arc::new(Script(s.clone()))),
bip32_derivation: output
.bip32_derivation
.iter()
.map(|(pk, (fingerprint, deriv_path))| {
(
pk.to_string(),
KeySource {
fingerprint: fingerprint.to_string(),
path: Arc::new(deriv_path.clone().into()),
},
)
})
.collect(),
tap_internal_key: output.tap_internal_key.as_ref().map(|k| k.to_string()),
tap_tree: output
.tap_tree
.as_ref()
.map(|t| Arc::new(TapTree(t.clone()))),
tap_key_origins: output
.tap_key_origins
.iter()
.map(|(k, v)| {
let key = k.to_string();
let value = TapKeyOrigin {
tap_leaf_hashes: v.0.iter().map(|h| h.to_string()).collect(),
key_source: KeySource {
// Unnecessary spaces being added by fmt. We use #[rustfmt::skip] to avoid them for now.
#[rustfmt::skip]
fingerprint: v.1.0.to_string(),
#[rustfmt::skip]
path: Arc::new(v.1.1.clone().into()),
},
};
(key, value)
})
.collect(),
proprietary: output
.proprietary
.iter()
.map(|(k, v)| {
(
ProprietaryKey {
prefix: k.prefix.clone(),
subtype: k.subtype,
key: k.key.clone(),
},
v.to_vec(),
)
})
.collect(),
unknown: output
.unknown
.iter()
.map(|(k, v)| {
(
Key {
key: k.key.clone(),
type_value: k.type_value,
},
v.to_vec(),
)
})
.collect(),
}
}
}
/// A Partially Signed Transaction.
#[derive(uniffi::Object)]
pub struct Psbt(pub(crate) Mutex<BdkPsbt>);
#[uniffi::export]
impl Psbt {
/// Creates a new `Psbt` instance from a base64-encoded string.
#[uniffi::constructor]
pub fn new(psbt_base64: String) -> Result<Self, PsbtParseError> {
let psbt: BdkPsbt = BdkPsbt::from_str(&psbt_base64)?;
Ok(Psbt(Mutex::new(psbt)))
}
/// Creates a PSBT from an unsigned transaction.
///
/// # Errors
///
/// If transactions is not unsigned.
#[uniffi::constructor]
pub fn from_unsigned_tx(tx: Arc<Transaction>) -> Result<Arc<Psbt>, PsbtError> {
let psbt: BdkPsbt = BdkPsbt::from_unsigned_tx(tx.0.clone())?;
Ok(Arc::new(Psbt(Mutex::new(psbt))))
}
/// Create a new `Psbt` from a `.psbt` file.
#[uniffi::constructor]
pub fn from_file(path: String) -> Result<Self, PsbtError> {
let file = File::open(path)?;
let mut buf_read = BufReader::new(file);
let psbt: BdkPsbt = BdkPsbt::deserialize_from_reader(&mut buf_read)?;
Ok(Psbt(Mutex::new(psbt)))
}
/// Serialize the PSBT into a base64-encoded string.
pub fn serialize(&self) -> String {
let psbt = self.0.lock().unwrap().clone();
psbt.to_string()
}
/// Extracts the `Transaction` from a `Psbt` by filling in the available signature information.
///
/// #### Errors
///
/// `ExtractTxError` variants will contain either the `Psbt` itself or the `Transaction`
/// that was extracted. These can be extracted from the Errors in order to recover.
/// See the error documentation for info on the variants. In general, it covers large fees.
pub fn extract_tx(&self) -> Result<Arc<Transaction>, ExtractTxError> {
let tx: BdkTransaction = self.0.lock().unwrap().clone().extract_tx()?;
let transaction: Transaction = tx.into();
Ok(Arc::new(transaction))
}
/// Calculates transaction fee.
///
/// 'Fee' being the amount that will be paid for mining a transaction with the current inputs
/// and outputs i.e., the difference in value of the total inputs and the total outputs.
///
/// #### Errors
///
/// - `MissingUtxo` when UTXO information for any input is not present or is invalid.
/// - `NegativeFee` if calculated value is negative.
/// - `FeeOverflow` if an integer overflow occurs.
pub fn fee(&self) -> Result<u64, PsbtError> {
self.0
.lock()
.unwrap()
.fee()
.map(|fee| fee.to_sat())
.map_err(PsbtError::from)
}
/// Combines this `Psbt` with `other` PSBT as described by BIP 174.
///
/// In accordance with BIP 174 this function is commutative i.e., `A.combine(B) == B.combine(A)`
pub fn combine(&self, other: Arc<Psbt>) -> Result<Arc<Psbt>, PsbtError> {
let mut original_psbt = self.0.lock().unwrap().clone();
let other_psbt = other.0.lock().unwrap().clone();
original_psbt.combine(other_psbt)?;
Ok(Arc::new(Psbt(Mutex::new(original_psbt))))
}
/// Finalizes the current PSBT and produces a result indicating
///
/// whether the finalization was successful or not.
pub fn finalize(&self) -> FinalizedPsbtResult {
let curve = Secp256k1::verification_only();
let finalized = self.0.lock().unwrap().clone().finalize(&curve);
match finalized {
Ok(psbt) => FinalizedPsbtResult {
psbt: Arc::new(psbt.into()),
could_finalize: true,
errors: None,
},
Err((psbt, errors)) => {
let errors = errors.into_iter().map(|e| e.into()).collect();
FinalizedPsbtResult {
psbt: Arc::new(psbt.into()),
could_finalize: false,
errors: Some(errors),
}
}
}
}
/// Write the `Psbt` to a file. Note that the file must not yet exist.
pub fn write_to_file(&self, path: String) -> Result<(), PsbtError> {
let file = File::create_new(path)?;
let mut writer = BufWriter::new(file);
let psbt = self.0.lock().unwrap();
psbt.serialize_to_writer(&mut writer)?;
Ok(())
}
/// Serializes the PSBT into a JSON string representation.
pub fn json_serialize(&self) -> String {
let psbt = self.0.lock().unwrap();
serde_json::to_string(psbt.deref()).unwrap()
}
/// Returns the spending utxo for this PSBT's input at `input_index`.
pub fn spend_utxo(&self, input_index: u64) -> String {
let psbt = self.0.lock().unwrap();
let utxo = psbt.spend_utxo(input_index as usize).unwrap();
serde_json::to_string(&utxo).unwrap()
}
/// The corresponding key-value map for each input in the unsigned transaction.
pub fn input(&self) -> Vec<Input> {
let psbt = self.0.lock().unwrap();
psbt.inputs.iter().map(|input| input.into()).collect()
}
/// The corresponding key-value map for each output in the unsigned transaction.
pub fn output(&self) -> Vec<Output> {
let psbt = self.0.lock().unwrap();
psbt.outputs.iter().map(|o| o.into()).collect()
}
}
impl From<BdkPsbt> for Psbt {
fn from(psbt: BdkPsbt) -> Self {
Psbt(Mutex::new(psbt))
}
}
#[derive(uniffi::Record)]
pub struct FinalizedPsbtResult {
pub psbt: Arc<Psbt>,
pub could_finalize: bool,
pub errors: Option<Vec<PsbtFinalizeError>>,
}
/// A transcation input.
#[derive(Debug, Clone, uniffi::Record)]
pub struct TxIn {
/// A pointer to the previous output this input spends from.
pub previous_output: OutPoint,
/// The script corresponding to the `scriptPubKey`, empty in SegWit transactions.
pub script_sig: Arc<Script>,
/// https://bitcoin.stackexchange.com/questions/87372/what-does-the-sequence-in-a-transaction-input-mean
pub sequence: u32,
/// A proof for the script that authorizes the spend of the output.
pub witness: Vec<Vec<u8>>,
}
impl From<&BdkTxIn> for TxIn {
fn from(tx_in: &BdkTxIn) -> Self {
TxIn {
previous_output: OutPoint {
txid: Arc::new(Txid(tx_in.previous_output.txid)),
vout: tx_in.previous_output.vout,
},
script_sig: Arc::new(Script(tx_in.script_sig.clone())),
sequence: tx_in.sequence.0,
witness: tx_in.witness.to_vec(),
}
}
}
/// Bitcoin transaction output.
///
/// Defines new coins to be created as a result of the transaction,
/// along with spending conditions ("script", aka "output script"),
/// which an input spending it must satisfy.
///
/// An output that is not yet spent by an input is called Unspent Transaction Output ("UTXO").
#[derive(Debug, Clone, uniffi::Record)]
pub struct TxOut {
/// The value of the output, in satoshis.
pub value: Arc<Amount>,
/// The script which must be satisfied for the output to be spent.
pub script_pubkey: Arc<Script>,
}
impl From<&BdkTxOut> for TxOut {
fn from(tx_out: &BdkTxOut) -> Self {
TxOut {
value: Arc::new(Amount(tx_out.value)),
script_pubkey: Arc::new(Script(tx_out.script_pubkey.clone())),
}
}
}
impl From<BdkTxOut> for TxOut {
fn from(tx_out: BdkTxOut) -> Self {
Self {
value: Arc::new(Amount(tx_out.value)),
script_pubkey: Arc::new(Script(tx_out.script_pubkey)),
}
}
}
impl From<TxOut> for BdkTxOut {
fn from(tx_out: TxOut) -> Self {
Self {
value: tx_out.value.0,
script_pubkey: tx_out.script_pubkey.0.clone(),
}
}
}
/// A child number in a derivation path
#[derive(Copy, Clone, uniffi::Enum)]
pub enum ChildNumber {
/// Non-hardened key
Normal {
/// Key index, within [0, 2^31 - 1]
index: u32,
},
/// Hardened key
Hardened {
/// Key index, within [0, 2^31 - 1]
index: u32,
},
}
impl From<BdkChildNumber> for ChildNumber {
fn from(value: BdkChildNumber) -> Self {
match value {
BdkChildNumber::Normal { index } => ChildNumber::Normal { index },
BdkChildNumber::Hardened { index } => ChildNumber::Hardened { index },
}
}
}
impl TryFrom<ChildNumber> for BdkChildNumber {
type Error = Bip32Error;
fn try_from(value: ChildNumber) -> Result<Self, Self::Error> {
match value {
ChildNumber::Normal { index } => {
BdkChildNumber::from_normal_idx(index).map_err(Bip32Error::from)
}
ChildNumber::Hardened { index } => {
BdkChildNumber::from_hardened_idx(index).map_err(Bip32Error::from)
}
}
}
}
/// A bitcoin Block hash
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, std::hash::Hash, uniffi::Object)]
#[uniffi::export(Display, Eq, Hash, Ord)]
pub struct BlockHash(pub(crate) BitcoinBlockHash);
impl_hash_like!(BlockHash, BitcoinBlockHash);
/// A bitcoin transaction identifier
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, std::hash::Hash, uniffi::Object)]
#[uniffi::export(Display, Eq, Hash, Ord)]
pub struct Txid(pub(crate) BitcoinTxid);
impl_hash_like!(Txid, BitcoinTxid);
/// A bitcoin transaction identifier, including witness data.
/// For transactions with no SegWit inputs, the `txid` will be equivalent to `wtxid`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, std::hash::Hash, uniffi::Object)]
#[uniffi::export(Display, Eq, Hash, Ord)]
pub struct Wtxid(pub(crate) BitcoinWtxid);
impl_hash_like!(Wtxid, BitcoinWtxid);
/// A collision-proof unique identifier for a descriptor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, std::hash::Hash, uniffi::Object)]
#[uniffi::export(Display, Eq, Hash, Ord)]
pub struct DescriptorId(pub(crate) BitcoinSha256Hash);
impl_hash_like!(DescriptorId, BitcoinSha256Hash);
/// The merkle root of the merkle tree corresponding to a block's transactions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, std::hash::Hash, uniffi::Object)]
#[uniffi::export(Display, Eq, Hash, Ord)]
pub struct TxMerkleNode(pub(crate) BitcoinDoubleSha256Hash);
impl_hash_like!(TxMerkleNode, BitcoinDoubleSha256Hash);
/// Descriptor Type of the descriptor
#[uniffi::remote(Enum)]
pub enum DescriptorType {
/// Bare descriptor(Contains the native P2pk)
Bare,
/// Pure Sh Descriptor. Does not contain nested Wsh/Wpkh
Sh,
/// Pkh Descriptor
Pkh,
/// Wpkh Descriptor
Wpkh,
/// Wsh
Wsh,
/// Sh Wrapped Wsh
ShWsh,
/// Sh wrapped Wpkh
ShWpkh,
/// Sh Sorted Multi
ShSortedMulti,
/// Wsh Sorted Multi
WshSortedMulti,
/// Sh Wsh Sorted Multi
ShWshSortedMulti,
/// Tr Descriptor
Tr,
}