1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
use pyo3::{prelude::*, pyclass::CompareOp, types::PyBytes};
use solana_sdk::signer::{
keypair::{
keypair_from_seed, keypair_from_seed_phrase_and_passphrase, Keypair as KeypairOriginal,
},
Signer as SignerTrait,
};
use crate::{
calculate_hash, handle_py_value_err, pubkey::Pubkey, signature::Signature, RichcmpSigner,
Signer, SignerTraitWrapper, ToSignerOriginal,
};
#[pyclass(module = "solders.keypair", subclass)]
#[derive(PartialEq, Debug)]
/// A vanilla Ed25519 key pair.
///
/// Calling ``Keypair()`` creates a new, random ``Keypair``.
///
/// Example:
/// >>> from solders.keypair import Keypair
/// >>> assert Keypair() != Keypair()
///
pub struct Keypair(pub KeypairOriginal);
#[pymethods]
impl Keypair {
#[classattr]
/// The length of a keypair in bytes.
const LENGTH: usize = 64;
#[new]
/// Constructs a new, random ``Keypair`` using ``OsRng``
pub fn new() -> Self {
KeypairOriginal::new().into()
}
/// Recovers a ``Keypair`` from bytes.
///
/// Args:
/// raw_bytes (bytes): a 64-byte keypair.
///
/// Returns:
/// Keypair: a keypair object.
///
/// Example:
/// >>> from solders.keypair import Keypair
/// >>> kp = Keypair()
/// >>> assert kp == Keypair.from_bytes(bytes(kp))
///
#[staticmethod]
pub fn from_bytes(raw_bytes: [u8; Self::LENGTH]) -> PyResult<Self> {
handle_py_value_err(KeypairOriginal::from_bytes(&raw_bytes))
}
/// Returns this ``Keypair`` as a byte array.
///
/// Returns:
/// list[int]: the keypair as a list of 64 u8 ints.
///
/// Example:
/// >>> from solders.keypair import Keypair
/// >>> raw_bytes = bytes([1] * 64)
/// >>> assert Keypair.from_bytes(raw_bytes).to_bytes_array() == list(raw_bytes)
///
pub fn to_bytes_array(&self) -> [u8; Self::LENGTH] {
self.0.to_bytes()
}
pub fn __bytes__<'a>(&self, py: Python<'a>) -> &'a PyBytes {
PyBytes::new(py, self.to_bytes_array().as_slice())
}
#[staticmethod]
/// Recovers a ``Keypair`` from a base58-encoded string.
///
/// Args:
/// s (str): The base58-encoded string.
///
/// Returns:
/// Keypair: a keypair oject.
///
/// Example:
/// >>> from solders.keypair import Keypair
/// >>> raw_bytes = bytes([0] * 64)
/// >>> base58_str = "1" * 64
/// >>> kp = Keypair.from_base58_string(base58_str)
/// >>> assert kp == Keypair.from_bytes(raw_bytes)
/// >>> assert str(kp) == base58_str
///
pub fn from_base58_string(s: &str) -> Self {
KeypairOriginal::from_base58_string(s).into()
}
/// Gets this ``Keypair``'s secret key.
///
/// Returns:
/// bytes: The secret key in 32 bytes.
///
/// Example:
/// >>> from solders.keypair import Keypair
/// >>> kp = Keypair()
/// >>> assert kp.secret() == bytes(kp)[:32]
///
pub fn secret(&self) -> &[u8] {
self.0.secret().as_ref()
}
pub fn __str__(&self) -> String {
self.0.to_base58_string()
}
#[pyo3(name = "pubkey")]
/// Get this keypair's :class:`~solders.pubkey.Pubkey`.
///
/// Returns:
/// Pubkey: the pubkey of this keypair.
///
/// Example:
/// >>> from solders.keypair import Keypair
/// >>> from solders.pubkey import Pubkey
/// >>> seed_bytes = bytes([0] * 32)
/// >>> pubkey_bytes = bytes([1] * 32)
/// >>> kp = Keypair.from_bytes(seed_bytes + pubkey_bytes)
/// >>> assert kp.pubkey() == Pubkey(pubkey_bytes)
///
pub fn py_pubkey(&self) -> Pubkey {
self.pubkey().into()
}
#[pyo3(name = "sign_message")]
/// Sign a mesage with this keypair, producing an Ed25519 signature over the provided message bytes.
///
/// Args:
/// message (bytes): The message to sign.
///
/// Returns:
/// Signature: The Ed25519 signature.
///
/// Example:
/// >>> from solders.keypair import Keypair
/// >>> seed = bytes([1] * 32)
/// >>> keypair = Keypair.from_seed(seed)
/// >>> msg = b"hello"
/// >>> sig = keypair.sign_message(msg)
/// >>> bytes(sig).hex()
/// 'e1430c6ebd0d53573b5c803452174f8991ef5955e0906a09e8fdc7310459e9c82a402526748c3431fe7f0e5faafbf7e703234789734063ee42be17af16438d08'
///
pub fn py_sign_message(&self, message: &[u8]) -> Signature {
self.sign_message(message).into()
}
#[staticmethod]
/// Generate a keypair from a 32-byte seed.
///
/// Args:
/// seed (bytes): 32-byte seed.
/// Returns:
/// Keypair: The generated keypair.
///
/// Example:
/// >>> from solders.keypair import Keypair
/// >>> from solders.pubkey import Pubkey
/// >>> seed_bytes = bytes([0] * 32)
/// >>> from_seed = Keypair.from_seed(seed_bytes)
/// >>> from_bytes = Keypair.from_bytes(seed_bytes + bytes(from_seed.pubkey()))
/// >>> assert from_seed == from_bytes
///
pub fn from_seed(seed: [u8; 32]) -> PyResult<Self> {
handle_py_value_err(keypair_from_seed(&seed))
}
#[staticmethod]
/// Generate a keypair from a seed phrase and passphrase.
///
/// Args:
/// seed_phrase (string): Secret seed phrase.
/// passphrase (string): Passphrase.
///
/// Example:
/// >>> from pybip39 import Mnemonic, Seed
/// >>> from solders.keypair import Keypair
/// >>> mnemonic = Mnemonic()
/// >>> passphrase = "42"
/// >>> seed = Seed(mnemonic, passphrase)
/// >>> expected_keypair = Keypair.from_seed(bytes(seed)[:32])
/// >>> keypair = Keypair.from_seed_phrase_and_passphrase(mnemonic.phrase, passphrase)
/// >>> assert keypair.pubkey() == expected_keypair.pubkey()
///
pub fn from_seed_phrase_and_passphrase(seed_phrase: &str, passphrase: &str) -> PyResult<Self> {
handle_py_value_err(keypair_from_seed_phrase_and_passphrase(
seed_phrase,
passphrase,
))
}
pub fn __hash__(&self) -> u64 {
calculate_hash(&("Keypair", self.pubkey()))
}
fn __richcmp__(&self, other: Signer, op: CompareOp) -> PyResult<bool> {
self.richcmp(other, op)
}
#[pyo3(name = "is_interactive")]
/// Whether the impelmentation requires user interaction to sign.
///
/// Returns:
/// bool: Always ``False`` for this class.
///
pub fn py_is_interactive(&self) -> bool {
self.is_interactive()
}
fn __repr__(&self) -> String {
format!("{:#?}", self)
}
}
impl RichcmpSigner for Keypair {}
impl Default for Keypair {
fn default() -> Self {
Self::new()
}
}
impl From<KeypairOriginal> for Keypair {
fn from(keypair: KeypairOriginal) -> Self {
Self(keypair)
}
}
impl From<Keypair> for KeypairOriginal {
fn from(k: Keypair) -> Self {
k.0
}
}
impl AsRef<KeypairOriginal> for Keypair {
fn as_ref(&self) -> &KeypairOriginal {
&self.0
}
}
impl Clone for Keypair {
fn clone(&self) -> Self {
Self::from_bytes(self.to_bytes_array()).unwrap()
}
}
impl ToSignerOriginal for Keypair {
fn to_inner(&self) -> Box<dyn SignerTrait> {
Box::new(self.clone().0)
}
}
impl SignerTraitWrapper for Keypair {}