cdp-sdk 0.5.0

SDK for interacting with the Coinbase Developer Platform Wallet API
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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
use crate::error::CdpError;
use base64::Engine;
use bon::bon;
use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
use reqwest::{Request, Response};
use reqwest_middleware::{Middleware, Next};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};
use uuid::Uuid;

const VERSION: &str = env!("CARGO_PKG_VERSION");

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Claims {
    sub: String,
    iss: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    aud: Option<Vec<String>>,
    exp: u64,
    iat: u64,
    nbf: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    uris: Option<Vec<String>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct WalletClaims {
    iat: u64,
    nbf: u64,
    jti: String,
    uris: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "reqHash")]
    req_hash: Option<String>,
}

/// Configuration options for the CDP Wallet Auth client
#[derive(Debug, Clone, Default)]
pub struct WalletAuth {
    /// The API key ID
    pub api_key_id: String,
    /// The API key secret
    pub api_key_secret: String,
    /// The wallet secret
    pub wallet_secret: Option<String>,
    /// Whether to enable debugging
    pub debug: bool,
    /// The source identifier for requests
    pub source: String,
    /// The version of the source making requests
    pub source_version: Option<String>,
    /// JWT expiration time in seconds
    pub expires_in: u64,
}

/// Configuration options for standalone JWT generation.
///
/// This struct holds all necessary parameters for generating a JWT token
/// for authenticating with the [Coinbase Developer Platform (CDP)](https://docs.cdp.coinbase.com/) REST APIs.
/// It supports both EC (ES256) and Ed25519 (EdDSA) keys.
///
/// When `request_method`, `request_host`, and `request_path` are all `None`,
/// the `uris` claim is omitted from the JWT (useful for websocket connections).
///
/// # Examples
///
/// ```no_run
/// use cdp_sdk::auth::{generate_jwt, JwtOptions};
///
/// // For REST API requests
/// let jwt = generate_jwt(JwtOptions::builder()
///     .api_key_id("your-api-key-id".to_string())
///     .api_key_secret("your-api-key-secret".to_string())
///     .request_method("GET".to_string())
///     .request_host("api.cdp.coinbase.com".to_string())
///     .request_path("/platform/v2/evm/accounts".to_string())
///     .build()
/// )?;
/// # Ok::<(), cdp_sdk::error::CdpError>(())
/// ```
#[derive(Debug, Clone)]
pub struct JwtOptions {
    /// The API key ID. Supported formats:
    /// - `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`
    /// - `organizations/{orgId}/apiKeys/{keyId}`
    pub api_key_id: String,
    /// The API key secret. Supported formats:
    /// - Edwards key (Ed25519): base64-encoded 64-byte key
    /// - Elliptic Curve key (ES256): PEM-encoded EC private key
    pub api_key_secret: String,
    /// HTTP method (e.g. "GET", "POST"). `None` for websocket JWTs.
    pub request_method: Option<String>,
    /// Request host (e.g. "api.cdp.coinbase.com"). `None` for websocket JWTs.
    pub request_host: Option<String>,
    /// Request path (e.g. "/platform/v2/evm/accounts"). `None` for websocket JWTs.
    pub request_path: Option<String>,
    /// JWT expiration time in seconds. Defaults to 120 (2 minutes).
    pub expires_in: Option<u64>,
    /// Optional audience claim for the JWT.
    pub audience: Option<Vec<String>>,
}

#[bon::bon]
impl JwtOptions {
    #[builder]
    pub fn new(
        api_key_id: String,
        api_key_secret: String,
        request_method: Option<String>,
        request_host: Option<String>,
        request_path: Option<String>,
        expires_in: Option<u64>,
        audience: Option<Vec<String>>,
    ) -> Self {
        Self {
            api_key_id,
            api_key_secret,
            request_method,
            request_host,
            request_path,
            expires_in,
            audience,
        }
    }
}

/// Generates a JWT (Bearer token) for authenticating with the CDP REST APIs.
///
/// This is a standalone function that accepts explicit options for JWT generation,
/// matching the pattern used by the TypeScript, Python, and Go SDKs. Use this when
/// you need to generate JWTs without constructing a [`WalletAuth`] instance.
///
/// Supports both EC (ES256) and Ed25519 (EdDSA) keys. When all request parameters
/// (`request_method`, `request_host`, `request_path`) are `None`, the `uris` claim
/// is omitted from the JWT (for websocket connections).
///
/// # Arguments
///
/// * `options` - Configuration options for JWT generation
///
/// # Returns
///
/// The signed JWT string.
///
/// # Errors
///
/// Returns [`CdpError::Auth`] if:
/// - The key format is invalid (neither EC PEM nor base64 Ed25519)
/// - Only some request parameters are provided (must be all or none)
/// - JWT signing fails
///
/// # Examples
///
/// ```no_run
/// use cdp_sdk::auth::{generate_jwt, JwtOptions};
///
/// // For REST API requests
/// let jwt = generate_jwt(JwtOptions::builder()
///     .api_key_id("your-key-id".to_string())
///     .api_key_secret("your-key-secret".to_string())
///     .request_method("GET".to_string())
///     .request_host("api.cdp.coinbase.com".to_string())
///     .request_path("/platform/v2/evm/accounts".to_string())
///     .build()
/// )?;
///
/// // For websocket connections (no uris claim)
/// let ws_jwt = generate_jwt(JwtOptions::builder()
///     .api_key_id("your-key-id".to_string())
///     .api_key_secret("your-key-secret".to_string())
///     .build()
/// )?;
/// # Ok::<(), cdp_sdk::error::CdpError>(())
/// ```
pub fn generate_jwt(options: JwtOptions) -> Result<String, CdpError> {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();

    let expires_in = options.expires_in.unwrap_or(120);

    // Validate: either all request params or none
    let uris = match (
        &options.request_method,
        &options.request_host,
        &options.request_path,
    ) {
        (Some(method), Some(host), Some(path)) => {
            Some(vec![format!("{} {}{}", method, host, path)])
        }
        (None, None, None) => None,
        _ => {
            return Err(CdpError::Auth(
                "Either all request details (request_method, request_host, request_path) \
                 must be provided, or all must be None for websocket JWTs"
                    .to_string(),
            ));
        }
    };

    let claims = Claims {
        sub: options.api_key_id.clone(),
        iss: "cdp".to_string(),
        aud: options.audience,
        exp: now + expires_in,
        iat: now,
        nbf: now,
        uris,
    };

    let (algorithm, encoding_key) = parse_signing_key(&options.api_key_secret)?;

    let mut header = Header::new(algorithm);
    header.kid = Some(options.api_key_id);

    encode(&header, &claims, &encoding_key)
        .map_err(|e| CdpError::Auth(format!("Failed to encode JWT: {}", e)))
}

/// Parses an API key secret and returns the appropriate signing algorithm and encoding key.
///
/// Supports EC PEM keys (ES256) and base64-encoded Ed25519 keys (EdDSA).
fn parse_signing_key(api_key_secret: &str) -> Result<(Algorithm, EncodingKey), CdpError> {
    if is_ec_pem_key(api_key_secret) {
        // PEM format EC key - use ES256
        let key = EncodingKey::from_ec_pem(api_key_secret.as_bytes())
            .map_err(|e| CdpError::Auth(format!("Failed to parse EC PEM key: {}", e)))?;
        Ok((Algorithm::ES256, key))
    } else if is_ed25519_key(api_key_secret) {
        // Base64 Ed25519 key - use EdDSA
        let decoded = base64::engine::general_purpose::STANDARD
            .decode(api_key_secret)
            .map_err(|e| CdpError::Auth(format!("Failed to decode Ed25519 key: {}", e)))?;

        if decoded.len() != 64 {
            return Err(CdpError::Auth(
                "Invalid Ed25519 key length, expected 64 bytes".to_string(),
            ));
        }

        // Extract the seed (first 32 bytes) and create PKCS#8 DER format
        let seed = &decoded[0..32];
        let mut pkcs8_der = Vec::new();
        let pkcs8_header = hex::decode("302e020100300506032b657004220420").unwrap();
        pkcs8_der.extend_from_slice(&pkcs8_header);
        pkcs8_der.extend_from_slice(seed);

        // Convert to PEM format
        let pem_content = base64::engine::general_purpose::STANDARD.encode(&pkcs8_der);
        let pem_formatted = format!(
            "-----BEGIN PRIVATE KEY-----\n{}\n-----END PRIVATE KEY-----",
            pem_content
                .chars()
                .collect::<Vec<_>>()
                .chunks(64)
                .map(|chunk| chunk.iter().collect::<String>())
                .collect::<Vec<_>>()
                .join("\n")
        );

        let key = EncodingKey::from_ed_pem(pem_formatted.as_bytes())
            .map_err(|e| CdpError::Auth(format!("Failed to parse Ed25519 key: {}", e)))?;
        Ok((Algorithm::EdDSA, key))
    } else {
        Err(CdpError::Auth(
            "Invalid key format - must be either PEM EC key or base64 Ed25519 key".to_string(),
        ))
    }
}

#[bon]
impl WalletAuth {
    #[builder]
    pub fn new(
        /// The API key ID
        api_key_id: Option<String>,
        /// The API key secret
        api_key_secret: Option<String>,
        /// The wallet secret
        wallet_secret: Option<String>,
        /// Whether to enable debugging
        debug: Option<bool>,
        /// The source identifier for requests
        source: Option<String>,
        /// The version of the source making requests
        source_version: Option<String>,
        /// JWT expiration time in seconds
        expires_in: Option<u64>,
    ) -> Result<Self, CdpError> {
        use std::env;

        // Get configuration from options or environment variables
        let api_key_id = api_key_id
            .or_else(|| env::var("CDP_API_KEY_ID").ok())
            .ok_or_else(|| {
                CdpError::Config(
                    "Missing required CDP API Key ID configuration.\n\n\
                        You can set them as environment variables:\n\
                        CDP_API_KEY_ID=your-api-key-id\n\
                        CDP_API_KEY_SECRET=your-api-key-secret\n\n\
                        Or pass them directly to the CdpClientOptions."
                        .to_string(),
                )
            })?;

        let api_key_secret = api_key_secret
            .or_else(|| env::var("CDP_API_KEY_SECRET").ok())
            .ok_or_else(|| {
                CdpError::Config(
                    "Missing required CDP API Key Secret configuration.\n\n\
                        You can set them as environment variables:\n\
                        CDP_API_KEY_ID=your-api-key-id\n\
                        CDP_API_KEY_SECRET=your-api-key-secret\n\n\
                        Or pass them directly to the CdpClientOptions."
                        .to_string(),
                )
            })?;

        let wallet_secret = wallet_secret.or_else(|| env::var("CDP_WALLET_SECRET").ok());

        let debug = debug.unwrap_or(false);
        let expires_in = expires_in.unwrap_or(120);
        let source = source.unwrap_or("sdk-auth".to_string());

        Ok(WalletAuth {
            api_key_id,
            api_key_secret,
            wallet_secret,
            debug,
            source,
            source_version,
            expires_in,
        })
    }

    /// Generates a JWT (Bearer token) for authenticating with the CDP REST APIs.
    ///
    /// Uses the `api_key_id` and `api_key_secret` from this [`WalletAuth`] instance
    /// to sign the JWT. For a standalone function that doesn't require a `WalletAuth`
    /// instance, see [`generate_jwt`].
    ///
    /// # Arguments
    ///
    /// * `method` - The HTTP method (e.g. "GET", "POST")
    /// * `host` - The request host (e.g. "api.cdp.coinbase.com")
    /// * `path` - The request path (e.g. "/platform/v2/evm/accounts")
    /// * `expires_in` - JWT expiration time in seconds
    ///
    /// # Returns
    ///
    /// The signed JWT string.
    ///
    /// # Errors
    ///
    /// Returns [`CdpError::Auth`] if the key format is invalid or signing fails.
    pub fn generate_jwt(
        &self,
        method: &str,
        host: &str,
        path: &str,
        expires_in: u64,
    ) -> Result<String, CdpError> {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let claims = Claims {
            sub: self.api_key_id.clone(),
            iss: "cdp".to_string(),
            aud: None,
            exp: now + expires_in,
            iat: now,
            nbf: now,
            uris: Some(vec![format!("{} {}{}", method, host, path)]),
        };

        let (algorithm, encoding_key) = parse_signing_key(&self.api_key_secret)?;

        let mut header = Header::new(algorithm);
        header.kid = Some(self.api_key_id.clone());

        encode(&header, &claims, &encoding_key)
            .map_err(|e| CdpError::Auth(format!("Failed to encode JWT: {}", e)))
    }

    pub fn generate_wallet_jwt(
        &self,
        method: &str,
        host: &str,
        path: &str,
        body: &[u8],
    ) -> Result<String, CdpError> {
        let wallet_secret = self.wallet_secret.as_ref().ok_or_else(|| {
            CdpError::Auth("Wallet secret required for this operation".to_string())
        })?;

        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let uri = format!("{} {}{}", method, host, path);
        let jti = format!("{:x}", Uuid::new_v4().simple()); // Use hex format like JavaScript

        // Calculate reqHash only if body is not empty, using hex format like JavaScript
        let req_hash = if !body.is_empty() {
            // Parse body as JSON and sort keys
            let body_str = std::str::from_utf8(body)
                .map_err(|e| CdpError::Auth(format!("Invalid UTF-8 in request body: {}", e)))?;

            if !body_str.trim().is_empty() {
                let parsed: Value = serde_json::from_str(body_str)
                    .map_err(|e| CdpError::Auth(format!("Failed to parse JSON body: {}", e)))?;

                let sorted = sort_keys(parsed);
                let sorted_json = serde_json::to_string(&sorted).map_err(|e| {
                    CdpError::Auth(format!("Failed to serialize sorted JSON: {}", e))
                })?;

                let mut hasher = Sha256::new();
                hasher.update(sorted_json.as_bytes());
                Some(format!("{:x}", hasher.finalize()))
            } else {
                None
            }
        } else {
            None
        };

        let claims = WalletClaims {
            iat: now,
            nbf: now, // Add nbf like JavaScript
            jti,
            uris: vec![uri],
            req_hash,
        };

        let header = Header::new(Algorithm::ES256);

        // Decode the base64 wallet secret
        let der_bytes = base64::engine::general_purpose::STANDARD
            .decode(wallet_secret)
            .map_err(|e| CdpError::Auth(format!("Failed to decode wallet secret: {}", e)))?;

        let encoding_key = EncodingKey::from_ec_der(&der_bytes);

        encode(&header, &claims, &encoding_key)
            .map_err(|e| CdpError::Auth(format!("Failed to encode wallet JWT: {}", e)))
    }

    fn requires_wallet_auth(&self, method: &str, path: &str) -> bool {
        (path.contains("/accounts") || path.contains("/spend-permissions"))
            && (method == "POST" || method == "DELETE" || method == "PUT")
    }

    fn get_correlation_data(&self) -> String {
        let mut data = HashMap::new();

        data.insert("sdk_version".to_string(), VERSION.to_string());
        data.insert("sdk_language".to_string(), "rust".to_string());
        data.insert("source".to_string(), self.source.clone());

        if let Some(ref source_version) = self.source_version {
            data.insert("source_version".to_string(), source_version.clone());
        }

        data.into_iter()
            .map(|(k, v)| format!("{}={}", k, urlencoding::encode(&v)))
            .collect::<Vec<_>>()
            .join(",")
    }
}

#[async_trait::async_trait]
impl Middleware for WalletAuth {
    async fn handle(
        &self,
        mut req: Request,
        extensions: &mut http::Extensions,
        next: Next<'_>,
    ) -> reqwest_middleware::Result<Response> {
        let method = req.method().as_str().to_uppercase();
        let url = req.url().clone();
        let host = url.host_str().unwrap_or("api.cdp.coinbase.com");
        let path = url.path();

        // Get request body for wallet auth
        let body = if let Some(body) = req.body() {
            body.as_bytes().unwrap_or_default().to_vec()
        } else {
            Vec::new()
        };

        let expires_in = self.expires_in;

        // Generate main JWT
        let jwt = self
            .generate_jwt(&method, host, path, expires_in)
            .map_err(reqwest_middleware::Error::middleware)?;

        // Add authorization header
        req.headers_mut()
            .insert("Authorization", format!("Bearer {}", jwt).parse().unwrap());

        // Add content type
        req.headers_mut()
            .insert("Content-Type", "application/json".parse().unwrap());

        // Add wallet auth if needed, and not already provided or if empty
        if self.requires_wallet_auth(&method, path)
            && (!req.headers().contains_key("X-Wallet-Auth")
                || req
                    .headers()
                    .get("X-Wallet-Auth")
                    .is_none_or(|v| v.is_empty()))
        {
            let wallet_jwt = self
                .generate_wallet_jwt(&method, host, path, &body)
                .map_err(reqwest_middleware::Error::middleware)?;

            req.headers_mut()
                .insert("X-Wallet-Auth", wallet_jwt.parse().unwrap());
        }

        // Add correlation data
        req.headers_mut().insert(
            "Correlation-Context",
            self.get_correlation_data().parse().unwrap(),
        );

        if self.debug {
            println!("Request: {} {}", method, url);
            println!("Headers: {:?}", req.headers());
        }

        let response = next.run(req, extensions).await;

        if self.debug {
            if let Ok(ref resp) = response {
                println!(
                    "Response: {} {}",
                    resp.status(),
                    resp.status().canonical_reason().unwrap_or("")
                );
            }
        }

        response
    }
}

fn sort_keys(value: Value) -> Value {
    match value {
        Value::Object(map) => {
            let mut sorted_map = serde_json::Map::new();
            let mut keys: Vec<_> = map.keys().collect();
            keys.sort();
            for key in keys {
                if let Some(val) = map.get(key) {
                    sorted_map.insert(key.clone(), sort_keys(val.clone()));
                }
            }
            Value::Object(sorted_map)
        }
        Value::Array(arr) => Value::Array(arr.into_iter().map(sort_keys).collect()),
        _ => value,
    }
}

/// Returns `true` if the given key string is a base64-encoded Ed25519 key (64 bytes when decoded).
///
/// Ed25519 keys in this format consist of 32 bytes of seed followed by 32 bytes of public key,
/// encoded together as a single 64-byte base64 string.
pub fn is_ed25519_key(key: &str) -> bool {
    if let Ok(decoded) = base64::engine::general_purpose::STANDARD.decode(key) {
        decoded.len() == 64
    } else {
        false
    }
}

/// Returns `true` if the given key string looks like a PEM-format EC private key.
///
/// Checks for the presence of PEM markers (`BEGIN`/`END`) and key type indicators
/// (`EC PRIVATE KEY` or `PRIVATE KEY`).
pub fn is_ec_pem_key(key: &str) -> bool {
    key.contains("-----BEGIN")
        && key.contains("-----END")
        && (key.contains("EC PRIVATE KEY") || key.contains("PRIVATE KEY"))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_wallet_auth_builder_with_all_fields() {
        let auth = WalletAuth::builder()
            .api_key_id("test_key_id".to_string())
            .api_key_secret("test_key_secret".to_string())
            .wallet_secret("test_wallet_secret".to_string())
            .debug(true)
            .source("test_source".to_string())
            .source_version("1.0.0".to_string())
            .expires_in(300)
            .build()
            .unwrap();

        assert_eq!(auth.api_key_id, "test_key_id");
        assert_eq!(auth.api_key_secret, "test_key_secret");
        assert_eq!(auth.wallet_secret, Some("test_wallet_secret".to_string()));
        assert!(auth.debug);
        assert_eq!(auth.source, "test_source");
        assert_eq!(auth.source_version, Some("1.0.0".to_string()));
        assert_eq!(auth.expires_in, 300);
    }

    #[test]
    fn test_wallet_auth_builder_with_required_fields_only() {
        let auth = WalletAuth::builder()
            .api_key_id("test_key_id".to_string())
            .api_key_secret("test_key_secret".to_string())
            .build()
            .unwrap();

        assert_eq!(auth.api_key_id, "test_key_id");
        assert_eq!(auth.api_key_secret, "test_key_secret");
        assert_eq!(auth.wallet_secret, None);
        assert!(!auth.debug);
        assert_eq!(auth.source, "sdk-auth");
        assert_eq!(auth.source_version, None);
        assert_eq!(auth.expires_in, 120);
    }

    #[test]
    fn test_wallet_auth_builder_with_optional_fields() {
        let auth = WalletAuth::builder()
            .api_key_id("test_key_id".to_string())
            .api_key_secret("test_key_secret".to_string())
            .debug(true)
            .expires_in(600)
            .build()
            .unwrap();

        assert_eq!(auth.api_key_id, "test_key_id");
        assert_eq!(auth.api_key_secret, "test_key_secret");
        assert!(auth.debug);
        assert_eq!(auth.expires_in, 600);
        assert_eq!(auth.source, "sdk-auth"); // default value
    }

    #[test]
    fn test_wallet_auth_builder_missing_api_key_id() {
        let result = WalletAuth::builder()
            .api_key_secret("test_key_secret".to_string())
            .build();

        assert!(result.is_err());
        if let Err(CdpError::Config(msg)) = result {
            assert!(msg.contains("Missing required CDP API Key ID configuration"));
        } else {
            panic!("Expected Config error for missing api_key_id");
        }
    }

    #[test]
    fn test_wallet_auth_builder_missing_api_key_secret() {
        let result = WalletAuth::builder()
            .api_key_id("test_key_id".to_string())
            .build();

        assert!(result.is_err());
        if let Err(CdpError::Config(msg)) = result {
            assert!(msg.contains("Missing required CDP API Key Secret configuration"));
        } else {
            panic!("Expected Config error for missing api_key_secret");
        }
    }

    #[test]
    fn test_wallet_auth_builder_custom_source() {
        let auth = WalletAuth::builder()
            .api_key_id("test_key_id".to_string())
            .api_key_secret("test_key_secret".to_string())
            .source("my-custom-app".to_string())
            .source_version("2.1.0".to_string())
            .build()
            .unwrap();

        assert_eq!(auth.source, "my-custom-app");
        assert_eq!(auth.source_version, Some("2.1.0".to_string()));
    }

    #[test]
    fn test_requires_wallet_auth() {
        let auth = WalletAuth::builder()
            .api_key_id("test_key_id".to_string())
            .api_key_secret("test_key_secret".to_string())
            .build()
            .unwrap();

        // Should require wallet auth for POST to accounts
        assert!(auth.requires_wallet_auth("POST", "/v2/evm/accounts"));

        // Should require wallet auth for PUT to accounts
        assert!(auth.requires_wallet_auth("PUT", "/v2/evm/accounts/0x123"));

        // Should require wallet auth for DELETE to accounts
        assert!(auth.requires_wallet_auth("DELETE", "/v2/evm/accounts/0x123"));

        // Should require wallet auth for spend-permissions
        assert!(auth.requires_wallet_auth("POST", "/v2/spend-permissions"));

        // Should NOT require wallet auth for GET requests
        assert!(!auth.requires_wallet_auth("GET", "/v2/evm/accounts"));

        // Should NOT require wallet auth for non-account endpoints
        assert!(!auth.requires_wallet_auth("POST", "/v2/other/endpoint"));
    }

    #[test]
    fn test_is_ed25519_key() {
        // Valid base64 encoded 64-byte key
        let valid_ed25519 = base64::engine::general_purpose::STANDARD.encode([0u8; 64]);
        assert!(is_ed25519_key(&valid_ed25519));

        // Invalid key (wrong length)
        let invalid_key = base64::engine::general_purpose::STANDARD.encode([0u8; 32]);
        assert!(!is_ed25519_key(&invalid_key));

        // Not base64
        assert!(!is_ed25519_key("not-base64"));
    }

    #[test]
    fn test_is_ec_pem_key() {
        let pem_key = "-----BEGIN EC PRIVATE KEY-----\ntest\n-----END EC PRIVATE KEY-----";
        assert!(is_ec_pem_key(pem_key));

        let generic_pem_key = "-----BEGIN PRIVATE KEY-----\ntest\n-----END PRIVATE KEY-----";
        assert!(is_ec_pem_key(generic_pem_key));

        let not_pem_key = "just-a-string";
        assert!(!is_ec_pem_key(not_pem_key));
    }

    // --- Test helpers ---

    fn generate_ec_pem_key() -> String {
        use p256::ecdsa::SigningKey;
        use p256::elliptic_curve::rand_core::OsRng;
        use p256::pkcs8::EncodePrivateKey;

        let signing_key = SigningKey::random(&mut OsRng);
        let pkcs8_pem = signing_key
            .to_pkcs8_pem(p256::pkcs8::LineEnding::LF)
            .expect("Failed to export EC key as PKCS8 PEM");
        pkcs8_pem.to_string()
    }

    fn generate_ed25519_key_base64() -> String {
        use ed25519_dalek::SigningKey;

        let mut csprng = p256::elliptic_curve::rand_core::OsRng;
        let signing_key = SigningKey::generate(&mut csprng);
        let seed = signing_key.to_bytes();
        let public = signing_key.verifying_key().to_bytes();

        let mut combined = Vec::with_capacity(64);
        combined.extend_from_slice(&seed);
        combined.extend_from_slice(&public);

        base64::engine::general_purpose::STANDARD.encode(&combined)
    }

    fn decode_jwt_header(token: &str) -> serde_json::Value {
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts.len(), 3, "JWT should have 3 parts");
        let header_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
            .decode(parts[0])
            .expect("Failed to decode JWT header");
        serde_json::from_slice(&header_bytes).expect("Failed to parse JWT header as JSON")
    }

    fn decode_jwt_claims(token: &str) -> serde_json::Value {
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts.len(), 3, "JWT should have 3 parts");
        let claims_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
            .decode(parts[1])
            .expect("Failed to decode JWT claims");
        serde_json::from_slice(&claims_bytes).expect("Failed to parse JWT claims as JSON")
    }

    // --- Standalone generate_jwt tests ---

    #[test]
    fn test_generate_jwt_with_ec_key() {
        let ec_key = generate_ec_pem_key();
        let token = generate_jwt(
            JwtOptions::builder()
                .api_key_id("test-key-id".to_string())
                .api_key_secret(ec_key)
                .request_method("GET".to_string())
                .request_host("api.cdp.coinbase.com".to_string())
                .request_path("/platform/v2/evm/accounts".to_string())
                .expires_in(120u64)
                .build(),
        )
        .unwrap();

        let header = decode_jwt_header(&token);
        assert_eq!(header["alg"], "ES256");
        assert_eq!(header["kid"], "test-key-id");

        let claims = decode_jwt_claims(&token);
        assert_eq!(claims["sub"], "test-key-id");
        assert_eq!(claims["iss"], "cdp");
        assert!(claims.get("aud").is_none() || claims["aud"].is_null());

        let uris = claims["uris"].as_array().expect("uris should be an array");
        assert_eq!(uris.len(), 1);
        assert_eq!(uris[0], "GET api.cdp.coinbase.com/platform/v2/evm/accounts");

        let exp = claims["exp"].as_u64().unwrap();
        let iat = claims["iat"].as_u64().unwrap();
        assert_eq!(exp - iat, 120);
    }

    #[test]
    fn test_generate_jwt_with_ed25519_key() {
        let ed_key = generate_ed25519_key_base64();
        let token = generate_jwt(
            JwtOptions::builder()
                .api_key_id("ed-key-id".to_string())
                .api_key_secret(ed_key)
                .request_method("POST".to_string())
                .request_host("api.cdp.coinbase.com".to_string())
                .request_path("/platform/v2/evm/accounts".to_string())
                .build(),
        )
        .unwrap();

        let header = decode_jwt_header(&token);
        assert_eq!(header["alg"], "EdDSA");
        assert_eq!(header["kid"], "ed-key-id");

        let claims = decode_jwt_claims(&token);
        assert_eq!(claims["sub"], "ed-key-id");
        assert_eq!(claims["iss"], "cdp");

        let uris = claims["uris"].as_array().expect("uris should be an array");
        assert_eq!(
            uris[0],
            "POST api.cdp.coinbase.com/platform/v2/evm/accounts"
        );
    }

    #[test]
    fn test_generate_jwt_websocket_no_uris() {
        let ec_key = generate_ec_pem_key();
        let token = generate_jwt(
            JwtOptions::builder()
                .api_key_id("ws-key-id".to_string())
                .api_key_secret(ec_key)
                .build(),
        )
        .unwrap();

        let claims = decode_jwt_claims(&token);
        assert_eq!(claims["sub"], "ws-key-id");
        assert_eq!(claims["iss"], "cdp");
        // uris should be absent for websocket JWTs
        assert!(claims.get("uris").is_none() || claims["uris"].is_null());
    }

    #[test]
    fn test_generate_jwt_partial_request_params_error() {
        let ec_key = generate_ec_pem_key();
        let result = generate_jwt(
            JwtOptions::builder()
                .api_key_id("test-key-id".to_string())
                .api_key_secret(ec_key)
                .request_method("GET".to_string())
                // missing host and path
                .build(),
        );

        assert!(result.is_err());
        if let Err(CdpError::Auth(msg)) = result {
            assert!(msg.contains("Either all request details"));
        } else {
            panic!("Expected Auth error for partial request params");
        }
    }

    #[test]
    fn test_generate_jwt_with_audience() {
        let ec_key = generate_ec_pem_key();
        let token = generate_jwt(
            JwtOptions::builder()
                .api_key_id("aud-key-id".to_string())
                .api_key_secret(ec_key)
                .audience(vec!["custom-audience".to_string()])
                .build(),
        )
        .unwrap();

        let claims = decode_jwt_claims(&token);
        let aud = claims["aud"].as_array().expect("aud should be an array");
        assert_eq!(aud.len(), 1);
        assert_eq!(aud[0], "custom-audience");
    }

    #[test]
    fn test_generate_jwt_default_expires_in() {
        let ec_key = generate_ec_pem_key();
        let token = generate_jwt(
            JwtOptions::builder()
                .api_key_id("default-exp-key".to_string())
                .api_key_secret(ec_key)
                .request_method("GET".to_string())
                .request_host("api.cdp.coinbase.com".to_string())
                .request_path("/test".to_string())
                .build(),
        )
        .unwrap();

        let claims = decode_jwt_claims(&token);
        let exp = claims["exp"].as_u64().unwrap();
        let iat = claims["iat"].as_u64().unwrap();
        assert_eq!(exp - iat, 120); // default 120 seconds
    }

    #[test]
    fn test_generate_jwt_custom_expires_in() {
        let ec_key = generate_ec_pem_key();
        let token = generate_jwt(
            JwtOptions::builder()
                .api_key_id("custom-exp-key".to_string())
                .api_key_secret(ec_key)
                .request_method("GET".to_string())
                .request_host("api.cdp.coinbase.com".to_string())
                .request_path("/test".to_string())
                .expires_in(300u64)
                .build(),
        )
        .unwrap();

        let claims = decode_jwt_claims(&token);
        let exp = claims["exp"].as_u64().unwrap();
        let iat = claims["iat"].as_u64().unwrap();
        assert_eq!(exp - iat, 300);
    }

    #[test]
    fn test_generate_jwt_invalid_key_format() {
        let result = generate_jwt(
            JwtOptions::builder()
                .api_key_id("bad-key-id".to_string())
                .api_key_secret("not-a-valid-key-format".to_string())
                .request_method("GET".to_string())
                .request_host("api.cdp.coinbase.com".to_string())
                .request_path("/test".to_string())
                .build(),
        );

        assert!(result.is_err());
        if let Err(CdpError::Auth(msg)) = result {
            assert!(msg.contains("Invalid key format"));
        } else {
            panic!("Expected Auth error for invalid key format");
        }
    }

    // --- WalletAuth::generate_jwt tests ---

    #[test]
    fn test_wallet_auth_generate_jwt_ec_key() {
        let ec_key = generate_ec_pem_key();
        let auth = WalletAuth::builder()
            .api_key_id("wa-ec-key-id".to_string())
            .api_key_secret(ec_key)
            .build()
            .unwrap();

        let token = auth
            .generate_jwt(
                "GET",
                "api.cdp.coinbase.com",
                "/platform/v2/evm/accounts",
                120,
            )
            .unwrap();

        let header = decode_jwt_header(&token);
        assert_eq!(header["alg"], "ES256");
        assert_eq!(header["kid"], "wa-ec-key-id");

        let claims = decode_jwt_claims(&token);
        assert_eq!(claims["sub"], "wa-ec-key-id");
        assert_eq!(claims["iss"], "cdp");

        let uris = claims["uris"].as_array().expect("uris should be an array");
        assert_eq!(uris[0], "GET api.cdp.coinbase.com/platform/v2/evm/accounts");
    }

    #[test]
    fn test_wallet_auth_generate_jwt_ed25519_key() {
        let ed_key = generate_ed25519_key_base64();
        let auth = WalletAuth::builder()
            .api_key_id("wa-ed-key-id".to_string())
            .api_key_secret(ed_key)
            .build()
            .unwrap();

        let token = auth
            .generate_jwt(
                "POST",
                "api.cdp.coinbase.com",
                "/platform/v2/evm/accounts",
                60,
            )
            .unwrap();

        let header = decode_jwt_header(&token);
        assert_eq!(header["alg"], "EdDSA");
        assert_eq!(header["kid"], "wa-ed-key-id");

        let claims = decode_jwt_claims(&token);
        assert_eq!(claims["sub"], "wa-ed-key-id");
        assert_eq!(claims["iss"], "cdp");

        let exp = claims["exp"].as_u64().unwrap();
        let iat = claims["iat"].as_u64().unwrap();
        assert_eq!(exp - iat, 60);
    }
}