dg_fast_farmer 2.0.2

A lite farmer for the Chia Blockchain.
Documentation
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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
use crate::farmer::config::Config;
use crate::{HEADERS, PROTOCOL_VERSION};
use blst::min_pk::SecretKey;
use dg_xch_clients::api::pool::{DefaultPoolClient, PoolClient};
use dg_xch_core::blockchain::sized_bytes::{Bytes32, Bytes48};
use dg_xch_core::clvm::bls_bindings::{sign, verify_signature};
use dg_xch_core::config::PoolWalletConfig;
use dg_xch_core::protocols::farmer::{FarmerPoolState, FarmerSharedState};
use dg_xch_core::protocols::pool::{
    AuthenticationPayload, GetFarmerRequest, GetFarmerResponse, PoolError, PoolErrorCode,
    PostFarmerPayload, PostFarmerRequest, PostFarmerResponse, PutFarmerPayload, PutFarmerRequest,
    PutFarmerResponse, get_current_authentication_token,
};
use dg_xch_core::traits::SizedBytes;
use dg_xch_core::utils::hash_256;
use dg_xch_keys::{encode_puzzle_hash, parse_payout_address};
use dg_xch_serialize::ChiaSerialize;
use log::{debug, error, info, warn};
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::io::Error;
use std::str::FromStr;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant, SystemTime};
use tokio::sync::RwLock;

const UPDATE_POOL_INFO_INTERVAL: u64 = 600;
const UPDATE_POOL_INFO_FAILURE_RETRY_INTERVAL: u64 = 120;
const UPDATE_POOL_FARMER_INFO_INTERVAL: u64 = 300;

pub async fn pool_updater<T, C: Clone>(
    shared_state: Arc<FarmerSharedState<T>>,
    config: Arc<RwLock<Config<C>>>,
) {
    let mut last_update = Instant::now();
    let mut first = true;
    let pool_client = Arc::new(DefaultPoolClient::new());
    loop {
        if !shared_state.signal.load(Ordering::Relaxed) {
            break;
        } else if first
            || shared_state.force_pool_update.load(Ordering::Relaxed)
            || Instant::now().duration_since(last_update).as_secs() >= 60
        {
            debug!("Updating Pool State");
            if let Err(e) = update_pool_state(
                pool_client.clone(),
                &*config.read().await,
                shared_state.clone(),
            )
            .await
            {
                error!("Error updating Pool State: {}", e);
                tokio::time::sleep(Duration::from_secs(10)).await;
            } else {
                first = false;
                last_update = Instant::now();
                shared_state.last_pool_update.store(
                    SystemTime::now()
                        .duration_since(SystemTime::UNIX_EPOCH)
                        .expect("System Time should be Greater than Epoch")
                        .as_secs(),
                    Ordering::Relaxed,
                );
                shared_state
                    .force_pool_update
                    .store(false, Ordering::Relaxed);
            }
        }
        tokio::time::sleep(Duration::from_millis(25)).await;
    }
    info!("Pool Handle Stopped");
}

pub async fn get_farmer<T: PoolClient + Sized + Sync + Send>(
    pool_config: &PoolWalletConfig,
    authentication_token_timeout: u8,
    authentication_sk: &SecretKey,
    client: Arc<T>,
    mut headers: HashMap<String, String>,
    chia_version: impl for<'a> AsyncFn() -> Option<String>,
) -> Result<GetFarmerResponse, PoolError> {
    let authentication_token = get_current_authentication_token(authentication_token_timeout);
    let msg = AuthenticationPayload {
        method_name: "get_farmer".to_string(),
        launcher_id: pool_config.launcher_id,
        target_puzzle_hash: pool_config.target_puzzle_hash,
        authentication_token,
    }
    .to_bytes(PROTOCOL_VERSION);
    let to_sign = hash_256(&msg);
    let signature = sign(authentication_sk, &to_sign);
    if !verify_signature(&authentication_sk.sk_to_pk(), &to_sign, &signature) {
        error!("Farmer GET Failed to Validate Signature");
        return Err(PoolError {
            error_code: PoolErrorCode::InvalidSignature as u8,
            error_message: "Local Failed to Validate Signature".to_string(),
        });
    }
    if let Some(v) = chia_version().await {
        headers.insert(String::from("X-chia-version"), v);
    }
    headers.extend(HEADERS.clone());
    client
        .get_farmer(
            &pool_config.pool_url,
            GetFarmerRequest {
                launcher_id: pool_config.launcher_id,
                authentication_token,
                signature: signature.to_bytes().into(),
            },
            &Some(headers),
        )
        .await
}

async fn do_auth(
    pool_config: &PoolWalletConfig,
    owner_sk: &SecretKey,
    auth_keys: &HashMap<Bytes48, SecretKey>,
) -> Result<Bytes48, PoolError> {
    if owner_sk.sk_to_pk().to_bytes() != pool_config.owner_public_key.bytes() {
        Err(PoolError {
            error_code: PoolErrorCode::ServerException as u8,
            error_message: "Owner Keys Mismatch".to_string(),
        })
    } else if let Some(auth_key) = auth_keys.get(&owner_sk.sk_to_pk().to_bytes().into()) {
        Ok(auth_key.sk_to_pk().to_bytes().into())
    } else {
        Err(PoolError {
            error_code: PoolErrorCode::NotFound as u8,
            error_message: "Auth Key Not Found".to_string(),
        })
    }
}

#[allow(clippy::too_many_arguments)]
pub async fn post_farmer<T: PoolClient + Sized + Sync + Send>(
    pool_config: &PoolWalletConfig,
    payout_instructions: &str,
    authentication_token_timeout: u8,
    owner_sk: &SecretKey,
    auth_keys: &HashMap<Bytes48, SecretKey>,
    suggested_difficulty: Option<u64>,
    client: Arc<T>,
    mut headers: HashMap<String, String>,
    chia_version: impl for<'a> AsyncFn() -> Option<String>,
) -> Result<PostFarmerResponse, PoolError> {
    let payload = PostFarmerPayload {
        launcher_id: pool_config.launcher_id,
        authentication_token: get_current_authentication_token(authentication_token_timeout),
        authentication_public_key: do_auth(pool_config, owner_sk, auth_keys).await?,
        payout_instructions: parse_payout_address(payout_instructions).map_err(|e| PoolError {
            error_code: PoolErrorCode::InvalidPayoutInstructions as u8,
            error_message: format!(
                "Failed to Parse Payout Instructions: {}, {:?}",
                payout_instructions, e
            ),
        })?,
        suggested_difficulty,
    };
    let to_sign = hash_256(payload.to_bytes(PROTOCOL_VERSION));
    let signature = sign(owner_sk, &to_sign);
    if !verify_signature(&owner_sk.sk_to_pk(), &to_sign, &signature) {
        error!("Farmer POST Failed to Validate Signature");
        return Err(PoolError {
            error_code: PoolErrorCode::InvalidSignature as u8,
            error_message: "Local Failed to Validate Signature".to_string(),
        });
    }
    if let Some(v) = chia_version().await {
        headers.insert(String::from("X-chia-version"), v);
    }
    headers.extend(HEADERS.clone());
    client
        .post_farmer(
            &pool_config.pool_url,
            PostFarmerRequest {
                payload,
                signature: signature.to_bytes().into(),
            },
            &Some(headers),
        )
        .await
}

#[allow(clippy::too_many_arguments)]
pub async fn put_farmer<T: PoolClient + Sized + Sync + Send>(
    pool_config: &PoolWalletConfig,
    payout_instructions: &str,
    authentication_token_timeout: u8,
    owner_sk: &SecretKey,
    auth_keys: &HashMap<Bytes48, SecretKey>,
    suggested_difficulty: Option<u64>,
    client: Arc<T>,
    mut headers: HashMap<String, String>,
    chia_version: impl for<'a> AsyncFn() -> Option<String>,
) -> Result<PutFarmerResponse, PoolError> {
    let authentication_public_key = do_auth(pool_config, owner_sk, auth_keys).await?;
    let payload = PutFarmerPayload {
        launcher_id: pool_config.launcher_id,
        authentication_token: get_current_authentication_token(authentication_token_timeout),
        authentication_public_key: Some(authentication_public_key),
        payout_instructions: parse_payout_address(payout_instructions).ok(),
        suggested_difficulty,
    };
    let to_sign = hash_256(payload.to_bytes(PROTOCOL_VERSION));
    let signature = sign(owner_sk, &to_sign);
    if !verify_signature(&owner_sk.sk_to_pk(), &to_sign, &signature) {
        error!("Local Failed to Validate Signature");
        return Err(PoolError {
            error_code: PoolErrorCode::InvalidSignature as u8,
            error_message: "Local Failed to Validate Signature".to_string(),
        });
    }
    let request = PutFarmerRequest {
        payload,
        signature: signature.to_bytes().into(),
    };
    if let Some(v) = chia_version().await {
        headers.insert(String::from("X-chia-version"), v);
    }
    headers.extend(HEADERS.clone());
    client
        .put_farmer(&pool_config.pool_url, request, &Some(headers))
        .await
}

pub async fn update_pool_farmer_info<T, P: PoolClient + Sized + Sync + Send>(
    pool_states: Arc<RwLock<HashMap<Bytes32, FarmerPoolState>>>,
    pool_config: &PoolWalletConfig,
    authentication_token_timeout: u8,
    authentication_sk: &SecretKey,
    client: Arc<P>,
    headers: HashMap<String, String>,
    shared_state: Arc<FarmerSharedState<T>>,
) -> Result<GetFarmerResponse, PoolError> {
    let response = get_farmer(
        pool_config,
        authentication_token_timeout,
        authentication_sk,
        client,
        headers,
        async move || {
            shared_state
                .upstream_handshake
                .read()
                .await
                .as_ref()
                .map(|v| v.software_version.clone())
        },
    )
    .await?;
    pool_states
        .write()
        .await
        .get_mut(&pool_config.p2_singleton_puzzle_hash)
        .unwrap_or_else(|| {
            panic!(
                "Item Added to Map Above, Expected {} to exist",
                &pool_config.p2_singleton_puzzle_hash
            )
        })
        .current_difficulty = Some(response.current_difficulty);
    pool_states
        .write()
        .await
        .get_mut(&pool_config.p2_singleton_puzzle_hash)
        .unwrap_or_else(|| {
            panic!(
                "Item Added to Map Above, Expected {} to exist",
                &pool_config.p2_singleton_puzzle_hash
            )
        })
        .current_points = response.current_points;
    info!(
        "Updating Pool Difficulty: {:?} ",
        pool_states
            .read()
            .await
            .get(&pool_config.p2_singleton_puzzle_hash)
            .unwrap_or_else(|| panic!(
                "Item Added to Map Above, Expected {} to exist",
                &pool_config.p2_singleton_puzzle_hash
            ))
            .current_difficulty
    );
    info!(
        "Updating Current Points: {:?} ",
        pool_states
            .read()
            .await
            .get(&pool_config.p2_singleton_puzzle_hash)
            .unwrap_or_else(|| panic!(
                "Item Added to Map Above, Expected {} to exist",
                &pool_config.p2_singleton_puzzle_hash
            ))
            .current_points
    );
    Ok(response)
}

pub async fn update_pool_state<'a, T, C: Clone, P: 'a + PoolClient + Sized + Sync + Send>(
    client: Arc<P>,
    config: &Config<C>,
    shared_state: Arc<FarmerSharedState<T>>,
) -> Result<(), Error> {
    let auth_keys = shared_state.owner_public_keys_to_auth_secret_keys.as_ref();
    let owner_keys = shared_state.owner_secret_keys.as_ref();
    let pool_states = shared_state.pool_states.clone();
    let headers = shared_state.additional_headers.as_ref().clone();
    for pool_config in &config.pool_info {
        if let (Some(owner_secret_key), Some(auth_secret_key)) = (
            owner_keys.get(&pool_config.owner_public_key),
            auth_keys.get(&pool_config.owner_public_key),
        ) {
            if let Entry::Vacant(s) = pool_states
                .write()
                .await
                .entry(pool_config.p2_singleton_puzzle_hash)
            {
                info!(
                    "Adding Pool State for {}",
                    pool_config.p2_singleton_puzzle_hash
                );
                s.insert(FarmerPoolState {
                    points_found_since_start: 0,
                    points_found_24h: vec![],
                    points_acknowledged_since_start: 0,
                    points_acknowledged_24h: vec![],
                    next_farmer_update: Instant::now(),
                    next_pool_info_update: Instant::now(),
                    current_points: 0,
                    current_difficulty: None,
                    pool_config: None,
                    pool_errors_24h: vec![],
                    authentication_token_timeout: None,
                });
            }
            pool_states
                .write()
                .await
                .get_mut(&pool_config.p2_singleton_puzzle_hash)
                .unwrap_or_else(|| {
                    panic!(
                        "Item Added to Map Above, Expected {} to exist",
                        &pool_config.p2_singleton_puzzle_hash
                    )
                })
                .pool_config = Some(pool_config.clone());
            if pool_config.pool_url.is_empty() {
                continue;
            }
            if config.selected_network == "mainnet" && !pool_config.pool_url.starts_with("https") {
                error!(
                    "Pool URLs must be HTTPS on mainnet {}",
                    pool_config.pool_url
                );
                continue;
            }
            let next_pool_info_update = pool_states
                .read()
                .await
                .get(&pool_config.p2_singleton_puzzle_hash)
                .unwrap_or_else(|| {
                    panic!(
                        "Item Added to Map Above, Expected {} to exist",
                        &pool_config.p2_singleton_puzzle_hash
                    )
                })
                .next_pool_info_update;
            if Instant::now() >= next_pool_info_update {
                info!(
                    "Updating Pool Info {}",
                    pool_config.p2_singleton_puzzle_hash
                );
                //Makes a GET request to the pool to get the updated information
                match client.get_pool_info(&pool_config.pool_url).await {
                    Ok(pool_info) => {
                        pool_states
                            .write()
                            .await
                            .get_mut(&pool_config.p2_singleton_puzzle_hash)
                            .unwrap_or_else(|| {
                                panic!(
                                    "Item Added to Map Above, Expected {} to exist",
                                    &pool_config.p2_singleton_puzzle_hash
                                )
                            })
                            .authentication_token_timeout =
                            Some(pool_info.authentication_token_timeout);
                        // Only update the first time from GET /pool_info, gets updated from GET /farmer later
                        let is_first = pool_states
                            .read()
                            .await
                            .get(&pool_config.p2_singleton_puzzle_hash)
                            .unwrap_or_else(|| {
                                panic!(
                                    "Item Added to Map Above, Expected {} to exist",
                                    &pool_config.p2_singleton_puzzle_hash
                                )
                            })
                            .current_difficulty
                            .is_none();
                        if is_first {
                            pool_states
                                .write()
                                .await
                                .get_mut(&pool_config.p2_singleton_puzzle_hash)
                                .unwrap_or_else(|| {
                                    panic!(
                                        "Item Added to Map Above, Expected {} to exist",
                                        &pool_config.p2_singleton_puzzle_hash
                                    )
                                })
                                .current_difficulty = Some(pool_info.minimum_difficulty);
                        }
                        pool_states
                            .write()
                            .await
                            .get_mut(&pool_config.p2_singleton_puzzle_hash)
                            .unwrap_or_else(|| {
                                panic!(
                                    "Item Added to Map Above, Expected {} to exist",
                                    &pool_config.p2_singleton_puzzle_hash
                                )
                            })
                            .next_pool_info_update =
                            Instant::now() + Duration::from_secs(UPDATE_POOL_INFO_INTERVAL);
                    }
                    Err(e) => {
                        pool_states
                            .write()
                            .await
                            .get_mut(&pool_config.p2_singleton_puzzle_hash)
                            .unwrap_or_else(|| {
                                panic!(
                                    "Item Added to Map Above, Expected {} to exist",
                                    &pool_config.p2_singleton_puzzle_hash
                                )
                            })
                            .next_pool_info_update = Instant::now()
                            + Duration::from_secs(UPDATE_POOL_INFO_FAILURE_RETRY_INTERVAL);
                        error!("Update Pool Info Error: {:?}", e);
                    }
                }
            } else {
                debug!("Not Ready for Update");
            }
            let next_farmer_update = pool_states
                .read()
                .await
                .get(&pool_config.p2_singleton_puzzle_hash)
                .unwrap_or_else(|| {
                    panic!(
                        "Item Added to Map Above, Expected {} to exist",
                        &pool_config.p2_singleton_puzzle_hash
                    )
                })
                .next_farmer_update;
            if Instant::now() >= next_farmer_update {
                info!(
                    "Updating Pool Info {}",
                    pool_config.p2_singleton_puzzle_hash
                );
                pool_states
                    .write()
                    .await
                    .get_mut(&pool_config.p2_singleton_puzzle_hash)
                    .unwrap_or_else(|| {
                        panic!(
                            "Item Added to Map Above, Expected {} to exist",
                            &pool_config.p2_singleton_puzzle_hash
                        )
                    })
                    .next_farmer_update =
                    Instant::now() + Duration::from_secs(UPDATE_POOL_FARMER_INFO_INTERVAL);
                let authentication_token_timeout = pool_states
                    .read()
                    .await
                    .get(&pool_config.p2_singleton_puzzle_hash)
                    .unwrap_or_else(|| {
                        panic!(
                            "Item Added to Map Above, Expected {} to exist",
                            &pool_config.p2_singleton_puzzle_hash
                        )
                    })
                    .authentication_token_timeout;
                if let Some(authentication_token_timeout) = authentication_token_timeout {
                    info!("Running Farmer Pool Update");
                    let farmer_info = match update_pool_farmer_info(
                        pool_states.clone(),
                        pool_config,
                        authentication_token_timeout,
                        auth_secret_key,
                        client.clone(),
                        headers.clone(),
                        shared_state.clone(),
                    )
                    .await
                    {
                        Ok(resp) => Some(resp),
                        Err(e) => {
                            if e.error_code == PoolErrorCode::FarmerNotKnown as u8 {
                                warn!("Farmer Pool Not Known");
                                let post_shared_state = shared_state.clone();
                                match post_farmer(
                                    pool_config,
                                    &config.payout_address,
                                    authentication_token_timeout,
                                    owner_secret_key,
                                    auth_keys,
                                    pool_config.difficulty,
                                    client.clone(),
                                    headers.clone(),
                                    async move || {
                                        post_shared_state
                                            .upstream_handshake
                                            .read()
                                            .await
                                            .as_ref()
                                            .map(|v| v.software_version.clone())
                                    },
                                )
                                .await
                                {
                                    Ok(resp) => {
                                        info!(
                                            "Welcome message from {} : {}",
                                            pool_config.pool_url, resp.welcome_message
                                        );
                                    }
                                    Err(e) => {
                                        error!("Failed post farmer info. {:?}", e);
                                    }
                                }
                                match update_pool_farmer_info(
                                    pool_states.clone(),
                                    pool_config,
                                    authentication_token_timeout,
                                    auth_secret_key,
                                    client.clone(),
                                    headers.clone(),
                                    shared_state.clone(),
                                )
                                .await
                                {
                                    Ok(resp) => Some(resp),
                                    Err(e) => {
                                        error!(
                                            "Failed to update farmer info after POST /farmer. {:?}",
                                            e
                                        );
                                        None
                                    }
                                }
                            } else if e.error_code == PoolErrorCode::InvalidSignature as u8 {
                                warn!("Invalid Signature Detected, Updating Farmer Auth Key");
                                let put_shared_state = shared_state.clone();
                                match put_farmer(
                                    pool_config,
                                    &config.payout_address,
                                    authentication_token_timeout,
                                    owner_secret_key,
                                    auth_keys,
                                    pool_config.difficulty,
                                    client.clone(),
                                    headers.clone(),
                                    async move || {
                                        put_shared_state
                                            .upstream_handshake
                                            .read()
                                            .await
                                            .as_ref()
                                            .map(|v| v.software_version.clone())
                                    },
                                )
                                .await
                                {
                                    Ok(res) => {
                                        info!("Farmer Update Response: {:?}", res);
                                        update_pool_farmer_info(
                                            pool_states.clone(),
                                            pool_config,
                                            authentication_token_timeout,
                                            auth_secret_key,
                                            client.clone(),
                                            headers.clone(),
                                            shared_state.clone(),
                                        )
                                        .await
                                        .ok()
                                    }
                                    Err(e) => {
                                        error!("Failed to update farmer auth key. {:?}", e);
                                        None
                                    }
                                }
                            } else {
                                None
                            }
                        }
                    };
                    let old_instructions;
                    let payout_instructions_update_required = if let Some(info) = farmer_info {
                        info!("Farmer Info: {:?}", &info);
                        if let (Ok(p1), Ok(p2)) = (
                            parse_payout_address(&config.payout_address.to_ascii_lowercase()),
                            parse_payout_address(&info.payout_instructions.to_ascii_lowercase()),
                        ) {
                            old_instructions = p2;
                            p1 != old_instructions
                        } else {
                            old_instructions = String::new();
                            false
                        }
                    } else {
                        warn!("Did not get response from pool!");
                        old_instructions = String::new();
                        false
                    };
                    let current_difficulty = pool_states
                        .read()
                        .await
                        .get(&pool_config.p2_singleton_puzzle_hash)
                        .unwrap_or_else(|| {
                            panic!(
                                "Item Added to Map Above, Expected {} to exist",
                                &pool_config.p2_singleton_puzzle_hash
                            )
                        })
                        .current_difficulty;
                    let difficulty_update_required = pool_config.difficulty.unwrap_or_default() > 0
                        && current_difficulty != pool_config.difficulty;
                    debug!(
                        "Current Pool Payout Address: {}",
                        encode_puzzle_hash(
                            &Bytes32::from_str(
                                &parse_payout_address(&old_instructions).unwrap_or_default()
                            )?,
                            "xch"
                        )
                        .unwrap_or_default()
                    );
                    debug!(
                        "Desired Pool Payout Address: {}",
                        encode_puzzle_hash(
                            &Bytes32::from_str(
                                &parse_payout_address(&config.payout_address).unwrap_or_default()
                            )?,
                            "xch"
                        )
                        .unwrap_or_default()
                    );
                    if payout_instructions_update_required || difficulty_update_required {
                        if payout_instructions_update_required {
                            info!(
                                "Updating Payout Address from {} to {}",
                                old_instructions,
                                parse_payout_address(&config.payout_address.to_ascii_lowercase())
                                    .unwrap_or_default(),
                            );
                        }
                        if difficulty_update_required {
                            info!(
                                "Updating Difficulty from {} to {}",
                                current_difficulty.unwrap_or_default(),
                                pool_config.difficulty.unwrap_or_default()
                            );
                        }
                        match owner_keys.get(&pool_config.owner_public_key) {
                            None => {
                                error!(
                                    "Could not find Owner SK for {}",
                                    &pool_config.owner_public_key
                                );
                                continue;
                            }
                            Some(sk) => {
                                let put_shared_state = shared_state.clone();
                                match put_farmer(
                                    pool_config,
                                    &config.payout_address,
                                    authentication_token_timeout,
                                    sk,
                                    auth_keys,
                                    pool_config.difficulty,
                                    client.clone(),
                                    headers.clone(),
                                    async move || {
                                        put_shared_state
                                            .upstream_handshake
                                            .read()
                                            .await
                                            .as_ref()
                                            .map(|v| v.software_version.clone())
                                    },
                                )
                                .await
                                {
                                    Ok(res) => {
                                        if payout_instructions_update_required {
                                            if let Some(false) = res.payout_instructions {
                                                error!("Pool Rejected Updating Payout Address")
                                            }
                                        }
                                        if difficulty_update_required {
                                            if let Some(true) = res.suggested_difficulty {
                                                info!(
                                                    "Updated Pool Difficulty to {:?}",
                                                    pool_config.difficulty.unwrap_or_default()
                                                );
                                                pool_states
                                                    .write()
                                                    .await
                                                    .get_mut(&pool_config.p2_singleton_puzzle_hash)
                                                    .unwrap_or_else(|| panic!("Item Added to Map Above, Expected {} to exist",
                                                                              &pool_config.p2_singleton_puzzle_hash))
                                                    .current_difficulty = pool_config.difficulty
                                            } else if let Some(false) = res.payout_instructions {
                                                error!("Pool Rejected Updating Difficulty")
                                            }
                                        }
                                        info!("Farmer Update Response: {:?}", res);
                                    }
                                    Err(e) => {
                                        error!("Failed to update farmer auth key. {:?}", e);
                                    }
                                }
                            }
                        }
                    }
                } else {
                    warn!(
                        "No pool specific authentication_token_timeout has been set for {}, check communication with the pool.",
                        &pool_config.p2_singleton_puzzle_hash
                    );
                }
            }
        } else {
            warn!(
                "Could not find owner sk for: {:?}",
                &pool_config.owner_public_key
            );
        }
    }
    Ok(())
}