ink_env/hash.rs
1// Copyright (C) Use Ink (UK) Ltd.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Provides type definitions and traits for the built-in cryptographic hashes.
16
17/// The output type of built-in cryptographic hash functions.
18pub trait HashOutput: private::Sealed {
19 /// The output type of the crypto hash.
20 ///
21 /// This should be a byte array with some constant size such as `[u8; 32]`.
22 type Type: Default;
23}
24
25/// Types that are usable as built-in cryptographic hashes.
26pub trait CryptoHash: HashOutput + private::Sealed {
27 /// Hashes the given raw byte input and copies the result into `output`.
28 fn hash(input: &[u8], output: &mut <Self as HashOutput>::Type);
29
30 /// Hashes the given raw byte input and copies the result into `output`.
31 ///
32 /// Utilizes `buffer`
33 fn hash_with_buffer(
34 input: &[u8],
35 buffer: &mut [u8],
36 output: &mut <Self as HashOutput>::Type,
37 );
38}
39
40/// The SHA-2 crypto hash with 256-bit output.
41#[derive(Debug, Copy, Clone, PartialEq, Eq)]
42pub enum Sha2x256 {}
43
44/// The KECCAK crypto hash with 256-bit output.
45#[derive(Debug, Copy, Clone, PartialEq, Eq)]
46pub enum Keccak256 {}
47
48/// The BLAKE-2 crypto hash with 256-bit output.
49#[derive(Debug, Copy, Clone, PartialEq, Eq)]
50pub enum Blake2x256 {}
51
52/// The BLAKE-2 crypto hash with 128-bit output.
53#[derive(Debug, Copy, Clone, PartialEq, Eq)]
54pub enum Blake2x128 {}
55
56mod private {
57 /// Seals the implementation of `CryptoHash` and `HashOutput`.
58 pub trait Sealed {}
59}
60
61impl private::Sealed for Sha2x256 {}
62impl private::Sealed for Keccak256 {}
63impl private::Sealed for Blake2x256 {}
64impl private::Sealed for Blake2x128 {}
65
66impl HashOutput for Sha2x256 {
67 type Type = [u8; 32];
68}
69
70impl HashOutput for Keccak256 {
71 type Type = [u8; 32];
72}
73
74impl HashOutput for Blake2x256 {
75 type Type = [u8; 32];
76}
77
78impl HashOutput for Blake2x128 {
79 type Type = [u8; 16];
80}