Made some idiomatic changes
This commit is contained in:
parent
3f2d428706
commit
a473d01b17
|
@ -78,7 +78,7 @@ impl Block {
|
||||||
if self.txdata.iter().all(|t| t.input.iter().all(|i| i.witness.is_empty())) {
|
if self.txdata.iter().all(|t| t.input.iter().all(|i| i.witness.is_empty())) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if self.txdata.len() > 0 {
|
if !self.txdata.is_empty() {
|
||||||
let coinbase = &self.txdata[0];
|
let coinbase = &self.txdata[0];
|
||||||
if coinbase.is_coin_base() {
|
if coinbase.is_coin_base() {
|
||||||
// commitment is in the last output that starts with below magic
|
// commitment is in the last output that starts with below magic
|
||||||
|
|
|
@ -162,7 +162,7 @@ pub fn serialize_hex<T: Encodable + ?Sized>(data: &T) -> String {
|
||||||
|
|
||||||
/// Deserialize an object from a vector, will error if said deserialization
|
/// Deserialize an object from a vector, will error if said deserialization
|
||||||
/// doesn't consume the entire vector.
|
/// doesn't consume the entire vector.
|
||||||
pub fn deserialize<'a, T: Decodable>(data: &'a [u8]) -> Result<T, Error> {
|
pub fn deserialize<T: Decodable>(data: &[u8]) -> Result<T, Error> {
|
||||||
let (rv, consumed) = deserialize_partial(data)?;
|
let (rv, consumed) = deserialize_partial(data)?;
|
||||||
|
|
||||||
// Fail if data are not consumed entirely.
|
// Fail if data are not consumed entirely.
|
||||||
|
@ -175,8 +175,8 @@ pub fn deserialize<'a, T: Decodable>(data: &'a [u8]) -> Result<T, Error> {
|
||||||
|
|
||||||
/// Deserialize an object from a vector, but will not report an error if said deserialization
|
/// Deserialize an object from a vector, but will not report an error if said deserialization
|
||||||
/// doesn't consume the entire vector.
|
/// doesn't consume the entire vector.
|
||||||
pub fn deserialize_partial<'a, T: Decodable>(
|
pub fn deserialize_partial<T: Decodable>(
|
||||||
data: &'a [u8],
|
data: &[u8],
|
||||||
) -> Result<(T, usize), Error> {
|
) -> Result<(T, usize), Error> {
|
||||||
let mut decoder = Cursor::new(data);
|
let mut decoder = Cursor::new(data);
|
||||||
let rv = Decodable::consensus_decode(&mut decoder)?;
|
let rv = Decodable::consensus_decode(&mut decoder)?;
|
||||||
|
|
|
@ -41,9 +41,9 @@ const ONION : [u16; 3] = [0xFD87, 0xD87E, 0xEB43];
|
||||||
impl Address {
|
impl Address {
|
||||||
/// Create an address message for a socket
|
/// Create an address message for a socket
|
||||||
pub fn new (socket :&SocketAddr, services: ServiceFlags) -> Address {
|
pub fn new (socket :&SocketAddr, services: ServiceFlags) -> Address {
|
||||||
let (address, port) = match socket {
|
let (address, port) = match *socket {
|
||||||
&SocketAddr::V4(ref addr) => (addr.ip().to_ipv6_mapped().segments(), addr.port()),
|
SocketAddr::V4(addr) => (addr.ip().to_ipv6_mapped().segments(), addr.port()),
|
||||||
&SocketAddr::V6(ref addr) => (addr.ip().segments(), addr.port())
|
SocketAddr::V6(addr) => (addr.ip().segments(), addr.port())
|
||||||
};
|
};
|
||||||
Address { address: address, port: port, services: services }
|
Address { address: address, port: port, services: services }
|
||||||
}
|
}
|
||||||
|
|
|
@ -72,9 +72,7 @@ impl Encodable for CommandString {
|
||||||
if strbytes.len() > 12 {
|
if strbytes.len() > 12 {
|
||||||
return Err(encode::Error::UnrecognizedNetworkCommand(self.0.clone().into_owned()));
|
return Err(encode::Error::UnrecognizedNetworkCommand(self.0.clone().into_owned()));
|
||||||
}
|
}
|
||||||
for x in 0..strbytes.len() {
|
rawbytes[..strbytes.len()].clone_from_slice(&strbytes[..]);
|
||||||
rawbytes[x] = strbytes[x];
|
|
||||||
}
|
|
||||||
rawbytes.consensus_encode(s)
|
rawbytes.consensus_encode(s)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -18,26 +18,22 @@
|
||||||
//! # Example: creating a new address from a randomly-generated key pair
|
//! # Example: creating a new address from a randomly-generated key pair
|
||||||
//!
|
//!
|
||||||
//! ```rust
|
//! ```rust
|
||||||
//! extern crate secp256k1;
|
|
||||||
//! extern crate bitcoin;
|
|
||||||
//!
|
//!
|
||||||
//! use bitcoin::network::constants::Network;
|
//! use bitcoin::network::constants::Network;
|
||||||
//! use bitcoin::util::address::Address;
|
//! use bitcoin::util::address::Address;
|
||||||
//! use bitcoin::util::key;
|
//! use bitcoin::util::key;
|
||||||
//! use secp256k1::Secp256k1;
|
//! use bitcoin::secp256k1::Secp256k1;
|
||||||
//! use secp256k1::rand::thread_rng;
|
//! use bitcoin::secp256k1::rand::thread_rng;
|
||||||
//!
|
//!
|
||||||
//! fn main() {
|
//! // Generate random key pair
|
||||||
//! // Generate random key pair
|
//! let s = Secp256k1::new();
|
||||||
//! let s = Secp256k1::new();
|
//! let public_key = key::PublicKey {
|
||||||
//! let public_key = key::PublicKey {
|
//! compressed: true,
|
||||||
//! compressed: true,
|
//! key: s.generate_keypair(&mut thread_rng()).1,
|
||||||
//! key: s.generate_keypair(&mut thread_rng()).1,
|
//! };
|
||||||
//! };
|
|
||||||
//!
|
//!
|
||||||
//! // Generate pay-to-pubkey-hash address
|
//! // Generate pay-to-pubkey-hash address
|
||||||
//! let address = Address::p2pkh(&public_key, Network::Bitcoin);
|
//! let address = Address::p2pkh(&public_key, Network::Bitcoin);
|
||||||
//! }
|
|
||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
use std::fmt::{self, Display, Formatter};
|
use std::fmt::{self, Display, Formatter};
|
||||||
|
@ -219,7 +215,7 @@ impl Payload {
|
||||||
assert!(ver.to_u8() <= 16);
|
assert!(ver.to_u8() <= 16);
|
||||||
let mut verop = ver.to_u8();
|
let mut verop = ver.to_u8();
|
||||||
if verop > 0 {
|
if verop > 0 {
|
||||||
verop = 0x50 + verop;
|
verop += 0x50;
|
||||||
}
|
}
|
||||||
script::Builder::new().push_opcode(verop.into()).push_slice(&prog)
|
script::Builder::new().push_opcode(verop.into()).push_slice(&prog)
|
||||||
}
|
}
|
||||||
|
@ -406,7 +402,7 @@ impl Display for Address {
|
||||||
/// Returns the same slice when no prefix is found.
|
/// Returns the same slice when no prefix is found.
|
||||||
fn find_bech32_prefix(bech32: &str) -> &str {
|
fn find_bech32_prefix(bech32: &str) -> &str {
|
||||||
// Split at the last occurrence of the separator character '1'.
|
// Split at the last occurrence of the separator character '1'.
|
||||||
match bech32.rfind("1") {
|
match bech32.rfind('1') {
|
||||||
None => bech32,
|
None => bech32,
|
||||||
Some(sep) => bech32.split_at(sep).0,
|
Some(sep) => bech32.split_at(sep).0,
|
||||||
}
|
}
|
||||||
|
@ -427,7 +423,7 @@ impl FromStr for Address {
|
||||||
if let Some(network) = bech32_network {
|
if let Some(network) = bech32_network {
|
||||||
// decode as bech32
|
// decode as bech32
|
||||||
let (_, payload) = bech32::decode(s)?;
|
let (_, payload) = bech32::decode(s)?;
|
||||||
if payload.len() == 0 {
|
if payload.is_empty() {
|
||||||
return Err(Error::EmptyBech32Payload);
|
return Err(Error::EmptyBech32Payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -19,6 +19,7 @@ use std::error;
|
||||||
use std::fmt::{self, Write};
|
use std::fmt::{self, Write};
|
||||||
use std::ops;
|
use std::ops;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
use std::cmp::Ordering;
|
||||||
|
|
||||||
/// A set of denominations in which amounts can be expressed.
|
/// A set of denominations in which amounts can be expressed.
|
||||||
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
|
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
|
||||||
|
@ -131,7 +132,7 @@ impl error::Error for ParseAmountError {
|
||||||
|
|
||||||
|
|
||||||
fn is_too_precise(s: &str, precision: usize) -> bool {
|
fn is_too_precise(s: &str, precision: usize) -> bool {
|
||||||
s.contains(".") || precision >= s.len() || s.chars().rev().take(precision).any(|d| d != '0')
|
s.contains('.') || precision >= s.len() || s.chars().rev().take(precision).any(|d| d != '0')
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parse decimal string in the given denomination into a satoshi value and a
|
/// Parse decimal string in the given denomination into a satoshi value and a
|
||||||
|
@ -140,14 +141,14 @@ fn parse_signed_to_satoshi(
|
||||||
mut s: &str,
|
mut s: &str,
|
||||||
denom: Denomination,
|
denom: Denomination,
|
||||||
) -> Result<(bool, u64), ParseAmountError> {
|
) -> Result<(bool, u64), ParseAmountError> {
|
||||||
if s.len() == 0 {
|
if s.is_empty() {
|
||||||
return Err(ParseAmountError::InvalidFormat);
|
return Err(ParseAmountError::InvalidFormat);
|
||||||
}
|
}
|
||||||
if s.len() > 50 {
|
if s.len() > 50 {
|
||||||
return Err(ParseAmountError::InputTooLarge);
|
return Err(ParseAmountError::InputTooLarge);
|
||||||
}
|
}
|
||||||
|
|
||||||
let is_negative = s.chars().next().unwrap() == '-';
|
let is_negative = s.starts_with('-');
|
||||||
if is_negative {
|
if is_negative {
|
||||||
if s.len() == 1 {
|
if s.len() == 1 {
|
||||||
return Err(ParseAmountError::InvalidFormat);
|
return Err(ParseAmountError::InvalidFormat);
|
||||||
|
@ -229,27 +230,29 @@ fn fmt_satoshi_in(
|
||||||
f.write_str("-")?;
|
f.write_str("-")?;
|
||||||
}
|
}
|
||||||
|
|
||||||
if denom.precision() > 0 {
|
let precision = denom.precision();
|
||||||
// add zeroes in the end
|
match precision.cmp(&0) {
|
||||||
let width = denom.precision() as usize;
|
Ordering::Greater => {
|
||||||
write!(f, "{}{:0width$}", satoshi, 0, width = width)?;
|
// add zeroes in the end
|
||||||
} else if denom.precision() < 0 {
|
let width = precision as usize;
|
||||||
// need to inject a comma in the number
|
write!(f, "{}{:0width$}", satoshi, 0, width = width)?;
|
||||||
let nb_decimals = denom.precision().abs() as usize;
|
|
||||||
let real = format!("{:0width$}", satoshi, width = nb_decimals);
|
|
||||||
if real.len() == nb_decimals {
|
|
||||||
write!(f, "0.{}", &real[real.len() - nb_decimals..])?;
|
|
||||||
} else {
|
|
||||||
write!(
|
|
||||||
f,
|
|
||||||
"{}.{}",
|
|
||||||
&real[0..(real.len() - nb_decimals)],
|
|
||||||
&real[real.len() - nb_decimals..]
|
|
||||||
)?;
|
|
||||||
}
|
}
|
||||||
} else {
|
Ordering::Less => {
|
||||||
// denom.precision() == 0
|
// need to inject a comma in the number
|
||||||
write!(f, "{}", satoshi)?;
|
let nb_decimals = precision.abs() as usize;
|
||||||
|
let real = format!("{:0width$}", satoshi, width = nb_decimals);
|
||||||
|
if real.len() == nb_decimals {
|
||||||
|
write!(f, "0.{}", &real[real.len() - nb_decimals..])?;
|
||||||
|
} else {
|
||||||
|
write!(
|
||||||
|
f,
|
||||||
|
"{}.{}",
|
||||||
|
&real[0..(real.len() - nb_decimals)],
|
||||||
|
&real[real.len() - nb_decimals..]
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ordering::Equal => write!(f, "{}", satoshi)?,
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -327,7 +330,7 @@ impl Amount {
|
||||||
/// If you want to parse only the amount without the denomination,
|
/// If you want to parse only the amount without the denomination,
|
||||||
/// use [from_str_in].
|
/// use [from_str_in].
|
||||||
pub fn from_str_with_denomination(s: &str) -> Result<Amount, ParseAmountError> {
|
pub fn from_str_with_denomination(s: &str) -> Result<Amount, ParseAmountError> {
|
||||||
let mut split = s.splitn(3, " ");
|
let mut split = s.splitn(3, ' ');
|
||||||
let amt_str = split.next().unwrap();
|
let amt_str = split.next().unwrap();
|
||||||
let denom_str = split.next().ok_or(ParseAmountError::InvalidFormat)?;
|
let denom_str = split.next().ok_or(ParseAmountError::InvalidFormat)?;
|
||||||
if split.next().is_some() {
|
if split.next().is_some() {
|
||||||
|
@ -614,7 +617,7 @@ impl SignedAmount {
|
||||||
return Err(ParseAmountError::TooBig);
|
return Err(ParseAmountError::TooBig);
|
||||||
}
|
}
|
||||||
Ok(match negative {
|
Ok(match negative {
|
||||||
true => SignedAmount(-1 * satoshi as i64),
|
true => SignedAmount(-(satoshi as i64)),
|
||||||
false => SignedAmount(satoshi as i64),
|
false => SignedAmount(satoshi as i64),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -624,7 +627,7 @@ impl SignedAmount {
|
||||||
/// If you want to parse only the amount without the denomination,
|
/// If you want to parse only the amount without the denomination,
|
||||||
/// use [from_str_in].
|
/// use [from_str_in].
|
||||||
pub fn from_str_with_denomination(s: &str) -> Result<SignedAmount, ParseAmountError> {
|
pub fn from_str_with_denomination(s: &str) -> Result<SignedAmount, ParseAmountError> {
|
||||||
let mut split = s.splitn(3, " ");
|
let mut split = s.splitn(3, ' ');
|
||||||
let amt_str = split.next().unwrap();
|
let amt_str = split.next().unwrap();
|
||||||
let denom_str = split.next().ok_or(ParseAmountError::InvalidFormat)?;
|
let denom_str = split.next().ok_or(ParseAmountError::InvalidFormat)?;
|
||||||
if split.next().is_some() {
|
if split.next().is_some() {
|
||||||
|
|
|
@ -103,7 +103,7 @@ impl<T: Default + Copy> SmallVec<T> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static BASE58_CHARS: &'static [u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
static BASE58_CHARS: &[u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
||||||
|
|
||||||
static BASE58_DIGITS: [Option<u8>; 128] = [
|
static BASE58_DIGITS: [Option<u8>; 128] = [
|
||||||
None, None, None, None, None, None, None, None, // 0-7
|
None, None, None, None, None, None, None, None, // 0-7
|
||||||
|
|
|
@ -49,6 +49,8 @@ use std::collections::HashSet;
|
||||||
use std::error;
|
use std::error;
|
||||||
use std::fmt::{Display, Formatter};
|
use std::fmt::{Display, Formatter};
|
||||||
use std::io::Cursor;
|
use std::io::Cursor;
|
||||||
|
use std::cmp::Ordering;
|
||||||
|
|
||||||
|
|
||||||
use hashes::{Hash, siphash24};
|
use hashes::{Hash, siphash24};
|
||||||
use hash_types::{BlockHash, FilterHash};
|
use hash_types::{BlockHash, FilterHash};
|
||||||
|
@ -260,17 +262,17 @@ impl GCSFilterReader {
|
||||||
let mut remaining = n_elements.0 - 1;
|
let mut remaining = n_elements.0 - 1;
|
||||||
for p in mapped {
|
for p in mapped {
|
||||||
loop {
|
loop {
|
||||||
if data == p {
|
match data.cmp(&p) {
|
||||||
return Ok(true);
|
Ordering::Equal => return Ok(true),
|
||||||
} else if data < p {
|
Ordering::Less => {
|
||||||
if remaining > 0 {
|
if remaining > 0 {
|
||||||
data += self.filter.golomb_rice_decode(&mut reader)?;
|
data += self.filter.golomb_rice_decode(&mut reader)?;
|
||||||
remaining -= 1;
|
remaining -= 1;
|
||||||
} else {
|
} else {
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
Ordering::Greater => break,
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -301,17 +303,17 @@ impl GCSFilterReader {
|
||||||
let mut remaining = n_elements.0 - 1;
|
let mut remaining = n_elements.0 - 1;
|
||||||
for p in mapped {
|
for p in mapped {
|
||||||
loop {
|
loop {
|
||||||
if data == p {
|
match data.cmp(&p) {
|
||||||
break;
|
Ordering::Equal => break,
|
||||||
} else if data < p {
|
Ordering::Less => {
|
||||||
if remaining > 0 {
|
if remaining > 0 {
|
||||||
data += self.filter.golomb_rice_decode(&mut reader)?;
|
data += self.filter.golomb_rice_decode(&mut reader)?;
|
||||||
remaining -= 1;
|
remaining -= 1;
|
||||||
} else {
|
} else {
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
}
|
}
|
||||||
} else {
|
},
|
||||||
return Ok(false);
|
Ordering::Greater => return Ok(false),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -423,7 +425,7 @@ impl GCSFilter {
|
||||||
q += 1;
|
q += 1;
|
||||||
}
|
}
|
||||||
let r = reader.read(self.p)?;
|
let r = reader.read(self.p)?;
|
||||||
return Ok((q << self.p) + r);
|
Ok((q << self.p) + r)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Hash an arbitrary slice with siphash using parameters of this filter
|
/// Hash an arbitrary slice with siphash using parameters of this filter
|
||||||
|
|
|
@ -179,13 +179,11 @@ impl FromStr for ChildNumber {
|
||||||
type Err = Error;
|
type Err = Error;
|
||||||
|
|
||||||
fn from_str(inp: &str) -> Result<ChildNumber, Error> {
|
fn from_str(inp: &str) -> Result<ChildNumber, Error> {
|
||||||
Ok(match inp.chars().last().map_or(false, |l| l == '\'' || l == 'h') {
|
let is_hardened = inp.chars().last().map_or(false, |l| l == '\'' || l == 'h');
|
||||||
true => ChildNumber::from_hardened_idx(
|
Ok(if is_hardened {
|
||||||
inp[0..inp.len() - 1].parse().map_err(|_| Error::InvalidChildNumberFormat)?
|
ChildNumber::from_hardened_idx(inp[0..inp.len() - 1].parse().map_err(|_| Error::InvalidChildNumberFormat)?)?
|
||||||
)?,
|
} else {
|
||||||
false => ChildNumber::from_normal_idx(
|
ChildNumber::from_normal_idx(inp.parse().map_err(|_| Error::InvalidChildNumberFormat)?)?
|
||||||
inp.parse().map_err(|_| Error::InvalidChildNumberFormat)?
|
|
||||||
)?,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -258,7 +256,7 @@ impl FromStr for DerivationPath {
|
||||||
type Err = Error;
|
type Err = Error;
|
||||||
|
|
||||||
fn from_str(path: &str) -> Result<DerivationPath, Error> {
|
fn from_str(path: &str) -> Result<DerivationPath, Error> {
|
||||||
let mut parts = path.split("/");
|
let mut parts = path.split('/');
|
||||||
// First parts must be `m`.
|
// First parts must be `m`.
|
||||||
if parts.next().unwrap() != "m" {
|
if parts.next().unwrap() != "m" {
|
||||||
return Err(Error::InvalidDerivationPathFormat);
|
return Err(Error::InvalidDerivationPathFormat);
|
||||||
|
@ -292,11 +290,7 @@ impl<'a> Iterator for DerivationPathIterator<'a> {
|
||||||
type Item = DerivationPath;
|
type Item = DerivationPath;
|
||||||
|
|
||||||
fn next(&mut self) -> Option<Self::Item> {
|
fn next(&mut self) -> Option<Self::Item> {
|
||||||
if self.next_child.is_none() {
|
let ret = self.next_child?;
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let ret = self.next_child.unwrap();
|
|
||||||
self.next_child = ret.increment().ok();
|
self.next_child = ret.increment().ok();
|
||||||
Some(self.base.child(ret))
|
Some(self.base.child(ret))
|
||||||
}
|
}
|
||||||
|
|
|
@ -30,7 +30,7 @@ pub fn bitcoin_merkle_root_inline<T>(data: &mut [T]) -> T
|
||||||
<T as Hash>::Engine: io::Write,
|
<T as Hash>::Engine: io::Write,
|
||||||
{
|
{
|
||||||
// Base case
|
// Base case
|
||||||
if data.len() < 1 {
|
if data.is_empty() {
|
||||||
return Default::default();
|
return Default::default();
|
||||||
}
|
}
|
||||||
if data.len() < 2 {
|
if data.len() < 2 {
|
||||||
|
|
|
@ -25,12 +25,10 @@
|
||||||
//! # Examples
|
//! # Examples
|
||||||
//!
|
//!
|
||||||
//! ```rust
|
//! ```rust
|
||||||
//! extern crate bitcoin;
|
|
||||||
//! use bitcoin::hash_types::Txid;
|
//! use bitcoin::hash_types::Txid;
|
||||||
//! use bitcoin::hashes::hex::FromHex;
|
//! use bitcoin::hashes::hex::FromHex;
|
||||||
//! use bitcoin::{Block, MerkleBlock};
|
//! use bitcoin::{Block, MerkleBlock};
|
||||||
//!
|
//!
|
||||||
//! # fn main() {
|
|
||||||
//! // Get the proof from a bitcoind by running in the terminal:
|
//! // Get the proof from a bitcoind by running in the terminal:
|
||||||
//! // $ TXID="5a4ebf66822b0b2d56bd9dc64ece0bc38ee7844a23ff1d7320a88c5fdb2ad3e2"
|
//! // $ TXID="5a4ebf66822b0b2d56bd9dc64ece0bc38ee7844a23ff1d7320a88c5fdb2ad3e2"
|
||||||
//! // $ bitcoin-cli gettxoutproof [\"$TXID\"]
|
//! // $ bitcoin-cli gettxoutproof [\"$TXID\"]
|
||||||
|
@ -52,7 +50,6 @@
|
||||||
//! );
|
//! );
|
||||||
//! assert_eq!(1, index.len());
|
//! assert_eq!(1, index.len());
|
||||||
//! assert_eq!(1, index[0]);
|
//! assert_eq!(1, index[0]);
|
||||||
//! # }
|
|
||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
|
@ -133,12 +130,10 @@ impl PartialMerkleTree {
|
||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// extern crate bitcoin;
|
|
||||||
/// use bitcoin::hash_types::Txid;
|
/// use bitcoin::hash_types::Txid;
|
||||||
/// use bitcoin::hashes::hex::FromHex;
|
/// use bitcoin::hashes::hex::FromHex;
|
||||||
/// use bitcoin::util::merkleblock::PartialMerkleTree;
|
/// use bitcoin::util::merkleblock::PartialMerkleTree;
|
||||||
///
|
///
|
||||||
/// # fn main() {
|
|
||||||
/// // Block 80000
|
/// // Block 80000
|
||||||
/// let txids: Vec<Txid> = [
|
/// let txids: Vec<Txid> = [
|
||||||
/// "c06fbab289f723c6261d3030ddb6be121f7d2508d77862bb1e484f5cd7f92b25",
|
/// "c06fbab289f723c6261d3030ddb6be121f7d2508d77862bb1e484f5cd7f92b25",
|
||||||
|
@ -152,7 +147,6 @@ impl PartialMerkleTree {
|
||||||
/// let matches = vec![false, true];
|
/// let matches = vec![false, true];
|
||||||
/// let tree = PartialMerkleTree::from_txids(&txids, &matches);
|
/// let tree = PartialMerkleTree::from_txids(&txids, &matches);
|
||||||
/// assert!(tree.extract_matches(&mut vec![], &mut vec![]).is_ok());
|
/// assert!(tree.extract_matches(&mut vec![], &mut vec![]).is_ok());
|
||||||
/// # }
|
|
||||||
/// ```
|
/// ```
|
||||||
pub fn from_txids(txids: &[Txid], matches: &[bool]) -> Self {
|
pub fn from_txids(txids: &[Txid], matches: &[bool]) -> Self {
|
||||||
// We can never have zero txs in a merkle block, we always need the coinbase tx
|
// We can never have zero txs in a merkle block, we always need the coinbase tx
|
||||||
|
@ -271,7 +265,7 @@ impl PartialMerkleTree {
|
||||||
if height == 0 || !parent_of_match {
|
if height == 0 || !parent_of_match {
|
||||||
// If at height 0, or nothing interesting below, store hash and stop
|
// If at height 0, or nothing interesting below, store hash and stop
|
||||||
let hash = self.calc_hash(height, pos, txids);
|
let hash = self.calc_hash(height, pos, txids);
|
||||||
self.hashes.push(hash.into());
|
self.hashes.push(hash);
|
||||||
} else {
|
} else {
|
||||||
// Otherwise, don't store any hash, but descend into the subtrees
|
// Otherwise, don't store any hash, but descend into the subtrees
|
||||||
self.traverse_and_build(height - 1, pos * 2, txids, matches);
|
self.traverse_and_build(height - 1, pos * 2, txids, matches);
|
||||||
|
@ -407,12 +401,10 @@ impl MerkleBlock {
|
||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// extern crate bitcoin;
|
|
||||||
/// use bitcoin::hash_types::Txid;
|
/// use bitcoin::hash_types::Txid;
|
||||||
/// use bitcoin::hashes::hex::FromHex;
|
/// use bitcoin::hashes::hex::FromHex;
|
||||||
/// use bitcoin::{Block, MerkleBlock};
|
/// use bitcoin::{Block, MerkleBlock};
|
||||||
///
|
///
|
||||||
/// # fn main() {
|
|
||||||
/// // Block 80000
|
/// // Block 80000
|
||||||
/// let block_bytes = Vec::from_hex("01000000ba8b9cda965dd8e536670f9ddec10e53aab14b20bacad2\
|
/// let block_bytes = Vec::from_hex("01000000ba8b9cda965dd8e536670f9ddec10e53aab14b20bacad2\
|
||||||
/// 7b9137190000000000190760b278fe7b8565fda3b968b918d5fd997f993b23674c0af3b6fde300b38f33\
|
/// 7b9137190000000000190760b278fe7b8565fda3b968b918d5fd997f993b23674c0af3b6fde300b38f33\
|
||||||
|
@ -437,7 +429,6 @@ impl MerkleBlock {
|
||||||
/// let mut index: Vec<u32> = vec![];
|
/// let mut index: Vec<u32> = vec![];
|
||||||
/// assert!(mb.extract_matches(&mut matches, &mut index).is_ok());
|
/// assert!(mb.extract_matches(&mut matches, &mut index).is_ok());
|
||||||
/// assert_eq!(txid, matches[0]);
|
/// assert_eq!(txid, matches[0]);
|
||||||
/// # }
|
|
||||||
/// ```
|
/// ```
|
||||||
pub fn from_block(block: &Block, match_txids: &HashSet<Txid>) -> Self {
|
pub fn from_block(block: &Block, match_txids: &HashSet<Txid>) -> Self {
|
||||||
let header = block.header;
|
let header = block.header;
|
||||||
|
|
|
@ -20,14 +20,14 @@ use hashes::{sha256d, Hash};
|
||||||
use blockdata::opcodes;
|
use blockdata::opcodes;
|
||||||
use consensus::encode;
|
use consensus::encode;
|
||||||
|
|
||||||
static MSG_SIGN_PREFIX: &'static [u8] = b"\x18Bitcoin Signed Message:\n";
|
static MSG_SIGN_PREFIX: &[u8] = b"\x18Bitcoin Signed Message:\n";
|
||||||
|
|
||||||
/// Search for `needle` in the vector `haystack` and remove every
|
/// Search for `needle` in the vector `haystack` and remove every
|
||||||
/// instance of it, returning the number of instances removed.
|
/// instance of it, returning the number of instances removed.
|
||||||
/// Loops through the vector opcode by opcode, skipping pushed data.
|
/// Loops through the vector opcode by opcode, skipping pushed data.
|
||||||
pub fn script_find_and_remove(haystack: &mut Vec<u8>, needle: &[u8]) -> usize {
|
pub fn script_find_and_remove(haystack: &mut Vec<u8>, needle: &[u8]) -> usize {
|
||||||
if needle.len() > haystack.len() { return 0; }
|
if needle.len() > haystack.len() { return 0; }
|
||||||
if needle.len() == 0 { return 0; }
|
if needle.is_empty() { return 0; }
|
||||||
|
|
||||||
let mut top = haystack.len() - needle.len();
|
let mut top = haystack.len() - needle.len();
|
||||||
let mut n_deleted = 0;
|
let mut n_deleted = 0;
|
||||||
|
|
|
@ -104,7 +104,7 @@ macro_rules! impl_psbtmap_consensus_enc_dec_oding {
|
||||||
macro_rules! impl_psbt_insert_pair {
|
macro_rules! impl_psbt_insert_pair {
|
||||||
($slf:ident.$unkeyed_name:ident <= <$raw_key:ident: _>|<$raw_value:ident: $unkeyed_value_type:ty>) => {
|
($slf:ident.$unkeyed_name:ident <= <$raw_key:ident: _>|<$raw_value:ident: $unkeyed_value_type:ty>) => {
|
||||||
if $raw_key.key.is_empty() {
|
if $raw_key.key.is_empty() {
|
||||||
if let None = $slf.$unkeyed_name {
|
if $slf.$unkeyed_name.is_none() {
|
||||||
let val: $unkeyed_value_type = ::util::psbt::serialize::Deserialize::deserialize(&$raw_value)?;
|
let val: $unkeyed_value_type = ::util::psbt::serialize::Deserialize::deserialize(&$raw_value)?;
|
||||||
|
|
||||||
$slf.$unkeyed_name = Some(val)
|
$slf.$unkeyed_name = Some(val)
|
||||||
|
|
Loading…
Reference in New Issue