Struggling with secp256k1

Hi everyone,
As my first project on Rust i'm trying to build a simple blockchain, but i'm stumbling into some stones along the way hahaha.
I've created a struct:

pub struct Output {
    pub sender: String,
    pub receiver: String,
    pub amount: u64,
    pub signature: String,
    pub spent: Cell<bool>,
}

but when i'm trying to make the signature, the unwrap() method always fails on me:

Error:

thread 'main' panicked at src\output.rs:32:79:
called `Result::unwrap()` on an `Err` value: InvalidMessage
//signs the message
    fn sign(&mut self, secret_key: &SecretKey) {
        let secp = Secp256k1::new();
        let message = self.create_message();
        let signature = secp.sign_ecdsa(&Message::from_digest_slice(&message).unwrap(), secret_key); //error happens here
        
        self.signature = signature.to_string();
    }

    //creates a message in bytes
    fn create_message(&self) -> Vec<u8> {
        let mut bytes = Vec::new();
        bytes.extend(self.sender.as_bytes());
        bytes.extend(self.receiver.as_bytes());
        bytes.extend(self.amount.to_le_bytes());
        bytes
    }

i'm not quite getting why. Sorry for any newbie stuff, i'm actually newbie.

Hi,
According to the document secp256k1, you need to create digest using sha256 hash before you can sign it.

use secp256k1::hashes::{sha256, Hash};
use secp256k1::rand::rngs::OsRng;
use secp256k1::{Message, Secp256k1, SecretKey};


  // other code 
  fn sign(&mut self, secret_key: &SecretKey) {
    // message created above
    let digest = sha256::Hash::hash(&message);
    let signature = secp.sign_ecdsa(
        &Message::from_digest_slice(&digest.to_byte_array()).unwrap(),
        secret_key,
    );
    // rest of code
  }

Remember to enable features
secp256k1 = {version="0.29.0", features=["rand-std", "hashes-std"] }

It's unworthy to use ECC any more, you should use Lattice-based asymmetric-key cryptography, Lattice-based ciphers can be post-quantum. NSA suggests using Kyber and Dilithium.

1 Like

Thank you! The problem was enabling the features, documentation was not very clear about that (or maybe I missed it).

1 Like

Thanks for the tip, will take a look on that. Since it's only for learning purposes i'm ok, but always good to learn the right way.