用rust开始eth,打开钱包签个名

  • 晓道
  • 更新于 2022-07-10 16:16
  • 阅读 3299

用rust开始eth, ethers-rs,打开钱包,签个名。

首先感谢登链社区给赠送的NFT,来这里认识了不少朋友,收了一些朋友给发的红包,感谢大家。

前段一直挺忙,有段时间周六还在上班,然后自己也一直在学习,好久没有分享点新知识。

以前跟群友吹过,我写点文章,主要就把自己学的会的做个记录。

最近半年,我比较关注foundry 项目,然后也自己动手,修改过一些foundry的代码,其实也没什么意思,也就换门语言而已。为什么就没有遇上多少社区朋友搞的rust的优秀开源项目呢,估计还是基础的问题,所以遇到优秀基础项目的就给大家分享分享。

在读foundry代码的时候,也顺便学习了foundry项目使用的ethers-rs) ,这个项目虽然新,但是很优秀,paradigm 公司搞的不少项目都构建在ethers-rs的基础上。

知名的有:

在开始rust开发之前,推广一下我的nvim配置自用配置 用nvim开发rust感觉很好,还给朋友安利过helix,这用起来也挺不错,nvim配置好了更好一些。

为什么要用rust搞eth, 主要就因为rust快那么一点点,我看国内搞个三明治攻击都挺卷的,也就是需要比别人快那么一点点。

这次就从打开钱包,签个名开始吧。

1,依赖添加

[dependencies]
anyhow = { version = "1" }
ethers = "0.13.0"
ethers-core = "0.13.0"
ethers-signers = "0.13"
rand = "0.8"
md5 = "0.7"
hex = "0.4"

2,打开钱包

use anyhow::Result; //导入包

use std::path::Path;
use ethers_signers::{Signer, to_eip155_v, Wallet};
use ethers_core::{
    k256::ecdsa::{self, SigningKey},
    utils::keccak256,
};
let dir = "./keystore/key"; //keystore的钱包路径
    let wallet = Wallet::<SigningKey>::decrypt_keystore(&dir,"123456")?; //参数2是钱包密码

3,签名一段数据

let digest = md5::compute(b"\"hello2\"");
    let k256 = keccak256(&digest[0..8]).into();
    let mut sig = wallet.sign_hash(k256);//里面有对recover_id加27操作
    sig.v =sig.v -27;// to_eip155_v(sig.v as u8 - 27, 1);
    let signstr = sig.to_vec();
    println!("{:?} {:?}",key,hex::encode(signstr));

我这里使用的sign_hash函数,其实ethers-rs还提供了sign_message函数,使用起来更简单

let signature = wallet.sign_message("hello world").await?;
signature.verify("hello world", wallet.address()).unwrap();

sign_message也是使用sign_hash来实现,签名时候加上了, const PREFIX: &str = "\x19Ethereum Signed Message:\n";

rust可以搞的事情挺多的,比如生成个钱包啥的,别的不说,比python生成个钱包快个10倍还是很轻松的。 来点代码。

use ethers_core::rand::thread_rng;
use ethers_signers::{LocalWallet, Signer};
let wallet = LocalWallet::new(&mut thread_rng());
let wallet = wallet.with_chain_id(1u64);

文档在这里 ether-rs

rust还是挺简单吧,大家一起耍耍 !!!

大家有什么好想法可以留言,有项目代码需要解读也可以留言。

点赞 1
收藏 1
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
晓道
晓道
0xdD09...9161
技术交流:https://t.me/realDAO