secp256r1 c语言程序,rust代码阅读 之 libsecp256k1 (1)

在密码学的运算中, 数字通常是非常大的. 以 ECDSA 椭圆曲线为例, 私钥是 256 位的.

所以在 libsecp256k1 这个库里, 定义了计算的元素 Field. 其中 n 为 320 位.

pub struct Field {

pub(crate) n: [u32; 10],

pub(crate) magnitude: u32,

pub(crate) normalized: bool,

}

为其实现加法运算符, 即 Add 和 AddAssign 特征:

impl AddAssign for Field {

fn add_assign(&mut self, other: &'a Field) {

self.n[0] += other.n[0];

self.n[1] += other.n[1];

self.n[2] += other.n[2];

self.n[3] += other.n[3];

self.n[4] += other.n[4];

self.n[5] += other.n[5];

self.n[6] += other.n[6];

self.n[7] += other.n[7];

self.n[8] += other.n[8];

self.n[9] += other.n[9];

self.magnitude += other.magnitude;

self.normalized = false;

debug_assert!(self.verify());

}

}

在 rust 里, 想要让某个 struct 可以进行某种运算, 例如加法, 只需要实现对应的 Trait 即可, 非常方便. 另外, 每种 Trait 的标识包括名称和类型签名. 一样的名称, 可以有不一样的类型签名.

小贴士: 这里 debug_assert! 宏是只在未开启优化的编译包中才有效.

Field 可以被压缩成 FieldStorage, 也就是我们常见的 256 位. 便于存储.

pub struct FieldStorage(pub [u32; 8]);

impl Into for Field {

fn into(self) -> FieldStorage {

debug_assert!(self.normalized);

let mut r = FieldStorage::default();

r.0[0] = self.n[0] | self.n[1] << 26;

...

r

}

}

小贴士: 定义 struct 的时候可以用上面这种方法直接以 tuple 作为项.