ink_ir/ir/blake2.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
// Copyright (C) Use Ink (UK) Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use proc_macro2::TokenStream as TokenStream2;
use syn::spanned::Spanned as _;
/// Computes the BLAKE-2b 256-bit hash for the given input and stores it in output.
pub fn blake2b_256(input: &[u8], output: &mut [u8; 32]) {
    use ::blake2::digest::{
        consts::U32,
        Digest as _,
    };
    type Blake2b256 = ::blake2::Blake2b<U32>;
    let mut blake2 = Blake2b256::new();
    blake2.update(input);
    let result = blake2.finalize();
    output.copy_from_slice(&result);
}
/// Computes the BLAKE2b-256 bit hash of a string or byte string literal.
///
/// # Note
///
/// This is mainly used for analysis and codegen of the `blake2x256!` macro.
#[derive(Debug)]
pub struct Blake2x256Macro {
    hash: [u8; 32],
    input: syn::Lit,
}
impl Blake2x256Macro {
    /// Returns the underlying selector.
    pub fn hash(&self) -> [u8; 32] {
        self.hash
    }
    /// Returns the literal input of the BLAKE-2b hash.
    pub fn input(&self) -> &syn::Lit {
        &self.input
    }
}
impl TryFrom<TokenStream2> for Blake2x256Macro {
    type Error = syn::Error;
    fn try_from(input: TokenStream2) -> Result<Self, Self::Error> {
        let input_span = input.span();
        let lit = syn::parse2::<syn::Lit>(input).map_err(|error| {
            format_err!(
                input_span,
                "expected string or byte string literal as input: {}",
                error
            )
        })?;
        let input_bytes = match lit {
            syn::Lit::Str(ref lit_str) => lit_str.value().into_bytes(),
            syn::Lit::ByteStr(ref byte_str) => byte_str.value(),
            invalid => {
                return Err(format_err!(
                    invalid.span(),
                    "expected string or byte string literal as input. found {:?}",
                    invalid,
                ))
            }
        };
        let mut output = [0u8; 32];
        blake2b_256(&input_bytes, &mut output);
        Ok(Self {
            hash: output,
            input: lit,
        })
    }
}