pchain_sdk/
crypto.rs

1/*
2    Copyright © 2023, ParallelChain Lab 
3    Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
4*/
5
6//! Defines runtime-supported cryptographic functions. What cryptgraphic functions have in common 
7//! is that the operations they implement are: 1. Relatively expensive, and 2. Relatively common in Contract applications. 
8//! In order to reduce gas costs, these functions are implemented in native (not-WASM) code that lives outside of the 
9//! WASM runtime, and exposed to calls through the handles defined in this module.
10
11use crate::imports;
12
13/// Computes the SHA256 digest (32 bytes) of arbitrary input.
14pub fn sha256(input: Vec<u8>) -> Vec<u8>{
15    let input_ptr = input.as_ptr();
16
17    let mut val_ptr: u32 = 0;
18    let val_ptr_ptr = &mut val_ptr;
19
20    unsafe {
21        imports::sha256(input_ptr, input.len() as u32, val_ptr_ptr);
22        Vec::<u8>::from_raw_parts(val_ptr as *mut u8, 32, 32)
23    }
24}
25
26/// Computes the Keccak256 digest (32 bytes) of arbitrary input.
27pub fn keccak256(input: Vec<u8>) -> Vec<u8>{
28    let input_ptr = input.as_ptr();
29
30    let mut val_ptr: u32 = 0;
31    let val_ptr_ptr = &mut val_ptr;
32
33    unsafe {
34        imports::keccak256(input_ptr, input.len() as u32, val_ptr_ptr);
35        Vec::<u8>::from_raw_parts(val_ptr as *mut u8,  32, 32)
36    }
37}
38
39/// Computes the RIPEMD160 digest (20 bytes) of arbitrary input.
40pub fn ripemd(input: Vec<u8>) -> Vec<u8>{
41    let input_ptr = input.as_ptr();
42
43    let mut val_ptr: u32 = 0;
44    let val_ptr_ptr = &mut val_ptr;
45
46    unsafe {
47        imports::ripemd(input_ptr, input.len() as u32, val_ptr_ptr);
48        Vec::<u8>::from_raw_parts(val_ptr as *mut u8, 20, 20)
49    }
50}
51
52/// Returns whether an Ed25519 signature was produced by a specified by a specified address over some specified message.
53/// Contract call fails if the input `address` or `signature` is not valid.
54pub fn verify_ed25519_signature(input: Vec<u8>, signature: Vec<u8>, address: Vec<u8>) -> bool {
55    let input_ptr = input.as_ptr();
56    let signature_ptr = signature.as_ptr();
57    let address_ptr = address.as_ptr();
58
59    let value;
60    unsafe {
61        value = imports::verify_ed25519_signature(input_ptr, input.len() as u32, signature_ptr, address_ptr);
62    }
63
64    value != 0
65}