Skip to content

Commit

Permalink
save dev state
Browse files Browse the repository at this point in the history
  • Loading branch information
borngraced committed Nov 20, 2024
1 parent af89011 commit 52e21fd
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 44 deletions.
17 changes: 11 additions & 6 deletions mm2src/mm2_bitcoin/crypto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,39 +34,44 @@ pub enum ChecksumType {
pub fn ripemd160(input: &[u8]) -> H160 {
let mut hasher = Ripemd160::new();
hasher.update(input);
(*hasher.finalize()).into()
let array: [u8; 20] = hasher.finalize().into();
array.into()
}

/// SHA-1
#[inline]
pub fn sha1(input: &[u8]) -> H160 {
let mut hasher = Sha1::default();
let mut hasher = Sha1::new();
hasher.update(input);
(*hasher.finalize()).into()
let array: [u8; 20] = hasher.finalize().into();
array.into()
}

/// SHA-256
#[inline]
pub fn sha256(input: &[u8]) -> H256 {
let mut hasher = Sha256::new();
hasher.update(input);
(*hasher.finalize()).into()
let array: [u8; 32] = hasher.finalize().into();
array.into()
}

/// Groestl-512
#[inline]
pub fn groestl512(input: &[u8]) -> H512 {
let mut hasher = Groestl512::new();
hasher.update(input);
(*hasher.finalize()).into()
let array: [u8; 64] = hasher.finalize().into();
array.into()
}

/// Keccak-256
#[inline]
pub fn keccak256(input: &[u8]) -> H256 {
let mut hasher = Keccak256::new();
hasher.update(input);
(*hasher.finalize()).into()
let array: [u8; 32] = hasher.finalize().into();
array.into()
}

/// Double Keccak-256
Expand Down
11 changes: 8 additions & 3 deletions mm2src/mm2_bitcoin/keys/src/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@

use hash::H520;
use hex::{FromHex, ToHex};
use std::{fmt, ops, str};
use std::convert::TryInto;
use std::{array::TryFromSliceError, convert::TryFrom, fmt, ops, str};
use Error;

#[derive(PartialEq, Clone)]
Expand Down Expand Up @@ -91,6 +92,10 @@ impl From<H520> for CompactSignature {
fn from(h: H520) -> Self { CompactSignature(h) }
}

impl From<Vec<u8>> for CompactSignature {
fn from(v: Vec<u8>) -> Self { CompactSignature(H520::from(&v[..])) }
impl TryFrom<Vec<u8>> for CompactSignature {
type Error = TryFromSliceError;
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
let bytes: &[u8; 65] = &value.as_slice().try_into()?;
Ok(CompactSignature(H520::from(bytes)))
}
}
26 changes: 14 additions & 12 deletions mm2src/mm2_bitcoin/primitives/src/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

use bitcoin_hashes::{sha256d, Hash as ExtHash};
use hex::{FromHex, FromHexError, ToHex};
use std::convert::TryInto;
use std::hash::{Hash, Hasher};
use std::{cmp, fmt, ops, str};
use uint::core_::convert::TryFrom;

macro_rules! impl_hash {
($name: ident, $size: expr) => {
Expand Down Expand Up @@ -39,10 +41,10 @@ macro_rules! impl_hash {
fn from(h: $name) -> Self { h.0 }
}

impl<'a> From<&'a [u8]> for $name {
fn from(slc: &[u8]) -> Self {
impl<'a> From<&'a [u8; $size]> for $name {
fn from(slc: &[u8; $size]) -> Self {
let mut inner = [0u8; $size];
inner[..].clone_from_slice(&slc[0..$size]);
inner.copy_from_slice(slc);
$name(inner)
}
}
Expand All @@ -61,17 +63,9 @@ macro_rules! impl_hash {

impl str::FromStr for $name {
type Err = FromHexError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let vec: Vec<u8> = s.from_hex()?;
match vec.len() {
$size => {
let mut result = [0u8; $size];
result.copy_from_slice(&vec);
Ok($name(result))
},
_ => Err(FromHexError::InvalidHexLength),
}
Self::from_slice(&vec).map_err(|_| FromHexError::InvalidHexLength)
}
}

Expand Down Expand Up @@ -143,6 +137,14 @@ macro_rules! impl_hash {
pub fn size() -> usize { $size }

pub fn is_zero(&self) -> bool { self.0.iter().all(|b| *b == 0) }

/// Preferred method for constructing from a slice - checks length and returns Result
pub fn from_slice(slc: &[u8]) -> Result<Self, &'static str> {
let bytes: [u8; $size] = slc
.try_into()
.map_err(|_| "Slice length must be exactly 40 bytes")?;
Ok(bytes.into())
}
}
};
}
Expand Down
29 changes: 17 additions & 12 deletions mm2src/mm2_bitcoin/script/src/script.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Serialized script, used inside transaction inputs and outputs.

use bytes::Bytes;
use chain::hash::{H160, H256};
use keys::{self, AddressHashEnum, Public};
use std::{fmt, ops};
use {Error, Opcode};
Expand Down Expand Up @@ -425,12 +426,14 @@ impl Script {
))]
})
},
ScriptType::PubKeyHash => Ok(vec![ScriptAddress::new_p2pkh(AddressHashEnum::AddressHash(
self.data[3..23].into(),
))]),
ScriptType::ScriptHash => Ok(vec![ScriptAddress::new_p2sh(AddressHashEnum::AddressHash(
self.data[2..22].into(),
))]),
ScriptType::PubKeyHash => {
let hash = H160::from_slice(&self.data[3..32]).map_err(|_| keys::Error::InvalidAddress)?;
Ok(vec![ScriptAddress::new_p2pkh(AddressHashEnum::AddressHash(hash))])
},
ScriptType::ScriptHash => {
let hash = H160::from_slice(&self.data[2..22]).map_err(|_| keys::Error::InvalidAddress)?;
Ok(vec![ScriptAddress::new_p2sh(AddressHashEnum::AddressHash(hash))])
},
ScriptType::Multisig => {
let mut addresses: Vec<ScriptAddress> = Vec::new();
let mut pc = 1;
Expand All @@ -448,12 +451,14 @@ impl Script {
Ok(addresses)
},
ScriptType::NullData => Ok(vec![]),
ScriptType::WitnessScript => Ok(vec![ScriptAddress::new_p2wsh(AddressHashEnum::WitnessScriptHash(
self.data[2..34].into(),
))]),
ScriptType::WitnessKey => Ok(vec![ScriptAddress::new_p2wpkh(AddressHashEnum::AddressHash(
self.data[2..22].into(),
))]),
ScriptType::WitnessScript => {
let hash = H256::from_slice(&self.data[2..34]).map_err(|_| keys::Error::WitnessHashMismatched)?;
Ok(vec![ScriptAddress::new_p2wsh(AddressHashEnum::WitnessScriptHash(hash))])
},
ScriptType::WitnessKey => {
let hash = H160::from_slice(&self.data[2..22]).map_err(|_| keys::Error::InvalidAddress)?;
Ok(vec![ScriptAddress::new_p2wpkh(AddressHashEnum::AddressHash(hash))])
},
ScriptType::CallSender => {
Ok(vec![]) // TODO
},
Expand Down
22 changes: 11 additions & 11 deletions mm2src/mm2_bitcoin/script/src/sign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,7 @@ impl TransactionInputSigner {
sig_hash_stream.append(&blake_2b_256_personal(
&prev_out_stream.out(),
ZCASH_PREVOUTS_HASH_PERSONALIZATION,
));
)?);
} else {
sig_hash_stream.append(&H256::default());
}
Expand All @@ -480,7 +480,7 @@ impl TransactionInputSigner {
sig_hash_stream.append(&blake_2b_256_personal(
&sequence_stream.out(),
ZCASH_SEQUENCE_HASH_PERSONALIZATION,
));
)?);
} else {
sig_hash_stream.append(&H256::default());
}
Expand All @@ -494,15 +494,15 @@ impl TransactionInputSigner {
sig_hash_stream.append(&blake_2b_256_personal(
&outputs_stream.out(),
ZCASH_OUTPUTS_HASH_PERSONALIZATION,
));
)?);
} else if sighash.base == SighashBase::Single && input_index < self.outputs.len() {
let mut outputs_stream = Stream::new();
outputs_stream.append(&self.outputs[input_index]);

sig_hash_stream.append(&blake_2b_256_personal(
&outputs_stream.out(),
ZCASH_OUTPUTS_HASH_PERSONALIZATION,
));
)?);
} else {
sig_hash_stream.append(&H256::default());
}
Expand All @@ -515,7 +515,7 @@ impl TransactionInputSigner {
sig_hash_stream.append(&blake_2b_256_personal(
&join_splits_stream.out(),
ZCASH_JOIN_SPLITS_HASH_PERSONALIZATION,
));
)?);
} else {
sig_hash_stream.append(&H256::default());
}
Expand All @@ -533,7 +533,7 @@ impl TransactionInputSigner {
sig_hash_stream.append(&blake_2b_256_personal(
&s_spends_stream.out(),
ZCASH_SHIELDED_SPENDS_HASH_PERSONALIZATION,
));
)?);
} else {
sig_hash_stream.append(&H256::default());
}
Expand All @@ -544,7 +544,7 @@ impl TransactionInputSigner {
s_outputs_stream.append(output);
}
let hash_shielded_outputs =
blake_2b_256_personal(&s_outputs_stream.out(), ZCASH_SHIELDED_OUTPUTS_HASH_PERSONALIZATION);
blake_2b_256_personal(&s_outputs_stream.out(), ZCASH_SHIELDED_OUTPUTS_HASH_PERSONALIZATION)?;
sig_hash_stream.append(&hash_shielded_outputs);
} else {
sig_hash_stream.append(&H256::default());
Expand All @@ -560,7 +560,7 @@ impl TransactionInputSigner {
sig_hash_stream.append(&self.inputs[input_index].amount);
sig_hash_stream.append(&self.inputs[input_index].sequence);

Ok(blake_2b_256_personal(&sig_hash_stream.out(), &personalization))
Ok(blake_2b_256_personal(&sig_hash_stream.out(), &personalization)?)
}
}

Expand Down Expand Up @@ -608,8 +608,8 @@ fn compute_hash_outputs(sighash: Sighash, input_index: usize, outputs: &[Transac
}
}

fn blake_2b_256_personal(input: &[u8], personal: &[u8]) -> H256 {
H256::from(
fn blake_2b_256_personal(input: &[u8], personal: &[u8]) -> Result<H256, &'static str> {
H256::from_slice(
Blake2b::new()
.hash_length(32)
.personal(personal)
Expand Down Expand Up @@ -783,7 +783,7 @@ mod tests {

#[test]
fn test_blake_2b_personal() {
let hash = blake_2b_256_personal(b"", b"ZcashPrevoutHash");
let hash = blake_2b_256_personal(b"", b"ZcashPrevoutHash").unwrap();
assert_eq!(
H256::from("d53a633bbecf82fe9e9484d8a0e727c73bb9e68c96e72dec30144f6a84afa136"),
hash
Expand Down

0 comments on commit 52e21fd

Please sign in to comment.