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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
use crate::{
bpf_loader, bpf_loader_deprecated, config, decode_error::DecodeError, feature, hash::hashv,
secp256k1_program, stake, system_program, sysvar, vote,
};
use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use num_derive::{FromPrimitive, ToPrimitive};
use std::{
convert::{Infallible, TryFrom},
fmt, mem,
str::FromStr,
};
use thiserror::Error;
pub const PUBKEY_BYTES: usize = 32;
pub const MAX_SEED_LEN: usize = 32;
pub const MAX_SEEDS: usize = 16;
const MAX_BASE58_LEN: usize = 44;
const PDA_MARKER: &[u8; 21] = b"ProgramDerivedAddress";
#[derive(Error, Debug, Serialize, Clone, PartialEq, FromPrimitive, ToPrimitive)]
pub enum PubkeyError {
#[error("Length of the seed is too long for address generation")]
MaxSeedLengthExceeded,
#[error("Provided seeds do not result in a valid address")]
InvalidSeeds,
#[error("Provided owner is not allowed")]
IllegalOwner,
}
impl<T> DecodeError<T> for PubkeyError {
fn type_of() -> &'static str {
"PubkeyError"
}
}
impl From<u64> for PubkeyError {
fn from(error: u64) -> Self {
match error {
0 => PubkeyError::MaxSeedLengthExceeded,
1 => PubkeyError::InvalidSeeds,
_ => panic!("Unsupported PubkeyError"),
}
}
}
#[repr(transparent)]
#[derive(
Serialize,
Deserialize,
BorshSerialize,
BorshDeserialize,
BorshSchema,
Clone,
Copy,
Default,
Eq,
PartialEq,
Ord,
PartialOrd,
Hash,
AbiExample,
)]
pub struct Pubkey([u8; 32]);
impl crate::sanitize::Sanitize for Pubkey {}
#[derive(Error, Debug, Serialize, Clone, PartialEq, FromPrimitive, ToPrimitive)]
pub enum ParsePubkeyError {
#[error("String is the wrong size")]
WrongSize,
#[error("Invalid Base58 string")]
Invalid,
}
impl From<Infallible> for ParsePubkeyError {
fn from(_: Infallible) -> Self {
unreachable!("Infallible unihnabited");
}
}
impl<T> DecodeError<T> for ParsePubkeyError {
fn type_of() -> &'static str {
"ParsePubkeyError"
}
}
impl FromStr for Pubkey {
type Err = ParsePubkeyError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.len() > MAX_BASE58_LEN {
return Err(ParsePubkeyError::WrongSize);
}
let pubkey_vec = bs58::decode(s)
.into_vec()
.map_err(|_| ParsePubkeyError::Invalid)?;
if pubkey_vec.len() != mem::size_of::<Pubkey>() {
Err(ParsePubkeyError::WrongSize)
} else {
Ok(Pubkey::new(&pubkey_vec))
}
}
}
impl TryFrom<&str> for Pubkey {
type Error = ParsePubkeyError;
fn try_from(s: &str) -> Result<Self, Self::Error> {
Pubkey::from_str(s)
}
}
pub fn bytes_are_curve_point<T: AsRef<[u8]>>(_bytes: T) -> bool {
#[cfg(not(target_arch = "bpf"))]
{
curve25519_dalek::edwards::CompressedEdwardsY::from_slice(_bytes.as_ref())
.decompress()
.is_some()
}
#[cfg(target_arch = "bpf")]
unimplemented!();
}
impl Pubkey {
pub fn new(pubkey_vec: &[u8]) -> Self {
Self(
<[u8; 32]>::try_from(<&[u8]>::clone(&pubkey_vec))
.expect("Slice must be the same length as a Pubkey"),
)
}
pub const fn new_from_array(pubkey_array: [u8; 32]) -> Self {
Self(pubkey_array)
}
#[deprecated(since = "1.3.9", note = "Please use 'Pubkey::new_unique' instead")]
#[cfg(not(target_arch = "bpf"))]
pub fn new_rand() -> Self {
Pubkey::new(&rand::random::<[u8; 32]>())
}
pub fn new_unique() -> Self {
use std::sync::atomic::{AtomicU64, Ordering};
static I: AtomicU64 = AtomicU64::new(1);
let mut b = [0u8; 32];
let i = I.fetch_add(1, Ordering::Relaxed);
b[0..8].copy_from_slice(&i.to_le_bytes());
Self::new(&b)
}
pub fn create_with_seed(
base: &Pubkey,
seed: &str,
owner: &Pubkey,
) -> Result<Pubkey, PubkeyError> {
if seed.len() > MAX_SEED_LEN {
return Err(PubkeyError::MaxSeedLengthExceeded);
}
let owner = owner.as_ref();
if owner.len() >= PDA_MARKER.len() {
let slice = &owner[owner.len() - PDA_MARKER.len()..];
if slice == PDA_MARKER {
return Err(PubkeyError::IllegalOwner);
}
}
Ok(Pubkey::new(
hashv(&[base.as_ref(), seed.as_ref(), owner]).as_ref(),
))
}
pub fn create_program_address(
seeds: &[&[u8]],
program_id: &Pubkey,
) -> Result<Pubkey, PubkeyError> {
if seeds.len() > MAX_SEEDS {
return Err(PubkeyError::MaxSeedLengthExceeded);
}
for seed in seeds.iter() {
if seed.len() > MAX_SEED_LEN {
return Err(PubkeyError::MaxSeedLengthExceeded);
}
}
if program_id.is_native_program_id() {
return Err(PubkeyError::IllegalOwner);
}
#[cfg(not(target_arch = "bpf"))]
{
let mut hasher = crate::hash::Hasher::default();
for seed in seeds.iter() {
hasher.hash(seed);
}
hasher.hashv(&[program_id.as_ref(), PDA_MARKER]);
let hash = hasher.result();
if bytes_are_curve_point(hash) {
return Err(PubkeyError::InvalidSeeds);
}
Ok(Pubkey::new(hash.as_ref()))
}
#[cfg(target_arch = "bpf")]
{
extern "C" {
fn sol_create_program_address(
seeds_addr: *const u8,
seeds_len: u64,
program_id_addr: *const u8,
address_bytes_addr: *const u8,
) -> u64;
};
let mut bytes = [0; 32];
let result = unsafe {
sol_create_program_address(
seeds as *const _ as *const u8,
seeds.len() as u64,
program_id as *const _ as *const u8,
&mut bytes as *mut _ as *mut u8,
)
};
match result {
crate::entrypoint::SUCCESS => Ok(Pubkey::new(&bytes)),
_ => Err(result.into()),
}
}
}
pub fn find_program_address(seeds: &[&[u8]], program_id: &Pubkey) -> (Pubkey, u8) {
Self::try_find_program_address(seeds, program_id)
.unwrap_or_else(|| panic!("Unable to find a viable program address bump seed"))
}
#[allow(clippy::same_item_push)]
pub fn try_find_program_address(seeds: &[&[u8]], program_id: &Pubkey) -> Option<(Pubkey, u8)> {
#[cfg(not(target_arch = "bpf"))]
{
let mut bump_seed = [std::u8::MAX];
for _ in 0..std::u8::MAX {
{
let mut seeds_with_bump = seeds.to_vec();
seeds_with_bump.push(&bump_seed);
match Self::create_program_address(&seeds_with_bump, program_id) {
Ok(address) => return Some((address, bump_seed[0])),
Err(PubkeyError::InvalidSeeds) => (),
_ => break,
}
}
bump_seed[0] -= 1;
}
None
}
#[cfg(target_arch = "bpf")]
{
extern "C" {
fn sol_try_find_program_address(
seeds_addr: *const u8,
seeds_len: u64,
program_id_addr: *const u8,
address_bytes_addr: *const u8,
bump_seed_addr: *const u8,
) -> u64;
};
let mut bytes = [0; 32];
let mut bump_seed = std::u8::MAX;
let result = unsafe {
sol_try_find_program_address(
seeds as *const _ as *const u8,
seeds.len() as u64,
program_id as *const _ as *const u8,
&mut bytes as *mut _ as *mut u8,
&mut bump_seed as *mut _ as *mut u8,
)
};
match result {
crate::entrypoint::SUCCESS => Some((Pubkey::new(&bytes), bump_seed)),
_ => None,
}
}
}
pub fn to_bytes(self) -> [u8; 32] {
self.0
}
pub fn is_on_curve(&self) -> bool {
bytes_are_curve_point(self)
}
pub fn log(&self) {
#[cfg(target_arch = "bpf")]
{
extern "C" {
fn sol_log_pubkey(pubkey_addr: *const u8);
};
unsafe { sol_log_pubkey(self.as_ref() as *const _ as *const u8) };
}
#[cfg(not(target_arch = "bpf"))]
crate::program_stubs::sol_log(&self.to_string());
}
pub fn is_native_program_id(&self) -> bool {
let all_program_ids = [
bpf_loader::id(),
bpf_loader_deprecated::id(),
feature::id(),
config::program::id(),
stake::program::id(),
stake::config::id(),
vote::program::id(),
secp256k1_program::id(),
system_program::id(),
sysvar::id(),
];
all_program_ids.contains(self)
}
}
impl AsRef<[u8]> for Pubkey {
fn as_ref(&self) -> &[u8] {
&self.0[..]
}
}
impl fmt::Debug for Pubkey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", bs58::encode(self.0).into_string())
}
}
impl fmt::Display for Pubkey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", bs58::encode(self.0).into_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::str::from_utf8;
#[test]
fn test_new_unique() {
assert!(Pubkey::new_unique() != Pubkey::new_unique());
}
#[test]
fn pubkey_fromstr() {
let pubkey = Pubkey::new_unique();
let mut pubkey_base58_str = bs58::encode(pubkey.0).into_string();
assert_eq!(pubkey_base58_str.parse::<Pubkey>(), Ok(pubkey));
pubkey_base58_str.push_str(&bs58::encode(pubkey.0).into_string());
assert_eq!(
pubkey_base58_str.parse::<Pubkey>(),
Err(ParsePubkeyError::WrongSize)
);
pubkey_base58_str.truncate(pubkey_base58_str.len() / 2);
assert_eq!(pubkey_base58_str.parse::<Pubkey>(), Ok(pubkey));
pubkey_base58_str.truncate(pubkey_base58_str.len() / 2);
assert_eq!(
pubkey_base58_str.parse::<Pubkey>(),
Err(ParsePubkeyError::WrongSize)
);
let mut pubkey_base58_str = bs58::encode(pubkey.0).into_string();
assert_eq!(pubkey_base58_str.parse::<Pubkey>(), Ok(pubkey));
pubkey_base58_str.replace_range(..1, "I");
assert_eq!(
pubkey_base58_str.parse::<Pubkey>(),
Err(ParsePubkeyError::Invalid)
);
let mut too_long = bs58::encode(&[255u8; PUBKEY_BYTES]).into_string();
too_long.push('1');
assert_eq!(too_long.parse::<Pubkey>(), Err(ParsePubkeyError::WrongSize));
}
#[test]
fn test_create_with_seed() {
assert!(
Pubkey::create_with_seed(&Pubkey::new_unique(), "☉", &Pubkey::new_unique()).is_ok()
);
assert_eq!(
Pubkey::create_with_seed(
&Pubkey::new_unique(),
from_utf8(&[127; MAX_SEED_LEN + 1]).unwrap(),
&Pubkey::new_unique()
),
Err(PubkeyError::MaxSeedLengthExceeded)
);
assert!(Pubkey::create_with_seed(
&Pubkey::new_unique(),
"\
\u{10FFFF}\u{10FFFF}\u{10FFFF}\u{10FFFF}\u{10FFFF}\u{10FFFF}\u{10FFFF}\u{10FFFF}\
",
&Pubkey::new_unique()
)
.is_ok());
assert_eq!(
Pubkey::create_with_seed(
&Pubkey::new_unique(),
"\
x\u{10FFFF}\u{10FFFF}\u{10FFFF}\u{10FFFF}\u{10FFFF}\u{10FFFF}\u{10FFFF}\u{10FFFF}\
",
&Pubkey::new_unique()
),
Err(PubkeyError::MaxSeedLengthExceeded)
);
assert!(Pubkey::create_with_seed(
&Pubkey::new_unique(),
std::str::from_utf8(&[0; MAX_SEED_LEN]).unwrap(),
&Pubkey::new_unique(),
)
.is_ok());
assert!(
Pubkey::create_with_seed(&Pubkey::new_unique(), "", &Pubkey::new_unique(),).is_ok()
);
assert_eq!(
Pubkey::create_with_seed(
&Pubkey::default(),
"limber chicken: 4/45",
&Pubkey::default(),
),
Ok("9h1HyLCW5dZnBVap8C5egQ9Z6pHyjsh5MNy83iPqqRuq"
.parse()
.unwrap())
);
}
#[test]
fn test_create_program_address() {
let exceeded_seed = &[127; MAX_SEED_LEN + 1];
let max_seed = &[0; MAX_SEED_LEN];
let program_id = Pubkey::from_str("BPFLoaderUpgradeab1e11111111111111111111111").unwrap();
let public_key = Pubkey::from_str("SeedPubey1111111111111111111111111111111111").unwrap();
assert_eq!(
Pubkey::create_program_address(&[exceeded_seed], &program_id),
Err(PubkeyError::MaxSeedLengthExceeded)
);
assert_eq!(
Pubkey::create_program_address(&[b"short_seed", exceeded_seed], &program_id),
Err(PubkeyError::MaxSeedLengthExceeded)
);
assert!(Pubkey::create_program_address(&[max_seed], &program_id).is_ok());
assert_eq!(
Pubkey::create_program_address(&[b"", &[1]], &program_id),
Ok("BwqrghZA2htAcqq8dzP1WDAhTXYTYWj7CHxF5j7TDBAe"
.parse()
.unwrap())
);
assert_eq!(
Pubkey::create_program_address(&["☉".as_ref(), &[0]], &program_id),
Ok("13yWmRpaTR4r5nAktwLqMpRNr28tnVUZw26rTvPSSB19"
.parse()
.unwrap())
);
assert_eq!(
Pubkey::create_program_address(&[b"Talking", b"Squirrels"], &program_id),
Ok("2fnQrngrQT4SeLcdToJAD96phoEjNL2man2kfRLCASVk"
.parse()
.unwrap())
);
assert_eq!(
Pubkey::create_program_address(&[public_key.as_ref(), &[1]], &program_id),
Ok("976ymqVnfE32QFe6NfGDctSvVa36LWnvYxhU6G2232YL"
.parse()
.unwrap())
);
assert_ne!(
Pubkey::create_program_address(&[b"Talking", b"Squirrels"], &program_id).unwrap(),
Pubkey::create_program_address(&[b"Talking"], &program_id).unwrap(),
);
}
#[test]
fn test_pubkey_off_curve() {
let mut addresses = vec![];
for _ in 0..1_000 {
let program_id = Pubkey::new_unique();
let bytes1 = rand::random::<[u8; 10]>();
let bytes2 = rand::random::<[u8; 32]>();
if let Ok(program_address) =
Pubkey::create_program_address(&[&bytes1, &bytes2], &program_id)
{
let is_on_curve = curve25519_dalek::edwards::CompressedEdwardsY::from_slice(
&program_address.to_bytes(),
)
.decompress()
.is_some();
assert!(!is_on_curve);
assert!(!addresses.contains(&program_address));
addresses.push(program_address);
}
}
}
#[test]
fn test_find_program_address() {
for _ in 0..1_000 {
let program_id = Pubkey::new_unique();
let (address, bump_seed) =
Pubkey::find_program_address(&[b"Lil'", b"Bits"], &program_id);
assert_eq!(
address,
Pubkey::create_program_address(&[b"Lil'", b"Bits", &[bump_seed]], &program_id)
.unwrap()
);
}
}
#[test]
fn test_is_native_program_id() {
assert!(bpf_loader::id().is_native_program_id());
assert!(bpf_loader_deprecated::id().is_native_program_id());
assert!(config::program::id().is_native_program_id());
assert!(feature::id().is_native_program_id());
assert!(secp256k1_program::id().is_native_program_id());
assert!(stake::program::id().is_native_program_id());
assert!(stake::config::id().is_native_program_id());
assert!(system_program::id().is_native_program_id());
assert!(sysvar::id().is_native_program_id());
assert!(vote::program::id().is_native_program_id());
}
}