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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
use {
bincode::{deserialize, serialize, serialized_size},
byteorder::{ByteOrder, LittleEndian},
crossbeam_channel::{unbounded, Sender},
log::*,
serde_derive::{Deserialize, Serialize},
solana_metrics::datapoint_info,
solana_sdk::{
hash::Hash,
instruction::Instruction,
message::Message,
native_token::lamports_to_sol,
packet::PACKET_DATA_SIZE,
pubkey::Pubkey,
signature::{Keypair, Signer},
system_instruction,
transaction::Transaction,
},
std::{
collections::{HashMap, HashSet},
io::{Read, Write},
net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream},
sync::{Arc, Mutex},
thread,
time::Duration,
},
thiserror::Error,
tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::{TcpListener, TcpStream as TokioTcpStream},
runtime::Runtime,
},
};
#[macro_export]
macro_rules! socketaddr {
($ip:expr, $port:expr) => {
SocketAddr::from((Ipv4Addr::from($ip), $port))
};
($str:expr) => {{
let a: SocketAddr = $str.parse().unwrap();
a
}};
}
const ERROR_RESPONSE: [u8; 2] = 0u16.to_le_bytes();
pub const TIME_SLICE: u64 = 60;
pub const FAUCET_PORT: u16 = 9900;
pub const FAUCET_PORT_STR: &str = "9900";
#[derive(Error, Debug)]
pub enum FaucetError {
#[error("IO Error: {0}")]
IoError(#[from] std::io::Error),
#[error("serialization error: {0}")]
Serialize(#[from] bincode::Error),
#[error("transaction_length from faucet exceeds limit: {0}")]
TransactionDataTooLarge(usize),
#[error("transaction_length from faucet: 0")]
NoDataReceived,
#[error("request too large; req: ◎{0}, cap: ◎{1}")]
PerRequestCapExceeded(f64, f64),
#[error("limit reached; req: ◎{0}, to: {1}, current: ◎{2}, cap: ◎{3}")]
PerTimeCapExceeded(f64, String, f64, f64),
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub enum FaucetRequest {
GetAirdrop {
lamports: u64,
to: Pubkey,
blockhash: Hash,
},
}
pub enum FaucetTransaction {
Airdrop(Transaction),
Memo((Transaction, String)),
}
pub struct Faucet {
faucet_keypair: Keypair,
ip_cache: HashMap<IpAddr, u64>,
address_cache: HashMap<Pubkey, u64>,
pub time_slice: Duration,
per_time_cap: Option<u64>,
per_request_cap: Option<u64>,
allowed_ips: HashSet<IpAddr>,
}
impl Faucet {
pub fn new(
faucet_keypair: Keypair,
time_input: Option<u64>,
per_time_cap: Option<u64>,
per_request_cap: Option<u64>,
) -> Self {
Self::new_with_allowed_ips(
faucet_keypair,
time_input,
per_time_cap,
per_request_cap,
HashSet::new(),
)
}
pub fn new_with_allowed_ips(
faucet_keypair: Keypair,
time_input: Option<u64>,
per_time_cap: Option<u64>,
per_request_cap: Option<u64>,
allowed_ips: HashSet<IpAddr>,
) -> Self {
let time_slice = Duration::new(time_input.unwrap_or(TIME_SLICE), 0);
if let Some((per_request_cap, per_time_cap)) = per_request_cap.zip(per_time_cap) {
if per_time_cap < per_request_cap {
warn!(
"per_time_cap {} SAFE < per_request_cap {} SAFE; \
maximum single requests will fail",
lamports_to_sol(per_time_cap),
lamports_to_sol(per_request_cap),
);
}
}
Self {
faucet_keypair,
ip_cache: HashMap::new(),
address_cache: HashMap::new(),
time_slice,
per_time_cap,
per_request_cap,
allowed_ips,
}
}
pub fn check_time_request_limit<T: LimitByTime + std::fmt::Display>(
&mut self,
request_amount: u64,
to: T,
) -> Result<(), FaucetError> {
let new_total = to.check_cache(self, request_amount);
to.datapoint_info(request_amount, new_total);
if let Some(cap) = self.per_time_cap {
if new_total > cap {
return Err(FaucetError::PerTimeCapExceeded(
lamports_to_sol(request_amount),
to.to_string(),
lamports_to_sol(new_total),
lamports_to_sol(cap),
));
}
}
Ok(())
}
pub fn clear_caches(&mut self) {
self.ip_cache.clear();
self.address_cache.clear();
}
pub fn build_airdrop_transaction(
&mut self,
req: FaucetRequest,
ip: IpAddr,
) -> Result<FaucetTransaction, FaucetError> {
trace!("build_airdrop_transaction: {:?}", req);
match req {
FaucetRequest::GetAirdrop {
lamports,
to,
blockhash,
} => {
let mint_pubkey = self.faucet_keypair.pubkey();
info!(
"Requesting airdrop of {} SAFE to {:?}",
lamports_to_sol(lamports),
to
);
if let Some(cap) = self.per_request_cap {
if lamports > cap {
let memo = format!(
"{}",
FaucetError::PerRequestCapExceeded(
lamports_to_sol(lamports),
lamports_to_sol(cap),
)
);
let memo_instruction = Instruction {
program_id: Pubkey::from(safe_memo::id().to_bytes()),
accounts: vec![],
data: memo.as_bytes().to_vec(),
};
let message = Message::new(&[memo_instruction], Some(&mint_pubkey));
return Ok(FaucetTransaction::Memo((
Transaction::new(&[&self.faucet_keypair], message, blockhash),
memo,
)));
}
}
if !ip.is_loopback() && !self.allowed_ips.contains(&ip) {
self.check_time_request_limit(lamports, ip)?;
}
self.check_time_request_limit(lamports, to)?;
let transfer_instruction =
system_instruction::transfer(&mint_pubkey, &to, lamports);
let message = Message::new(&[transfer_instruction], Some(&mint_pubkey));
Ok(FaucetTransaction::Airdrop(Transaction::new(
&[&self.faucet_keypair],
message,
blockhash,
)))
}
}
}
pub fn process_faucet_request(
&mut self,
bytes: &[u8],
ip: IpAddr,
) -> Result<Vec<u8>, FaucetError> {
let req: FaucetRequest = deserialize(bytes)?;
info!("Airdrop transaction requested...{:?}", req);
let res = self.build_airdrop_transaction(req, ip);
match res {
Ok(tx) => {
let tx = match tx {
FaucetTransaction::Airdrop(tx) => {
info!("Airdrop transaction granted");
tx
}
FaucetTransaction::Memo((tx, memo)) => {
warn!("Memo transaction returned: {}", memo);
tx
}
};
let response_vec = bincode::serialize(&tx)?;
let mut response_vec_with_length = vec![0; 2];
LittleEndian::write_u16(&mut response_vec_with_length, response_vec.len() as u16);
response_vec_with_length.extend_from_slice(&response_vec);
Ok(response_vec_with_length)
}
Err(err) => {
warn!("Airdrop transaction failed: {}", err);
Err(err)
}
}
}
}
impl Drop for Faucet {
fn drop(&mut self) {
solana_metrics::flush();
}
}
pub fn request_airdrop_transaction(
faucet_addr: &SocketAddr,
id: &Pubkey,
lamports: u64,
blockhash: Hash,
) -> Result<Transaction, FaucetError> {
info!(
"request_airdrop_transaction: faucet_addr={} id={} lamports={} blockhash={}",
faucet_addr, id, lamports, blockhash
);
let mut stream = TcpStream::connect_timeout(faucet_addr, Duration::new(3, 0))?;
stream.set_read_timeout(Some(Duration::new(10, 0)))?;
let req = FaucetRequest::GetAirdrop {
lamports,
blockhash,
to: *id,
};
let req = serialize(&req).expect("serialize faucet request");
stream.write_all(&req)?;
let mut buffer = [0; 2];
stream.read_exact(&mut buffer).map_err(|err| {
info!(
"request_airdrop_transaction: buffer length read_exact error: {:?}",
err
);
err
})?;
let transaction_length = LittleEndian::read_u16(&buffer) as usize;
if transaction_length > PACKET_DATA_SIZE {
return Err(FaucetError::TransactionDataTooLarge(transaction_length));
} else if transaction_length == 0 {
return Err(FaucetError::NoDataReceived);
}
let mut buffer = Vec::new();
buffer.resize(transaction_length, 0);
stream.read_exact(&mut buffer).map_err(|err| {
info!(
"request_airdrop_transaction: buffer read_exact error: {:?}",
err
);
err
})?;
let transaction: Transaction = deserialize(&buffer)?;
Ok(transaction)
}
pub fn run_local_faucet_with_port(
faucet_keypair: Keypair,
sender: Sender<Result<SocketAddr, String>>,
per_time_cap: Option<u64>,
port: u16, ) {
thread::spawn(move || {
let faucet_addr = socketaddr!(0, port);
let faucet = Arc::new(Mutex::new(Faucet::new(
faucet_keypair,
None,
per_time_cap,
None,
)));
let runtime = Runtime::new().unwrap();
runtime.block_on(run_faucet(faucet, faucet_addr, Some(sender)));
});
}
pub fn run_local_faucet(faucet_keypair: Keypair, per_time_cap: Option<u64>) -> SocketAddr {
let (sender, receiver) = unbounded();
run_local_faucet_with_port(faucet_keypair, sender, per_time_cap, 0);
receiver
.recv()
.expect("run_local_faucet")
.expect("faucet_addr")
}
pub async fn run_faucet(
faucet: Arc<Mutex<Faucet>>,
faucet_addr: SocketAddr,
sender: Option<Sender<Result<SocketAddr, String>>>,
) {
let listener = TcpListener::bind(&faucet_addr).await;
if let Some(sender) = sender {
sender.send(
listener.as_ref().map(|listener| listener.local_addr().unwrap())
.map_err(|err| {
format!(
"Unable to bind faucet to {:?}, check the address is not already in use: {}",
faucet_addr, err
)
})
)
.unwrap();
}
let listener = match listener {
Err(err) => {
error!("Faucet failed to start: {}", err);
return;
}
Ok(listener) => listener,
};
info!("Faucet started. Listening on: {}", faucet_addr);
info!(
"Faucet account address: {}",
faucet.lock().unwrap().faucet_keypair.pubkey()
);
loop {
let _faucet = faucet.clone();
match listener.accept().await {
Ok((stream, _)) => {
tokio::spawn(async move {
if let Err(e) = process(stream, _faucet).await {
info!("failed to process request; error = {:?}", e);
}
});
}
Err(e) => debug!("failed to accept socket; error = {:?}", e),
}
}
}
async fn process(
mut stream: TokioTcpStream,
faucet: Arc<Mutex<Faucet>>,
) -> Result<(), Box<dyn std::error::Error>> {
let mut request = vec![
0u8;
serialized_size(&FaucetRequest::GetAirdrop {
lamports: u64::default(),
to: Pubkey::default(),
blockhash: Hash::default(),
})
.unwrap() as usize
];
while stream.read_exact(&mut request).await.is_ok() {
trace!("{:?}", request);
let response = {
match stream.peer_addr() {
Err(e) => {
info!("{:?}", e.into_inner());
ERROR_RESPONSE.to_vec()
}
Ok(peer_addr) => {
let ip = peer_addr.ip();
info!("Request IP: {:?}", ip);
match faucet.lock().unwrap().process_faucet_request(&request, ip) {
Ok(response_bytes) => {
trace!("Airdrop response_bytes: {:?}", response_bytes);
response_bytes
}
Err(e) => {
info!("Error in request: {}", e);
ERROR_RESPONSE.to_vec()
}
}
}
}
};
stream.write_all(&response).await?;
}
Ok(())
}
pub trait LimitByTime {
fn check_cache(&self, faucet: &mut Faucet, request_amount: u64) -> u64;
fn datapoint_info(&self, request_amount: u64, new_total: u64);
}
impl LimitByTime for IpAddr {
fn check_cache(&self, faucet: &mut Faucet, request_amount: u64) -> u64 {
*faucet
.ip_cache
.entry(*self)
.and_modify(|total| *total = total.saturating_add(request_amount))
.or_insert(request_amount)
}
fn datapoint_info(&self, request_amount: u64, new_total: u64) {
datapoint_info!(
"faucet-airdrop",
("request_amount", request_amount, i64),
("ip", self.to_string(), String),
("new_total", new_total, i64)
);
}
}
impl LimitByTime for Pubkey {
fn check_cache(&self, faucet: &mut Faucet, request_amount: u64) -> u64 {
*faucet
.address_cache
.entry(*self)
.and_modify(|total| *total = total.saturating_add(request_amount))
.or_insert(request_amount)
}
fn datapoint_info(&self, request_amount: u64, new_total: u64) {
datapoint_info!(
"faucet-airdrop",
("request_amount", request_amount, i64),
("address", self.to_string(), String),
("new_total", new_total, i64)
);
}
}
#[cfg(test)]
mod tests {
use {super::*, solana_sdk::system_instruction::SystemInstruction, std::time::Duration};
#[test]
fn test_check_time_request_limit() {
let keypair = Keypair::new();
let mut faucet = Faucet::new(keypair, None, Some(2), None);
let ip = socketaddr!([203, 0, 113, 1], 1234).ip();
assert!(faucet.check_time_request_limit(1, ip).is_ok());
assert!(faucet.check_time_request_limit(1, ip).is_ok());
assert!(faucet.check_time_request_limit(1, ip).is_err());
let address = Pubkey::new_unique();
assert!(faucet.check_time_request_limit(1, address).is_ok());
assert!(faucet.check_time_request_limit(1, address).is_ok());
assert!(faucet.check_time_request_limit(1, address).is_err());
}
#[test]
fn test_clear_caches() {
let keypair = Keypair::new();
let mut faucet = Faucet::new(keypair, None, None, None);
let ip = socketaddr!([127, 0, 0, 1], 0).ip();
assert_eq!(faucet.ip_cache.len(), 0);
faucet.check_time_request_limit(1, ip).unwrap();
assert_eq!(faucet.ip_cache.len(), 1);
faucet.clear_caches();
assert_eq!(faucet.ip_cache.len(), 0);
assert!(faucet.ip_cache.is_empty());
let address = Pubkey::new_unique();
assert_eq!(faucet.address_cache.len(), 0);
faucet.check_time_request_limit(1, address).unwrap();
assert_eq!(faucet.address_cache.len(), 1);
faucet.clear_caches();
assert_eq!(faucet.address_cache.len(), 0);
assert!(faucet.address_cache.is_empty());
}
#[test]
fn test_faucet_default_init() {
let keypair = Keypair::new();
let time_slice: Option<u64> = None;
let per_time_cap: Option<u64> = Some(200);
let per_request_cap: Option<u64> = Some(100);
let faucet = Faucet::new(keypair, time_slice, per_time_cap, per_request_cap);
assert_eq!(faucet.time_slice, Duration::new(TIME_SLICE, 0));
assert_eq!(faucet.per_time_cap, per_time_cap);
assert_eq!(faucet.per_request_cap, per_request_cap);
}
#[test]
fn test_faucet_build_airdrop_transaction() {
let to = Pubkey::new_unique();
let blockhash = Hash::default();
let request = FaucetRequest::GetAirdrop {
lamports: 2,
to,
blockhash,
};
let ip = socketaddr!([203, 0, 113, 1], 1234).ip();
let mint = Keypair::new();
let mint_pubkey = mint.pubkey();
let mut faucet = Faucet::new(mint, None, None, None);
if let FaucetTransaction::Airdrop(tx) =
faucet.build_airdrop_transaction(request, ip).unwrap()
{
let message = tx.message();
assert_eq!(tx.signatures.len(), 1);
assert_eq!(
message.account_keys,
vec![mint_pubkey, to, Pubkey::default()]
);
assert_eq!(message.recent_blockhash, blockhash);
assert_eq!(message.instructions.len(), 1);
let instruction: SystemInstruction =
deserialize(&message.instructions[0].data).unwrap();
assert_eq!(instruction, SystemInstruction::Transfer { lamports: 2 });
} else {
panic!("airdrop should succeed");
}
let mint = Keypair::new();
faucet = Faucet::new(mint, None, Some(2), None);
let _tx = faucet.build_airdrop_transaction(request, ip).unwrap(); let tx = faucet.build_airdrop_transaction(request, ip);
assert!(tx.is_err());
let mint = Keypair::new();
faucet = Faucet::new(mint, None, Some(2), None);
let ip = socketaddr!([127, 0, 0, 1], 0).ip();
let other = Pubkey::new_unique();
let _tx0 = faucet.build_airdrop_transaction(request, ip).unwrap(); let request1 = FaucetRequest::GetAirdrop {
lamports: 2,
to: other,
blockhash,
};
let _tx1 = faucet.build_airdrop_transaction(request1, ip).unwrap(); let tx0 = faucet.build_airdrop_transaction(request, ip);
assert!(tx0.is_err());
let tx1 = faucet.build_airdrop_transaction(request1, ip);
assert!(tx1.is_err());
let mint = Keypair::new();
let ip = socketaddr!([203, 0, 113, 1], 0).ip();
let mut allowed_ips = HashSet::new();
allowed_ips.insert(ip);
faucet = Faucet::new_with_allowed_ips(mint, None, Some(2), None, allowed_ips);
let other = Pubkey::new_unique();
let _tx0 = faucet.build_airdrop_transaction(request, ip).unwrap(); let request1 = FaucetRequest::GetAirdrop {
lamports: 2,
to: other,
blockhash,
};
let _tx1 = faucet.build_airdrop_transaction(request1, ip).unwrap(); let tx0 = faucet.build_airdrop_transaction(request, ip);
assert!(tx0.is_err());
let tx1 = faucet.build_airdrop_transaction(request1, ip);
assert!(tx1.is_err());
let mint = Keypair::new();
let mint_pubkey = mint.pubkey();
let mut faucet = Faucet::new(mint, None, None, Some(1));
if let FaucetTransaction::Memo((tx, memo)) =
faucet.build_airdrop_transaction(request, ip).unwrap()
{
let message = tx.message();
assert_eq!(tx.signatures.len(), 1);
assert_eq!(
message.account_keys,
vec![mint_pubkey, Pubkey::from(safe_memo::id().to_bytes())]
);
assert_eq!(message.recent_blockhash, blockhash);
assert_eq!(message.instructions.len(), 1);
let parsed_memo = std::str::from_utf8(&message.instructions[0].data).unwrap();
let expected_memo = "request too large; req: ◎0.000000002, cap: ◎0.000000001";
assert_eq!(parsed_memo, expected_memo);
assert_eq!(memo, expected_memo);
} else {
panic!("airdrop attempt should result in memo tx");
}
}
#[test]
fn test_process_faucet_request() {
let to = solana_sdk::pubkey::new_rand();
let blockhash = Hash::new(to.as_ref());
let lamports = 50;
let req = FaucetRequest::GetAirdrop {
lamports,
blockhash,
to,
};
let ip = socketaddr!([203, 0, 113, 1], 1234).ip();
let req = serialize(&req).unwrap();
let keypair = Keypair::new();
let expected_instruction = system_instruction::transfer(&keypair.pubkey(), &to, lamports);
let message = Message::new(&[expected_instruction], Some(&keypair.pubkey()));
let expected_tx = Transaction::new(&[&keypair], message, blockhash);
let expected_bytes = serialize(&expected_tx).unwrap();
let mut expected_vec_with_length = vec![0; 2];
LittleEndian::write_u16(&mut expected_vec_with_length, expected_bytes.len() as u16);
expected_vec_with_length.extend_from_slice(&expected_bytes);
let mut faucet = Faucet::new(keypair, None, None, None);
let response = faucet.process_faucet_request(&req, ip);
let response_vec = response.unwrap().to_vec();
assert_eq!(expected_vec_with_length, response_vec);
let bad_bytes = "bad bytes".as_bytes();
assert!(faucet.process_faucet_request(bad_bytes, ip).is_err());
}
}