Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add fast_merkle_root and AssetId type #19

Merged
merged 3 commits into from
Sep 20, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 123 additions & 0 deletions src/fast_merkle_root.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// Rust Elements Library
// Written in 2019 by
// The Elements developers
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//

use bitcoin::hashes::{sha256, Hash, HashEngine};

/// Calculate a single sha256 midstate hash of the given left and right leaves.
#[inline]
fn sha256midstate(left: &[u8], right: &[u8]) -> sha256::Midstate {
let mut engine = sha256::Hash::engine();
engine.input(left);
engine.input(right);
engine.midstate()
}

/// Compute the Merkle root of the give hashes using mid-state only.
/// The inputs must be byte slices of length 32.
/// Note that the merkle root calculated with this method is not the same as the
/// one computed by a normal SHA256(d) merkle root.
pub fn fast_merkle_root(leaves: &[[u8; 32]]) -> sha256::Midstate {
let mut result_hash = Default::default();
// Implementation based on ComputeFastMerkleRoot method in Elements Core.
if leaves.is_empty() {
return result_hash;
}

// inner is an array of eagerly computed subtree hashes, indexed by tree
// level (0 being the leaves).
// For example, when count is 25 (11001 in binary), inner[4] is the hash of
// the first 16 leaves, inner[3] of the next 8 leaves, and inner[0] equal to
// the last leaf. The other inner entries are undefined.
//
// First process all leaves into 'inner' values.
let mut inner: [sha256::Midstate; 32] = Default::default();
let mut count: u32 = 0;
while (count as usize) < leaves.len() {
let mut temp_hash = sha256::Midstate::from_inner(leaves[count as usize]);
count += 1;
// For each of the lower bits in count that are 0, do 1 step. Each
// corresponds to an inner value that existed before processing the
// current leaf, and each needs a hash to combine it.
let mut level = 0;
while count & (1u32 << level) == 0 {
temp_hash = sha256midstate(&inner[level][..], &temp_hash[..]);
level += 1;
}
// Store the resulting hash at inner position level.
inner[level] = temp_hash;
}

// Do a final 'sweep' over the rightmost branch of the tree to process
// odd levels, and reduce everything to a single top value.
// Level is the level (counted from the bottom) up to which we've sweeped.
//
// As long as bit number level in count is zero, skip it. It means there
// is nothing left at this level.
let mut level = 0;
while count & (1u32 << level) == 0 {
level += 1;
}
result_hash = inner[level];

while count != (1u32 << level) {
// If we reach this point, hash is an inner value that is not the top.
// We combine it with itself (Bitcoin's special rule for odd levels in
// the tree) to produce a higher level one.

// Increment count to the value it would have if two entries at this
// level had existed and propagate the result upwards accordingly.
count += 1 << level;
level += 1;
while count & (1u32 << level) == 0 {
result_hash = sha256midstate(&inner[level][..], &result_hash[..]);
level += 1;
}
}
// Return result.
result_hash
}

#[cfg(test)]
mod tests {
use super::fast_merkle_root;
use bitcoin::hashes::hex::FromHex;
use bitcoin::hashes::sha256;

#[test]
fn test_fast_merkle_root() {
// unit test vectors from Elements Core
let test_leaves = [
"b66b041650db0f297b53f8d93c0e8706925bf3323f8c59c14a6fac37bfdcd06f",
"99cb2fa68b2294ae133550a9f765fc755d71baa7b24389fed67d1ef3e5cb0255",
"257e1b2fa49dd15724c67bac4df7911d44f6689860aa9f65a881ae0a2f40a303",
"b67b0b9f093fa83d5e44b707ab962502b7ac58630e556951136196e65483bb80",
];

let test_roots = [
"0000000000000000000000000000000000000000000000000000000000000000",
"b66b041650db0f297b53f8d93c0e8706925bf3323f8c59c14a6fac37bfdcd06f",
"f752938da0cb71c051aabdd5a86658e8d0b7ac00e1c2074202d8d2a79d8a6cf6",
"245d364a28e9ad20d522c4a25ffc6a7369ab182f884e1c7dcd01aa3d32896bd3",
"317d6498574b6ca75ee0368ec3faec75e096e245bdd5f36e8726fa693f775dfc",
];

let mut leaves = vec![];
for i in 0..4 {
let root = fast_merkle_root(&leaves);
assert_eq!(root, FromHex::from_hex(&test_roots[i]).unwrap(), "root #{}", i);
leaves.push(sha256::Midstate::from_hex(&test_leaves[i]).unwrap().into_inner());
}
assert_eq!(fast_merkle_root(&leaves), FromHex::from_hex(test_roots[4]).unwrap());
}
}
214 changes: 214 additions & 0 deletions src/issuance.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
// Rust Elements Library
// Written in 2019 by
// The Elements developers
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//

//! Asset Issuance

use bitcoin::util::hash::BitcoinHash;
use bitcoin::hashes::{hex, sha256, Hash};
use fast_merkle_root::fast_merkle_root;
use transaction::OutPoint;

/// The zero hash.
const ZERO32: [u8; 32] = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
/// The one hash.
const ONE32: [u8; 32] = [
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
/// The two hash.
const TWO32: [u8; 32] = [
2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];

/// An issued asset ID.
#[derive(Copy, Clone, PartialEq, Eq, Default, PartialOrd, Ord, Hash)]
pub struct AssetId(sha256::Midstate);

impl AssetId {
/// Create an [AssetId] from its inner type.
pub fn from_inner(midstate: sha256::Midstate) -> AssetId {
AssetId(midstate)
}

/// Convert the [AssetId] into its inner type.
pub fn into_inner(self) -> sha256::Midstate {
self.0
}

/// Generate the asset entropy from the issuance prevout and the contract hash.
pub fn generate_asset_entropy(
prevout: OutPoint,
contract_hash: sha256::Hash,
) -> sha256::Midstate {
// E : entropy
// I : prevout
// C : contract
// E = H( H(I) || H(C) )
fast_merkle_root(&[prevout.bitcoin_hash().into_inner(), contract_hash.into_inner()])
}

/// Calculate the asset ID from the asset entropy.
pub fn from_entropy(entropy: sha256::Midstate) -> AssetId {
// H_a : asset tag
// E : entropy
// H_a = H( E || 0 )
AssetId(fast_merkle_root(&[entropy.into_inner(), ZERO32]))
}

/// Calculate the reissuance token asset ID from the asset entropy.
pub fn reissuance_token_from_entropy(entropy: sha256::Midstate, confidential: bool) -> AssetId {
// H_a : asset reissuance tag
// E : entropy
// if not fConfidential:
// H_a = H( E || 1 )
// else
// H_a = H( E || 2 )
let second = match confidential {
false => ONE32,
true => TWO32,
};
AssetId(fast_merkle_root(&[entropy.into_inner(), second]))
}
}

impl hex::FromHex for AssetId {
fn from_byte_iter<I>(iter: I) -> Result<Self, hex::Error>
where
I: Iterator<Item = Result<u8, hex::Error>> + ExactSizeIterator + DoubleEndedIterator,
{
sha256::Midstate::from_byte_iter(iter).map(AssetId)
}
}

impl ::std::fmt::Display for AssetId {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::std::fmt::Display::fmt(&self.0, f)
}
}

impl ::std::fmt::Debug for AssetId {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::std::fmt::Display::fmt(&self, f)
}
}

impl ::std::fmt::LowerHex for AssetId {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::std::fmt::LowerHex::fmt(&self.0, f)
}
}

#[cfg(feature = "serde")]
impl ::serde::Serialize for AssetId {
fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
use bitcoin::hashes::hex::ToHex;
if s.is_human_readable() {
s.serialize_str(&self.to_hex())
} else {
s.serialize_bytes(&self.0[..])
}
}
}

#[cfg(feature = "serde")]
impl<'de> ::serde::Deserialize<'de> for AssetId {
fn deserialize<D: ::serde::Deserializer<'de>>(d: D) -> Result<AssetId, D::Error> {
use bitcoin::hashes::hex::FromHex;

if d.is_human_readable() {
struct HexVisitor;

impl<'de> ::serde::de::Visitor<'de> for HexVisitor {
type Value = AssetId;

fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
formatter.write_str("an ASCII hex string")
}

fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: ::serde::de::Error,
{
if let Ok(hex) = ::std::str::from_utf8(v) {
AssetId::from_hex(hex).map_err(E::custom)
} else {
return Err(E::invalid_value(::serde::de::Unexpected::Bytes(v), &self));
}
}

fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: ::serde::de::Error,
{
AssetId::from_hex(v).map_err(E::custom)
}
}

d.deserialize_str(HexVisitor)
} else {
struct BytesVisitor;

impl<'de> ::serde::de::Visitor<'de> for BytesVisitor {
type Value = AssetId;

fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
formatter.write_str("a bytestring")
}

fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: ::serde::de::Error,
{
if v.len() != 32 {
Err(E::invalid_length(v.len(), &stringify!($len)))
} else {
let mut ret = [0; 32];
ret.copy_from_slice(v);
Ok(AssetId(sha256::Midstate::from_inner(ret)))
}
}
}

d.deserialize_bytes(BytesVisitor)
}
}
}

#[cfg(test)]
mod test {
use super::*;
use std::str::FromStr;

use bitcoin::hashes::hex::FromHex;
use bitcoin::hashes::sha256;

#[test]
fn example_elements_core() {
// example test data from Elements Core 0.17
let prevout_str = "05a047c98e82a848dee94efcf32462b065198bebf2404d201ba2e06db30b28f4:0";
let entropy_hex = "746f447f691323502cad2ef646f932613d37a83aeaa2133185b316648df4b70a";
let asset_id_hex = "dcd60818d863b5c026c40b2bc3ba6fdaf5018bcc8606c18adf7db4da0bcd8533";
let token_id_hex = "c1adb114f4f87d33bf9ce90dd4f9ca523dd414d6cd010a7917903e2009689530";

let contract_hash = sha256::Hash::from_inner(ZERO32);
let prevout = OutPoint::from_str(prevout_str).unwrap();
let entropy = sha256::Midstate::from_hex(entropy_hex).unwrap();
assert_eq!(AssetId::generate_asset_entropy(prevout, contract_hash), entropy);
let asset_id = AssetId::from_hex(asset_id_hex).unwrap();
assert_eq!(AssetId::from_entropy(entropy), asset_id);
let token_id = AssetId::from_hex(token_id_hex).unwrap();
assert_eq!(AssetId::reissuance_token_from_entropy(entropy, false), token_id);
}
}
4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ mod block;
pub mod confidential;
pub mod dynafed;
pub mod encode;
mod fast_merkle_root;
pub mod issuance;
mod transaction;

// export everything at the top level so it can be used as `elements::Transaction` etc.
Expand All @@ -46,4 +48,6 @@ pub use transaction::{OutPoint, PeginData, PegoutData, TxIn, TxOut, TxInWitness,
pub use block::{BlockHeader, Block};
pub use block::ExtData as BlockExtData;
pub use ::bitcoin::consensus::encode::VarInt;
pub use fast_merkle_root::fast_merkle_root;
pub use issuance::AssetId;

Loading