Skip to content

Commit 40e6ecf

Browse files
feat: add WalletConnect v2 Sign API
This change adds WalletConnect v2 Sign API, as per: https://specs.walletconnect.com/2.0/specs/clients/sign/ Please note that although the specification is fairly thorough, there are some inconsistencies. This implementation is derived from specs, analyzing ws traffic in browsers devtools, as well as the original WalletConnect JavaScript client at: https://github.com/WalletConnect/walletconnect-monorepo Design decisions: Modularity: - RPC and crypto modules are not dependent on each other, so client implementations don't have to use their own crypto implementation. Closes: #47
1 parent 6c2dc10 commit 40e6ecf

18 files changed

+1168
-2
lines changed

Cargo.toml

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,21 @@ license = "Apache-2.0"
99
[workspace]
1010
members = [
1111
"relay_client",
12-
"relay_rpc"
12+
"relay_rpc",
13+
"sign_api"
1314
]
1415

1516
[features]
1617
default = ["full"]
17-
full = ["client", "rpc"]
18+
full = ["client", "rpc", "sign_api"]
1819
client = ["dep:relay_client"]
1920
rpc = ["dep:relay_rpc"]
21+
sign_api = ["dep:sign_api"]
2022

2123
[dependencies]
2224
relay_client = { path = "./relay_client", optional = true }
2325
relay_rpc = { path = "./relay_rpc", optional = true }
26+
sign_api = { path = "./sign_api", optional = true }
2427

2528
[dev-dependencies]
2629
anyhow = "1"

sign_api/Cargo.toml

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
[package]
2+
name = "sign_api"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
[dependencies]
7+
anyhow = "1"
8+
base58 = "0.2"
9+
base64 = "0.21"
10+
base64-url = "2.0"
11+
chacha20poly1305 = "0.10"
12+
chrono = "0.4"
13+
hex = "0.4"
14+
hex-literal = "0.4"
15+
hkdf = "0.12"
16+
lazy_static = "1.4"
17+
once_cell = "1.16"
18+
paste = "1.0"
19+
rand = "0.8"
20+
regex = "1.10"
21+
sha2 = "0.10"
22+
serde = { version = "1.0", features = ["derive", "rc"] }
23+
serde_json = "1.0"
24+
thiserror = "1.0"
25+
x25519-dalek = { version = "2.0", features = ["static_secrets"] }
26+
url = "2.4"

sign_api/src/crypto.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
pub mod payload;
2+
pub mod session;

sign_api/src/crypto/payload.rs

Lines changed: 227 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,227 @@
1+
use anyhow::Result;
2+
use base64::prelude::BASE64_STANDARD;
3+
use base64::Engine;
4+
use chacha20poly1305::aead::{Aead, KeyInit, OsRng, Payload};
5+
use chacha20poly1305::{AeadCore, ChaCha20Poly1305, Nonce};
6+
7+
const TYPE_0: u8 = 0;
8+
const TYPE_1: u8 = 1;
9+
const TYPE_INDEX: usize = 0;
10+
const TYPE_LENGTH: usize = 1;
11+
const IV_LENGTH: usize = 12;
12+
const PUB_KEY_LENGTH: usize = 32;
13+
const SYM_KEY_LENGTH: usize = 32;
14+
15+
pub type Iv = [u8; IV_LENGTH];
16+
pub type SymKey = [u8; SYM_KEY_LENGTH];
17+
pub type PubKey = [u8; PUB_KEY_LENGTH];
18+
19+
#[derive(Clone, Debug, PartialEq, Eq)]
20+
pub enum EnvelopeType<'a> {
21+
Type0,
22+
Type1 { sender_public_key: &'a PubKey },
23+
}
24+
25+
#[derive(Clone, Debug, PartialEq, Eq)]
26+
struct EncodingParams<'a> {
27+
sealed: &'a [u8],
28+
iv: &'a Iv,
29+
envelope_type: EnvelopeType<'a>,
30+
}
31+
32+
impl<'a> EncodingParams<'a> {
33+
fn parse_decoded(data: &'a [u8]) -> Result<Self> {
34+
let envelope_type = data[0];
35+
match envelope_type {
36+
TYPE_0 => {
37+
let iv_index: usize = TYPE_INDEX + TYPE_LENGTH;
38+
let sealed_index: usize = iv_index + IV_LENGTH;
39+
Ok(EncodingParams {
40+
iv: data[iv_index..=IV_LENGTH].try_into()?,
41+
sealed: &data[sealed_index..],
42+
envelope_type: EnvelopeType::Type0,
43+
})
44+
}
45+
TYPE_1 => {
46+
let key_index: usize = TYPE_INDEX + TYPE_LENGTH;
47+
let iv_index: usize = key_index + PUB_KEY_LENGTH;
48+
let sealed_index: usize = iv_index + IV_LENGTH;
49+
Ok(EncodingParams {
50+
iv: data[iv_index..=IV_LENGTH].try_into()?,
51+
sealed: &data[sealed_index..],
52+
envelope_type: EnvelopeType::Type1 {
53+
sender_public_key: data[key_index..=PUB_KEY_LENGTH].try_into()?,
54+
},
55+
})
56+
}
57+
_ => anyhow::bail!("Invalid envelope type: {}", envelope_type),
58+
}
59+
}
60+
}
61+
62+
// TODO: RNG as an input
63+
pub fn encrypt_and_encode<T>(envelope_type: EnvelopeType, msg: T, key: &SymKey) -> Result<String>
64+
where
65+
T: AsRef<[u8]>,
66+
{
67+
let payload = Payload {
68+
msg: msg.as_ref(),
69+
aad: &[],
70+
};
71+
let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng);
72+
73+
let sealed = encrypt(&nonce, payload, key)?;
74+
Ok(encode(
75+
envelope_type,
76+
sealed.as_slice(),
77+
nonce.as_slice().try_into()?,
78+
))
79+
}
80+
81+
pub fn decode_and_decrypt_type0<T>(msg: T, key: &SymKey) -> Result<String>
82+
where
83+
T: AsRef<[u8]>,
84+
{
85+
let data = BASE64_STANDARD.decode(msg)?;
86+
let decoded = EncodingParams::parse_decoded(&data)?;
87+
if let EnvelopeType::Type1 { .. } = decoded.envelope_type {
88+
anyhow::bail!("Expected envelope type 0");
89+
}
90+
91+
let payload = Payload {
92+
msg: decoded.sealed,
93+
aad: &[],
94+
};
95+
let decrypted = decrypt(decoded.iv.try_into()?, payload, key)?;
96+
97+
Ok(String::from_utf8(decrypted)?)
98+
}
99+
100+
fn encrypt(nonce: &Nonce, payload: Payload<'_, '_>, key: &SymKey) -> Result<Vec<u8>> {
101+
let cipher = ChaCha20Poly1305::new(key.try_into()?);
102+
let sealed = cipher
103+
.encrypt(nonce, payload)
104+
.map_err(|e| anyhow::anyhow!("Encryption failed, err: {:?}", e))?;
105+
106+
Ok(sealed)
107+
}
108+
109+
fn encode(envelope_type: EnvelopeType, sealed: &[u8], iv: &Iv) -> String {
110+
match envelope_type {
111+
EnvelopeType::Type0 => BASE64_STANDARD.encode([&[TYPE_0], iv.as_slice(), sealed].concat()),
112+
EnvelopeType::Type1 { sender_public_key } => {
113+
BASE64_STANDARD.encode([&[TYPE_1], sender_public_key.as_slice(), iv, sealed].concat())
114+
}
115+
}
116+
}
117+
118+
fn decrypt(nonce: &Nonce, payload: Payload<'_, '_>, key: &SymKey) -> Result<Vec<u8>> {
119+
let cipher = ChaCha20Poly1305::new(key.try_into()?);
120+
let unsealed = cipher
121+
.decrypt(nonce, payload)
122+
.map_err(|e| anyhow::anyhow!("Decryption failed, err: {:?}", e))?;
123+
124+
Ok(unsealed)
125+
}
126+
127+
#[cfg(test)]
128+
mod tests {
129+
use hex_literal::hex;
130+
131+
use super::*;
132+
133+
// https://www.rfc-editor.org/rfc/rfc7539#section-2.8.2
134+
// Below constans are taken from this section of the RFC.
135+
136+
const PLAINTEXT: &str = r#"Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it."#;
137+
const CIPHERTEXT: [u8; 114] = hex!(
138+
"d3 1a 8d 34 64 8e 60 db 7b 86 af bc 53 ef 7e c2
139+
a4 ad ed 51 29 6e 08 fe a9 e2 b5 a7 36 ee 62 d6
140+
3d be a4 5e 8c a9 67 12 82 fa fb 69 da 92 72 8b
141+
1a 71 de 0a 9e 06 0b 29 05 d6 a5 b6 7e cd 3b 36
142+
92 dd bd 7f 2d 77 8b 8c 98 03 ae e3 28 09 1b 58
143+
fa b3 24 e4 fa d6 75 94 55 85 80 8b 48 31 d7 bc
144+
3f f4 de f0 8e 4b 7a 9d e5 76 d2 65 86 ce c6 4b
145+
61 16"
146+
);
147+
const TAG: [u8; 16] = hex!("1a e1 0b 59 4f 09 e2 6a 7e 90 2e cb d0 60 06 91");
148+
const SYMKEY: SymKey = hex!(
149+
"80 81 82 83 84 85 86 87 88 89 8a 8b 8c 8d 8e 8f
150+
90 91 92 93 94 95 96 97 98 99 9a 9b 9c 9d 9e 9f"
151+
);
152+
const AAD: [u8; 12] = hex!("50 51 52 53 c0 c1 c2 c3 c4 c5 c6 c7");
153+
const IV: Iv = hex!("07 00 00 00 40 41 42 43 44 45 46 47");
154+
155+
/// Tests WCv2 encoding and decoding.
156+
#[test]
157+
fn test_decode_encoded() -> Result<()> {
158+
let iv: &Iv = IV.as_slice().try_into()?;
159+
let sealed = [CIPHERTEXT.as_slice(), TAG.as_slice()].concat();
160+
161+
let encoded = encode(EnvelopeType::Type0, &sealed, iv);
162+
assert_eq!(
163+
encoded,
164+
"AAcAAABAQUJDREVGR9MajTRkjmDbe4avvFPvfsKkre1RKW4I/qnitac27mLWPb6kXoypZxKC+vtp2pJyixpx3gqeBgspBdaltn7NOzaS3b1/LXeLjJgDruMoCRtY+rMk5PrWdZRVhYCLSDHXvD/03vCOS3qd5XbSZYbOxkthFhrhC1lPCeJqfpAuy9BgBpE="
165+
);
166+
167+
let data = BASE64_STANDARD.decode(&encoded)?;
168+
let decoded = EncodingParams::parse_decoded(&data)?;
169+
assert_eq!(decoded.envelope_type, EnvelopeType::Type0);
170+
assert_eq!(decoded.sealed, sealed);
171+
assert_eq!(decoded.iv, iv);
172+
173+
Ok(())
174+
}
175+
176+
/// Tests ChaCha20-Poly1305 encryption against the RFC test vector.
177+
///
178+
/// https://www.rfc-editor.org/rfc/rfc7539#section-2.8.2
179+
/// Please note that this test vector has an
180+
/// "Additional Authentication Data", in practice, we will likely
181+
/// be using this algorithm without "AAD".
182+
#[test]
183+
fn test_encryption() -> Result<()> {
184+
let payload = Payload {
185+
msg: PLAINTEXT.as_bytes(),
186+
aad: AAD.as_slice(),
187+
};
188+
let iv = IV.as_slice().try_into()?;
189+
190+
let sealed = encrypt(iv, payload, &SYMKEY)?;
191+
assert_eq!(sealed, [CIPHERTEXT.as_slice(), TAG.as_slice()].concat());
192+
193+
Ok(())
194+
}
195+
196+
/// Tests that encrypted message can be decrypted back.
197+
#[test]
198+
fn test_decrypt_encrypted() -> Result<()> {
199+
let iv = IV.as_slice().try_into()?;
200+
201+
let seal_payload = Payload {
202+
msg: PLAINTEXT.as_bytes(),
203+
aad: AAD.as_slice(),
204+
};
205+
let sealed = encrypt(iv, seal_payload, &SYMKEY)?;
206+
207+
let unseal_payload = Payload {
208+
msg: &sealed,
209+
aad: AAD.as_slice(),
210+
};
211+
let unsealed = decrypt(iv, unseal_payload, &SYMKEY)?;
212+
213+
assert_eq!(PLAINTEXT.to_string(), String::from_utf8(unsealed)?);
214+
215+
Ok(())
216+
}
217+
218+
/// Tests that plain text can be WCv2 serialized and deserialized back.
219+
#[test]
220+
fn test_encrypt_encode_decode_decrypt() -> Result<()> {
221+
let encoded = encrypt_and_encode(EnvelopeType::Type0, PLAINTEXT, &SYMKEY)?;
222+
let decoded = decode_and_decrypt_type0(&encoded, &SYMKEY)?;
223+
assert_eq!(decoded, PLAINTEXT);
224+
225+
Ok(())
226+
}
227+
}

sign_api/src/crypto/session.rs

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
use std::fmt::{Debug, Formatter};
2+
3+
use anyhow::Result;
4+
use hkdf::Hkdf;
5+
use rand::{rngs::OsRng, CryptoRng, RngCore};
6+
use sha2::{Digest, Sha256};
7+
use x25519_dalek::{EphemeralSecret, PublicKey};
8+
9+
pub struct SessionKey {
10+
sym_key: [u8; 32],
11+
public_key: PublicKey,
12+
}
13+
14+
impl Debug for SessionKey {
15+
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
16+
f.debug_struct("WalletConnectUrl")
17+
.field("sym_key", &"********")
18+
.field("public_key", &self.public_key)
19+
.finish()
20+
}
21+
}
22+
23+
impl SessionKey {
24+
pub fn from_osrng(sender_public_key: &[u8; 32]) -> Result<Self> {
25+
SessionKey::diffie_hellman(OsRng, sender_public_key)
26+
}
27+
28+
pub fn diffie_hellman<T>(csprng: T, sender_public_key: &[u8; 32]) -> Result<Self>
29+
where
30+
T: RngCore + CryptoRng,
31+
{
32+
let single_use_private_key = EphemeralSecret::random_from_rng(csprng);
33+
let public_key = PublicKey::from(&single_use_private_key);
34+
35+
let ikm = single_use_private_key.diffie_hellman(&PublicKey::from(*sender_public_key));
36+
37+
let mut session_sym_key = Self {
38+
sym_key: [0u8; 32],
39+
public_key,
40+
};
41+
let hk = Hkdf::<Sha256>::new(None, ikm.as_bytes());
42+
hk.expand(&[], &mut session_sym_key.sym_key)
43+
.map_err(|e| anyhow::anyhow!("Failed to generate SymKey: {e}"))?;
44+
45+
Ok(session_sym_key)
46+
}
47+
48+
pub fn symmetric_key(&self) -> &[u8; 32] {
49+
&self.sym_key
50+
}
51+
52+
pub fn diffie_public_key(&self) -> &[u8; 32] {
53+
self.public_key.as_bytes()
54+
}
55+
56+
pub fn generate_topic(&self) -> String {
57+
let mut hasher = Sha256::new();
58+
hasher.update(self.sym_key);
59+
hex::encode(hasher.finalize())
60+
}
61+
}

sign_api/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
pub mod crypto;
2+
pub mod pairing_uri;
3+
pub mod rpc;

0 commit comments

Comments
 (0)