Skip to content

Commit

Permalink
Add seed constant to contract ID (#26)
Browse files Browse the repository at this point in the history
  • Loading branch information
vlopes11 authored and xgreenx committed Dec 20, 2022
1 parent 595cf45 commit c828653
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 6 deletions.
56 changes: 52 additions & 4 deletions fuel-tx/src/crypto.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,58 @@
use crate::Bytes32;
use sha2::{Digest, Sha256};

pub fn hash(data: &[u8]) -> Bytes32 {
let mut hasher = Sha256::new();
use std::iter;

hasher.update(data);
#[derive(Debug, Default, Clone)]
pub struct Hasher(Sha256);

<[u8; Bytes32::size_of()]>::from(hasher.finalize()).into()
impl Hasher {
pub fn input<B>(&mut self, data: B)
where
B: AsRef<[u8]>,
{
self.0.update(data)
}

pub fn chain<B>(self, data: B) -> Self
where
B: AsRef<[u8]>,
{
Self(self.0.chain(data))
}

pub fn reset(&mut self) {
self.0.reset();
}

pub fn hash<B>(data: B) -> Bytes32
where
B: AsRef<[u8]>,
{
let mut hasher = Sha256::new();

hasher.update(data);

<[u8; Bytes32::size_of()]>::from(hasher.finalize()).into()
}

pub fn digest(&self) -> Bytes32 {
<[u8; Bytes32::size_of()]>::from(self.0.clone().finalize()).into()
}
}

impl<B> iter::FromIterator<B> for Hasher
where
B: AsRef<[u8]>,
{
fn from_iter<T>(iter: T) -> Self
where
T: IntoIterator<Item = B>,
{
let mut hasher = Hasher::default();

iter.into_iter().for_each(|i| hasher.input(i));

hasher
}
}
4 changes: 2 additions & 2 deletions fuel-tx/src/transaction/id.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::{Bytes32, Input, Metadata, Output, Transaction, Witness};
use crate::bytes::SerializableVec;
use crate::crypto;
use crate::crypto::Hasher;

impl Transaction {
pub(crate) fn inputs_mut(&mut self) -> &mut [Input] {
Expand Down Expand Up @@ -35,7 +35,7 @@ impl Transaction {
let mut tx = self.clone();
tx.prepare_sign();

crypto::hash(tx.to_bytes().as_slice())
Hasher::hash(tx.to_bytes().as_slice())
}

fn prepare_sign(&mut self) {
Expand Down
4 changes: 4 additions & 0 deletions fuel-tx/src/transaction/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,7 @@ key!(Color, 32);
key!(ContractId, 32);
key!(Bytes32, 32);
key!(Salt, 32);

impl ContractId {
pub const SEED: [u8; 4] = 0x4655454C_u32.to_be_bytes();
}

0 comments on commit c828653

Please sign in to comment.