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
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
//! Encrypt and decrypt bitcoin private keys with
//! [bip-0038](https://github.com/bitcoin/bips/blob/master/bip-0038.mediawiki) standard.
//!
//! This crate can handle bitcoin private keys as raw 32 bytes (`[u8; 32]`) and encoded in the
//! `wif` format.
//!
//! # Basic examples
//!
//! #### Encryption
//!
//! ```
//! use bip38::{Encrypt, EncryptWif, Error};
//!
//! // true => compress
//! assert_eq!(
//!     [0x11; 32].encrypt("strong_pass", true).unwrap(),
//!     "6PYMgbeR64ypE4g8ZQhGo7ScudV5BLz1vMFUCs49AWpW3jVNWfH6cAdTi2"
//! );
//! // false => uncompress
//! assert_eq!(
//!     [0x11; 32].encrypt("strong_pass", false).unwrap(),
//!     "6PRVo8whLAhpRwSM5tJfmbAbZ9mCxjyZExaTXt6EMSXw3f5QJxMDFQQND2"
//! );
//! // [0x00; 32] is an invalid private key and cannot generate a valid bitcoin address
//! assert_eq!([0x00; 32].encrypt("strong_pass", true), Err(Error::PrvKey));
//! assert_eq!([0x00; 32].encrypt("strong_pass", false), Err(Error::PrvKey));
//!
//! // wif
//! assert_eq!(
//!     "KwntMbt59tTsj8xqpqYqRRWufyjGunvhSyeMo3NTYpFYzZbXJ5Hp".encrypt_wif("strong_pass"),
//!     Ok(String::from("6PYMgbeR64ypE4g8ZQhGo7ScudV5BLz1vMFUCs49AWpW3jVNWfH6cAdTi2"))
//! );
//! assert_eq!(
//!     "5HwoXVkHoRM8sL2KmNRS217n1g8mPPBomrY7yehCuXC1115WWsh".encrypt_wif("strong_pass"),
//!     Ok(String::from("6PRVo8whLAhpRwSM5tJfmbAbZ9mCxjyZExaTXt6EMSXw3f5QJxMDFQQND2"))
//! );
//! ```
//!
//! #### Decryption
//!
//! ```
//! use bip38::{Decrypt, Error};
//!
//! assert_eq!(
//!     "6PYMgbeR64ypE4g8ZQhGo7ScudV5BLz1vMFUCs49AWpW3jVNWfH6cAdTi2".decrypt("strong_pass"),
//!     Ok(([0x11; 32], true)) // compress
//! );
//! assert_eq!(
//!     "6PRVo8whLAhpRwSM5tJfmbAbZ9mCxjyZExaTXt6EMSXw3f5QJxMDFQQND2".decrypt("strong_pass"),
//!     Ok(([0x11; 32], false)) // uncompress
//! );
//! assert_eq!(
//!     "6PRVo8whLAhpRwSM5tJfmbAbZ9mCxjyZExaTXt6EMSXw3f5QJxMDFQQND2".decrypt("wrong_pass"),
//!     Err(Error::Pass)
//! );
//!
//! // wif
//! assert_eq!(
//!     "6PYMgbeR64ypE4g8ZQhGo7ScudV5BLz1vMFUCs49AWpW3jVNWfH6cAdTi2"
//!         .decrypt_to_wif("strong_pass"),
//!     Ok(String::from("KwntMbt59tTsj8xqpqYqRRWufyjGunvhSyeMo3NTYpFYzZbXJ5Hp"))
//! );
//! assert_eq!(
//!     "6PRVo8whLAhpRwSM5tJfmbAbZ9mCxjyZExaTXt6EMSXw3f5QJxMDFQQND2"
//!         .decrypt_to_wif("strong_pass"),
//!     Ok(String::from("5HwoXVkHoRM8sL2KmNRS217n1g8mPPBomrY7yehCuXC1115WWsh"))
//! );
//! ```
//!
//! #### Generation (elliptic curve multiplication, not deterministic)
//!
//! ```
//! use bip38::{Decrypt, Generate};
//!
//! // true => compress
//! assert!("passphrase".generate(true).unwrap().starts_with("6Pn"));
//!
//! // false => uncompress
//! assert!("passphrase".generate(false).unwrap().starts_with("6Pf"));
//!
//! // ぽー
//! assert!("バンドメイド".generate(true).unwrap().decrypt("バンドメイド").is_ok());
//! ```
//!
//! # Boolean flag
//!
//! * `true` always signify: use the public key of this private key `compressed` (33 bytes).
//! * `false` always signify: use the public key of this private key `uncompressed` (65 bytes).
//!
//! Obs: the use of uncompressed public keys is deprecated and discouraged. For new private keys
//! always choose the `true` flag.
//!
//! # Normalization
//!
//! This crate handle the normalization (`nfc`) of the passphrase as specified on `bip-0038`.
//!
//! ```
//! use bip38::{Decrypt, Encrypt};
//!
//! assert_eq!(
//!     [0xba; 32].encrypt("ΜΟΛΩΝ ΛΑΒΕ", true).unwrap().decrypt("ΜΟΛΩΝ ΛΑΒΕ").unwrap(),
//!     ([0xba; 32], true)
//! );
//! ```
//!
//! # Testing
//!
//! Please always run `cargo test` with `--release` flag. Without the optimizations of a release
//! build running tests can consume long time (the encryption algorithm is, by design, heavy on
//! cpu).
//!
//! # Usage
//!
//! You can use this crate in your project by adding the following to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! bip38 = "1.1.0"
//! ```
//!
//! #### Decrypting
//!
//! ```
//! use bip38::Decrypt;
//!
//! let user_ekey = String::from("6PnVMRLWZnQQGjLJPnzGnBM2hBwvT8padAsHToFXwhZBFQF1e6nckKXFG9");
//! let user_pass = String::from("ultra_secret_pass");
//!
//! let (private_key, compress) = user_ekey.decrypt(&user_pass).unwrap_or_else(|err| {
//!     eprintln!("{}", err); // in case of invalid passphrase or invalid encrypted private key
//!     std::process::exit(1);
//! });
//! let wif = user_ekey.decrypt_to_wif(&user_pass).unwrap_or_else(|err| {
//!     eprintln!("{}", err);
//!     std::process::exit(2);
//! });
//! ```
//!
//! #### Encrypting
//!
//! ```
//! use bip38::{Encrypt, EncryptWif};
//!
//! let informed_wif_key = "L4DczGWRanBGXnun83Fs9HcPCaXXq7ngxZrBY13Phdsw36WU1rQA";
//! let internal_prv_key = [0xd0; 32];
//! let user_pass = String::from("not_good_pass");
//!
//! let eprvk_from_raw = internal_prv_key.encrypt(&user_pass, true).unwrap_or_else(|err| {
//!     eprintln!("{}", err); // if the private key could not generate a valid bitcoin address
//!     std::process::exit(1);
//! });
//! let eprvk_from_wif = informed_wif_key.encrypt_wif(&user_pass).unwrap_or_else(|err| {
//!     eprintln!("{}", err); // in case of invalid wif/decoded private key
//!     std::process::exit(2);
//! });
//! assert_eq!(eprvk_from_raw, eprvk_from_wif);
//! ```
//!
//! #### Generating (elliptic curve multiplication)
//!
//! ```
//! use bip38::Generate;
//!
//! let user_pass = String::from("a_good_pass_please");
//!
//! let encrypted_prv_key = user_pass.generate(false).unwrap_or_else(|err| {
//!     eprintln!("{}", err); // if the private key could not generate an address (a rare case)
//!     std::process::exit(1);
//! });
//! ```

use aes::Aes256;
use aes::cipher::{
    BlockDecrypt,
    BlockEncrypt,
    generic_array::GenericArray,
    NewBlockCipher
};
use rand::RngCore;
use ripemd160::Ripemd160;
use scrypt::Params;
use secp256k1::{Secp256k1, SecretKey, PublicKey};
use sha2::Digest;
use unicode_normalization::UnicodeNormalization;

/// Number of base58 characters on every encrypted private key.
const LEN_EKEY: usize = 58;

/// Number of base58 characters in a wif compressed secret key.
const LEN_WIFC: usize = 52;

/// Number of base58 characters in a wif uncompressed secret key.
const LEN_WIFU: usize = 51;

/// Number of bytes of a public key compressed.
const NBBY_PUBC: usize = 33;

/// Number of bytes of a public key uncompressed.
const NBBY_PUBU: usize = 65;

/// Number of bytes (payload only) contained in a decoded wif compressed key.
const NBBY_WIFC: usize = 34;

/// Number of bytes (payload only) contained in a decoded wif uncompressed key.
const NBBY_WIFU: usize = 33;

/// Prefix of all ec encrypted keys.
const PRE_EC: [u8; 2] = [0x01, 0x43];

/// Prefix of all private keys encrypted with bip-0038 standard.
const PRE_EKEY: &str = "6P";

/// Prefix of all non ec encrypted keys.
const PRE_NON_EC: [u8; 2] = [0x01, 0x42];

/// First two possible characters of a wif compressed secret key.
const PRE_WIFC: &str = "KL";

/// First byte of all wif encoded secret keys.
const PRE_WIFB: u8 = 0x80;

/// First character of a wif uncompressed secret key.
const PRE_WIFU: &str = "5";

/// Error variants of `bip38` crate.
///
/// The only errors that are intended to be handle are:
///
/// `Base58`, `Checksum`, `EncKey`, `Pass`, `PrvKey`, `WifKey`.
///
/// All others exist for safety in case of something unexpected happens with dependencies.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd)]
pub enum Error {
    /// If an invalid base 58 string is processed.
    Base58,
    /// Invalid checksum was found.
    Checksum,
    /// Invalid result of elliptic curve multiplication.
    EcMul,
    /// Found invalid encrypted private key.
    EncKey,
    /// Invalid number of public key bytes.
    NbPubB,
    /// Found invalid passphrase.
    Pass,
    /// Invalid private key found (could not generate address).
    PrvKey,
    /// Found invalid public key.
    PubKey,
    /// Trowed if an error occurs when using `scrypt` function.
    ScryptFn,
    /// Trowed if an invalid `scrypt` parameter is used.
    ScryptParam,
    /// Invalid private key represented in `wif` format.
    WifKey,
}

/// Internal Functions to manipulate an arbitrary number of bytes [u8].
trait BytesManipulation {
    /// Encode informed data in base 58 check.
    fn encode_base58ck(&self) -> String;

    /// Sha256 and ripemd160 in sequence.
    fn hash160(&self) -> [u8; 20];

    /// Receives bytes and return 32 bytes of a dual sha256 hash.
    fn hash256(&self) -> [u8; 32];

    /// Create an p2wpkh address according length bytes of the public key.
    fn p2wpkh(&self) -> Result<String, Error>;
}

/// Allow decryption of bitcoin encrypted private keys in `srt` format.
pub trait Decrypt {
    /// Decrypt an encrypted bitcoin private key in `str`format (both non-ec and ec).
    ///
    /// This function targets strings of 58 base58 characters with the version prefix `6P` and
    /// returns a tuple containing the decrypted private key (`[u8; 32]`) and a boolean indication
    /// of if this private key is intended to result in a compressed public key or not. So, if the
    /// flag is `true`, create an compressed public key (33 bytes), in case of `false`, use the
    /// full 65 bytes of the public key.
    ///
    /// # Examples
    ///
    ///
    /// ```
    /// use bip38::Decrypt;
    ///
    /// // decryption of non elliptic curve multiplication
    /// assert_eq!(
    ///     "6PYMgbeR6XCsX4yJx8E52vW4PJDoTiu1QeFLn81KoW6Shye5DZ4ZnDauno".decrypt("weakPass"),
    ///     Ok(([0x11; 32], true)) // indication to compress the public key of this private key
    /// );
    /// assert_eq!(
    ///     "6PRVo8whL3QbdrXpKk3gP2dGuxDbuvMsMqUq2imVigrm8oyRbvBoRUsbB3".decrypt("weakPass"),
    ///     Ok(([0x11; 32], false)) // indication do not compress the public key
    /// );
    ///
    /// // decryption of elliptic curve multiplication
    /// assert!(
    ///     "6PnPQGcDuPhCMmXzTebiryx8zHxr8PZvUJccSxarn9nLHVLX7yVj6Wcoj9".decrypt("weakPass").is_ok()
    /// );
    /// assert!(
    ///     "6PfVV4eYCodt6tRiHbHH356MX818xZvcN54oNd1rCr8Cbme3273xWAgBhx".decrypt("notWeak?").is_ok()
    /// );
    /// ```
    ///
    /// # Errors
    ///
    /// * `Error::Pass` is returned if an invalid passphrase is inserted.
    ///
    /// * `Error::EncKey` is returned if the target `str` is not an valid encrypted private key.
    ///
    /// * `Error::Checksum` is returned if the target `str` has valid encrypted private key format
    /// but invalid checksum.
    ///
    /// * `Error::Base58` is returned if an non `base58` character is found.
    ///
    /// ```
    /// use bip38::{Decrypt, Error};
    ///
    /// assert!(
    ///     "6PRNFFkZc2NZ6dJqFfhRoFNMR9Lnyj7dYGrzdgXXVMXcxoKTePPX1dWByq".decrypt("Satoshi").is_ok()
    /// );
    /// assert_eq!(
    ///     "6PRNFFkZc2NZ6dJqFfhRoFNMR9Lnyj7dYGrzdgXXVMXcxoKTePPX1dWByq".decrypt("Nakamoto"),
    ///     Err(Error::Pass)
    /// );
    /// assert_eq!(
    ///     "6PRNFFkZc2NZ6dJqFfhRoFNMR9Lnyj7dYGrzdgXXVMXcxoKTePPX1dWByQ".decrypt("Satoshi"), // ← Q
    ///     Err(Error::Checksum)
    /// );
    /// assert_eq!(
    ///     "6PRNFFkZc2NZ6dJqFfhRoFNMR9Lnyj7dYGrzdgXXVMXcxoKTePPX1dWBy".decrypt("Satoshi"), // ← q?
    ///     Err(Error::EncKey)
    /// );
    /// assert_eq!(
    ///     "6PRNFFkZc2NZ6dJqFfhRoFNMR9Lnyj7dYGrzdgXXVMXcxoKTePPX1dWBy!".decrypt("Satoshi"), // ← !
    ///     Err(Error::Base58)
    /// );
    /// ```
    ///
    /// # Passphrase
    ///
    /// This function handle the normalization (`nfc`) of the passphrase as specified on
    /// `bip-0038`.
    ///
    /// ```
    /// use bip38::Decrypt;
    ///
    /// assert!(
    ///     "6PRW5o9FLp4gJDDVqJQKJFTpMvdsSGJxMYHtHaQBF3ooa8mwD69bapcDQn"
    ///         .decrypt("\u{03d2}\u{0301}\u{0000}\u{010400}\u{01f4a9}").is_ok()
    /// );
    /// ```
    fn decrypt(&self, pass: &str) -> Result<([u8; 32], bool), Error>;

    /// Decrypt an encrypted bitcoin private key in `str`format (both non-ec and ec), resulting on
    /// a `wif` private key.
    ///
    /// This function targets strings of 58 base58 characters with the version prefix `6P` and
    /// returns a `String` of base58 characters representing the decrypted private key in the `wif`
    /// format.
    ///
    /// # Examples
    ///
    ///
    /// ```
    /// use bip38::Decrypt;
    ///
    /// // decryption of non elliptic curve multiplication
    /// assert_eq!(
    ///     "6PYMgbeR6XCsX4yJx8E52vW4PJDoTiu1QeFLn81KoW6Shye5DZ4ZnDauno".decrypt_to_wif("weakPass"),
    ///     Ok(String::from("KwntMbt59tTsj8xqpqYqRRWufyjGunvhSyeMo3NTYpFYzZbXJ5Hp"))
    /// );
    /// assert_eq!(
    ///     "6PRVo8whL3QbdrXpKk3gP2dGuxDbuvMsMqUq2imVigrm8oyRbvBoRUsbB3".decrypt_to_wif("weakPass"),
    ///     Ok(String::from("5HwoXVkHoRM8sL2KmNRS217n1g8mPPBomrY7yehCuXC1115WWsh"))
    /// );
    ///
    /// // decryption of elliptic curve multiplication
    /// assert_eq!(
    ///     "6PnPQGcDuPhCMmXzTebiryx8zHxr8PZvUJccSxarn9nLHVLX7yVj6Wcoj9".decrypt_to_wif("weakPass"),
    ///     Ok(String::from("Kyo7rXp5Qygn5qUFS39wR9DsxfrznTUc8XJeaHVSWhkVnhC4NVWE"))
    /// );
    /// assert_eq!(
    ///     "6PfVV4eYCodt6tRiHbHH356MX818xZvcN54oNd1rCr8Cbme3273xWAgBhx".decrypt_to_wif("notWeak?"),
    ///     Ok(String::from("5JPeaPgoWj6R9CEnSrvmGJh36e3cxRpGGpJ3mzTeK6M88Hc3Ttm"))
    /// );
    /// ```
    ///
    /// # Errors
    ///
    /// * `Error::Pass` is returned if an invalid passphrase is inserted.
    ///
    /// * `Error::EncKey` is returned if the target `str` is not an valid encrypted private key.
    ///
    /// * `Error::Checksum` is returned if the target `str` has valid encrypted private key format
    /// but invalid checksum.
    ///
    /// * `Error::Base58` is returned if an non `base58` character is found.
    ///
    /// ```
    /// use bip38::{Decrypt, Error};
    ///
    /// assert_eq!(
    ///     "6PRNFFkZc2NZ6dJqFfhRoFNMR9Lnyj7dYGrzdgXXVMXcxoKTePPX1dWByq".decrypt_to_wif("Satoshi"),
    ///     Ok(String::from("5HtasZ6ofTHP6HCwTqTkLDuLQisYPah7aUnSKfC7h4hMUVw2gi5"))
    /// );
    /// assert_eq!(
    ///     "6PRNFFkZc2NZ6dJqFfhRoFNMR9Lnyj7dYGrzdgXXVMXcxoKTePPX1dWByq".decrypt_to_wif("Nakamoto"),
    ///     Err(Error::Pass)
    /// );
    /// assert_eq!( // Q
    ///     "6PRNFFkZc2NZ6dJqFfhRoFNMR9Lnyj7dYGrzdgXXVMXcxoKTePPX1dWByQ".decrypt_to_wif("Satoshi"),
    ///     Err(Error::Checksum)
    /// );
    /// assert_eq!( // q?
    ///     "6PRNFFkZc2NZ6dJqFfhRoFNMR9Lnyj7dYGrzdgXXVMXcxoKTePPX1dWBy".decrypt_to_wif("Satoshi"),
    ///     Err(Error::EncKey)
    /// );
    /// assert_eq!( // !
    ///     "6PRNFFkZc2NZ6dJqFfhRoFNMR9Lnyj7dYGrzdgXXVMXcxoKTePPX1dWBy!".decrypt_to_wif("Satoshi"),
    ///     Err(Error::Base58)
    /// );
    /// ```
    ///
    /// # Passphrase
    ///
    /// This function handle the normalization (`nfc`) of the passphrase as specified on
    /// `bip-0038`.
    ///
    /// ```
    /// use bip38::Decrypt;
    ///
    /// assert_eq!(
    ///     "6PRW5o9FLp4gJDDVqJQKJFTpMvdsSGJxMYHtHaQBF3ooa8mwD69bapcDQn"
    ///         .decrypt_to_wif("\u{03d2}\u{0301}\u{0000}\u{010400}\u{01f4a9}"),
    ///     Ok(String::from("5Jajm8eQ22H3pGWLEVCXyvND8dQZhiQhoLJNKjYXk9roUFTMSZ4"))
    /// );
    /// ```
    fn decrypt_to_wif(&self, pass: &str) -> Result<String, Error>;
}

/// Allow encryption of bitcoin private keys in `[u8; 32]` format.
pub trait Encrypt {
    /// Encrypt a bitcoin private key in the format of `[u8; 32]` (without elliptic curve
    /// multiplication) into a `String` of 58 base58 characters.
    ///
    /// When decrypting the boolean flag `compress` is just an indication, but here it influences
    /// on the resulting prefix of the encrypted private key and obviously on the indication when
    /// decrypting, but not in the private key itself.
    ///
    /// # Examples
    ///
    /// ```
    /// use bip38::Encrypt;
    ///
    /// assert_eq!(
    ///     [0x11; 32].encrypt("weakPass", true).unwrap(),
    ///     "6PYMgbeR6XCsX4yJx8E52vW4PJDoTiu1QeFLn81KoW6Shye5DZ4ZnDauno"
    /// );
    /// assert_eq!(
    ///     [0x11; 32].encrypt("weakPass", false).unwrap(),
    ///     "6PRVo8whL3QbdrXpKk3gP2dGuxDbuvMsMqUq2imVigrm8oyRbvBoRUsbB3"
    /// );
    /// ```
    ///
    /// # Errors
    ///
    /// The only case this function can fail by itself is if the provided private key could not
    /// result in a bitcoin address. All other errors are here for safety and are related to
    /// dependencies. This function don't `unwrap` internally to let the decision to do or not to
    /// the developer using the crate.
    ///
    /// ```
    /// use bip38::{Encrypt, Error};
    ///
    /// assert_eq!([0x00; 32].encrypt("oh_no!", true), Err(Error::PrvKey));
    /// assert_eq!([0xff; 32].encrypt("oh_no!", true), Err(Error::PrvKey));
    /// ```
    ///
    /// # Passphrase
    ///
    /// This function handle the normalization (`nfc`) of the passphrase as specified on
    /// `bip-0038`.
    /// ```
    /// use bip38::Encrypt;
    ///
    /// assert_eq!(
    ///     [
    ///         0x64, 0xee, 0xab, 0x5f, 0x9b, 0xe2, 0xa0, 0x1a, 0x83, 0x65, 0xa5, 0x79, 0x51, 0x1e,
    ///         0xb3, 0x37, 0x3c, 0x87, 0xc4, 0x0d, 0xa6, 0xd2, 0xa2, 0x5f, 0x05, 0xbd, 0xa6, 0x8f,
    ///         0xe0, 0x77, 0xb6, 0x6e
    ///     ].encrypt("\u{03d2}\u{0301}\u{0000}\u{010400}\u{01f4a9}", false),
    ///     Ok(String::from("6PRW5o9FLp4gJDDVqJQKJFTpMvdsSGJxMYHtHaQBF3ooa8mwD69bapcDQn"))
    /// );
    /// ```
    fn encrypt(&self, pass: &str, compress: bool) -> Result<String, Error>;
}

/// Allow encryption of bitcoin private keys in the `wif` format.
pub trait EncryptWif {
    /// Encrypt a bitcoin private key in the `wif` format (without elliptic curve multiplication)
    /// into a `String` of 58 base58 characters according to the `wif` indication of a compressed
    /// or uncompressed future public key (the prefix of the `wif` affects the prefix of the
    /// encrypted private key).
    ///
    /// # Examples
    ///
    /// ```
    /// use bip38::EncryptWif;
    ///
    /// assert_eq!(
    ///     "KwntMbt59tTsj8xqpqYqRRWufyjGunvhSyeMo3NTYpFYzZbXJ5Hp".encrypt_wif("weakPass"),
    ///     Ok(String::from("6PYMgbeR6XCsX4yJx8E52vW4PJDoTiu1QeFLn81KoW6Shye5DZ4ZnDauno"))
    /// );
    /// assert_eq!(
    ///     "5HwoXVkHoRM8sL2KmNRS217n1g8mPPBomrY7yehCuXC1115WWsh".encrypt_wif("weakPass"),
    ///     Ok(String::from("6PRVo8whL3QbdrXpKk3gP2dGuxDbuvMsMqUq2imVigrm8oyRbvBoRUsbB3"))
    /// );
    /// ```
    ///
    /// # Errors
    ///
    /// This function can fail due to decoding process of the target `wif` private key and if the
    /// decoded private key can't result in a bitcoin address.
    ///
    /// * `Error::Base58` is returned if an non `base58` character is found.
    ///
    /// * `Error::Checksum` is returned if the target `str` has valid `wif` format but invalid
    /// checksum.
    ///
    /// * `Error::PrvKey` is returned if the decoded private key could not generate a bitcoin
    /// address
    ///
    /// * `Error::WifKey` is returned if the target `str` is not an valid `wif` private key.
    ///
    ///
    /// ```
    /// use bip38::{EncryptWif, Error};
    ///
    /// assert_eq!(
    ///     "5HtasZ6ofTHP6HCwTqTkLDuLQisYPah7aUnSKfC7h4hMUVw2gi5".encrypt_wif("Satoshi"),
    ///     Ok(String::from("6PRNFFkZc2NZ6dJqFfhRoFNMR9Lnyj7dYGrzdgXXVMXcxoKTePPX1dWByq"))
    /// );
    /// assert_eq!(
    ///     "5HtasZ6ofTHP6HCwTqTkLDuLQisYPah7aUnSKfC7h4hMUVw2gi!".encrypt_wif("Satoshi"), // !
    ///     Err(Error::Base58)
    /// );
    /// assert_eq!(
    ///     "5HtasZ6ofTHP6HCwTqTkLDuLQisYPah7aUnSKfC7h4hMUVw2gi6".encrypt_wif("Satoshi"), // 6
    ///     Err(Error::Checksum)
    /// );
    /// assert_eq!(
    ///     "5HtasZ6ofTHP6HCwTqTkLDuLQisYPah7aUnSKfC7h4hMUVw2gi55".encrypt_wif("Satoshi"), // 55
    ///     Err(Error::WifKey)
    /// );
    /// assert_eq!( // the payload of this wif is [0x00; 32]
    ///     "KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73NUBByJr".encrypt_wif("Satoshi"),
    ///     Err(Error::PrvKey)
    /// );
    /// ```
    ///
    /// # Passphrase
    ///
    /// This function handle the normalization (`nfc`) of the passphrase as specified on
    /// `bip-0038`.
    /// ```
    /// use bip38::EncryptWif;
    ///
    /// assert_eq!(
    ///     "5Jajm8eQ22H3pGWLEVCXyvND8dQZhiQhoLJNKjYXk9roUFTMSZ4"
    ///         .encrypt_wif("\u{03d2}\u{0301}\u{0000}\u{010400}\u{01f4a9}"),
    ///     Ok(String::from("6PRW5o9FLp4gJDDVqJQKJFTpMvdsSGJxMYHtHaQBF3ooa8mwD69bapcDQn"))
    /// );
    /// ```
    fn encrypt_wif(&self, pass: &str) -> Result<String, Error>;
}

/// Allow generation of encrypted private keys using elliptic curve multiplication.
pub trait Generate {
    /// Create an encrypted private key in the form of a `String` of 58 base58 characters based on
    /// a passphrase (using elliptic curve multiplication and pseudo-random number generation).
    ///
    /// This function don't receives a private key, it's generated internally as specified in
    /// `bip-0038`. The target string is the passphrase to be used to decrypt. The resulting
    /// private key is only know if the encrypted private key is decrypted. So the result is, by
    /// design, not deterministic.
    ///
    /// When decrypting the boolean flag `compress` is just an indication, but here it influences
    /// on the resulting prefix of the encrypted private key and obviously on the indication when
    /// decrypting, but not in the private key itself.
    ///
    /// # Examples
    ///
    /// ```
    /// use bip38::{Decrypt, Generate};
    ///
    /// // true => compress
    /// assert!("hopefully_a_strong_passphrase".generate(true).unwrap().starts_with("6Pn"));
    ///
    /// // false => uncompress
    /// assert!("hopefully_a_strong_passphrase".generate(false).unwrap().starts_with("6Pf"));
    ///
    /// assert!("バンドメイド".generate(true).unwrap().decrypt("バンドメイド").is_ok());
    /// assert!("くるっぽー!".generate(false).unwrap().decrypt("くるっぽー!").is_ok());
    /// ```
    ///
    /// # Errors
    ///
    /// The only case this function can fail by itself is if the generated private key could not
    /// result in a bitcoin address. In this case the function results in `Error::PrvKey`. All
    /// other errors are here for safety and are related to dependencies. This function don't
    /// `unwrap` internally to let the decision to do or not to the developer using the crate.
    ///
    /// # Passphrase
    ///
    /// This function handle the normalization (`nfc`) of the passphrase as specified on
    /// `bip-0038`.
    ///
    /// ```
    /// use bip38::{Decrypt, Generate};
    ///
    /// assert!(
    ///     "\u{03d2}\u{0301}\u{0000}\u{010400}\u{01f4a9}".generate(true).unwrap()
    ///         .decrypt("\u{03d2}\u{0301}\u{0000}\u{010400}\u{01f4a9}").is_ok()
    /// );
    /// ```
    fn generate(&self, compress: bool) -> Result<String, Error>;
}

/// Internal trait to manipulate private keys (32 bytes).
trait PrivateKeyManipulation {
    /// Generate secp256k1 point based on target secret key.
    fn public(&self, compress: bool) -> Result<Vec<u8>, Error>;

    /// Generate a representation of a secret key in wif format.
    fn wif(&self, compress: bool) -> String;
}

/// Internal Functions to manipulate strings.
trait StringManipulation {
    /// Decode informed base 58 string into bytes (payload only).
    fn decode_base58ck(&self) -> Result<Vec<u8>, Error>;

    /// Decode a secret key encoded in base58 returning bytes and compression.
    fn decode_wif(&self) -> Result<([u8; 32], bool), Error>;

    /// Decrypt encrypted private key with ec multiply mode.
    fn decrypt_ec(&self, pass: &str) -> Result<([u8; 32], bool), Error>;

    /// Decrypt a non-ec encrypted private key.
    fn decrypt_non_ec(&self, pass: &str) -> Result<([u8; 32], bool), Error>;
}

impl core::fmt::Display for Error {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        match self {
            Error::Base58 => write!(f, "invalid base58 string"),
            Error::Checksum => write!(f, "invalid checksum"),
            Error::EcMul => write!(f, "invalid elliptic curve multiplication"),
            Error::EncKey => write!(f, "invalid encrypted private key"),
            Error::NbPubB => write!(f, "invalid number of public key bytes"),
            Error::Pass => write!(f, "invalid passphrase"),
            Error::PrvKey => write!(f, "invalid private key"),
            Error::PubKey => write!(f, "invalid public key"),
            Error::ScryptFn => write!(f, "failure on scrypt function"),
            Error::ScryptParam => write!(f, "invalid scrypt parameter"),
            Error::WifKey => write!(f, "invalid wif private key")
        }
    }
}

impl BytesManipulation for [u8] {
    #[inline]
    fn encode_base58ck(&self) -> String {
        let mut decoded = self.to_vec();
        decoded.append(&mut decoded.hash256()[..4].to_vec());
        bs58::encode(decoded).into_string()
    }

    #[inline]
    fn hash160(&self) -> [u8; 20] {
        let mut result = [0x00; 20];
        result[..].copy_from_slice(&Ripemd160::digest(&sha2::Sha256::digest(self)));
        result
    }

    #[inline]
    fn hash256(&self) -> [u8; 32] {
        let mut result = [0x00; 32];
        result[..].copy_from_slice(&sha2::Sha256::digest(&sha2::Sha256::digest(self)));
        result
    }

    #[inline]
    fn p2wpkh(&self) -> Result<String, Error> {
        if self.len() != NBBY_PUBC && self.len() != NBBY_PUBU { return Err(Error::NbPubB); }
        let mut address_bytes = vec![0x00];
        address_bytes.append(&mut self.hash160().to_vec());
        Ok(address_bytes.encode_base58ck())
    }
}

impl Decrypt for str {
    #[inline]
    fn decrypt(&self, pass: &str) -> Result<([u8; 32], bool), Error> {
        Ok(
            if self.len() != LEN_EKEY || (self.is_char_boundary(2) && &self[..2] != PRE_EKEY) {
                return Err(Error::EncKey);
            } else if self.decode_base58ck()?[..2] == PRE_NON_EC {
                self.decrypt_non_ec(pass)?
            } else if self.decode_base58ck()?[..2] == PRE_EC {
                self.decrypt_ec(pass)?
            } else {
                return Err(Error::EncKey);
            }
        )
    }

    #[inline]
    fn decrypt_to_wif(&self, pass: &str) -> Result<String, Error> {
        let raw = self.decrypt(pass)?;
        let wif = raw.0.wif(raw.1);
        Ok(wif)
    }
}

impl EncryptWif for str {
    #[inline]
    fn encrypt_wif(&self, pass: &str) -> Result<String, Error> {
        let raw_prvk = self.decode_wif()?;
        let eprvk = raw_prvk.0.encrypt(pass, raw_prvk.1)?;
        Ok(eprvk)
    }
}

impl Encrypt for [u8; 32] {
    #[inline]
    fn encrypt(&self, pass: &str, compress: bool) -> Result<String, Error> {
        let address = self.public(compress)?.p2wpkh()?;
        let checksum = &address.as_bytes().hash256()[..4];
        let mut scrypt_key = [0x00; 64];

        scrypt::scrypt(
            pass.nfc().collect::<String>().as_bytes(),
            checksum,
            &Params::new(14, 8, 8).map_err(|_| Error::ScryptParam)?,
            &mut scrypt_key
        ).map_err(|_| Error::ScryptFn)?;

        let mut half1 = [0x00; 32];
        half1[..].copy_from_slice(&scrypt_key[..32]);

        let cipher = Aes256::new(GenericArray::from_slice(&scrypt_key[32..]));

        for idx in 0..32 {
            half1[idx] ^= self[idx];
        }

        let mut part1 = GenericArray::clone_from_slice(&half1[..16]);
        let mut part2 = GenericArray::clone_from_slice(&half1[16..]);

        cipher.encrypt_block(&mut part1);
        cipher.encrypt_block(&mut part2);

        let mut buffer = [0x00; 39];
        buffer[..2].copy_from_slice(&PRE_NON_EC);
        buffer[2] = if compress { 0xe0 } else { 0xc0 };
        buffer[3..7].copy_from_slice(checksum);
        buffer[7..23].copy_from_slice(&part1);
        buffer[23..].copy_from_slice(&part2);

        Ok(buffer.encode_base58ck())
    }
}

impl Generate for str {
    #[inline]
    fn generate(&self, compress: bool) -> Result<String, Error> {
        let mut owner_salt = [0x00; 8];
        let mut pass_factor = [0x00; 32];
        let mut seed_b = [0x00; 24];

        rand::thread_rng().fill_bytes(&mut owner_salt);

        scrypt::scrypt(
            self.nfc().collect::<String>().as_bytes(),
            &owner_salt,
            &Params::new(14, 8, 8).map_err(|_| Error::ScryptParam)?,
            &mut pass_factor
        ).map_err(|_| Error::ScryptFn)?;

        let pass_point = pass_factor.public(true)?;

        let mut pass_point_mul = PublicKey::from_slice(&pass_point).map_err(|_| Error::PubKey)?;

        rand::thread_rng().fill_bytes(&mut seed_b);

        let factor_b = seed_b.hash256();

        pass_point_mul.mul_assign(&Secp256k1::new(), &factor_b).map_err(|_| Error::EcMul)?;

        let pubk = if compress {
            pass_point_mul.serialize().to_vec()
        } else {
            pass_point_mul.serialize_uncompressed().to_vec()
        };

        let address = pubk.p2wpkh()?;
        let address_hash = &address.as_bytes().hash256()[..4];
        let mut salt = [0x00; 12];
        let mut seed_b_pass = [0x00; 64];

        salt[..4].copy_from_slice(address_hash);
        salt[4..].copy_from_slice(&owner_salt);

        scrypt::scrypt(
            &pass_point,
            &salt,
            &Params::new(10, 1, 1).map_err(|_| Error::ScryptParam)?,
            &mut seed_b_pass
        ).map_err(|_| Error::ScryptFn)?;

        let derived_half1 = &seed_b_pass[..32];
        let derived_half2 = &seed_b_pass[32..];
        let en_p1 = &mut seed_b[..16];

        for idx in 0..16 {
            en_p1[idx] ^= derived_half1[idx];
        }

        let cipher = Aes256::new(GenericArray::from_slice(derived_half2));
        let mut encrypted_part1 = GenericArray::clone_from_slice(en_p1);

        cipher.encrypt_block(&mut encrypted_part1);

        let mut en_p2 = [0x00; 16];
        en_p2[..8].copy_from_slice(&encrypted_part1[8..]);
        en_p2[8..].copy_from_slice(&seed_b[16..]);

        for idx in 0..16 {
            en_p2[idx] ^= derived_half1[idx + 16];
        }

        let mut encrypted_part2 = GenericArray::clone_from_slice(&en_p2);

        cipher.encrypt_block(&mut encrypted_part2);

        let flag = if compress { 0x20 } else { 0x00 };

        let mut result_bytes = [0x00; 39];
        result_bytes[..2].copy_from_slice(&PRE_EC);
        result_bytes[2] = flag;
        result_bytes[3..7].copy_from_slice(address_hash);
        result_bytes[7..15].copy_from_slice(&owner_salt);
        result_bytes[15..23].copy_from_slice(&encrypted_part1[..8]);
        result_bytes[23..].copy_from_slice(&encrypted_part2);

        Ok(result_bytes.encode_base58ck())
    }
}

impl PrivateKeyManipulation for [u8; 32] {
    #[inline]
    fn public(&self, compress: bool) -> Result<Vec<u8>, Error> {
        let secp_pub = PublicKey::from_secret_key(
            &Secp256k1::new(),
            &SecretKey::from_slice(self).map_err(|_| Error::PrvKey)?
        );

        if compress {
            Ok(secp_pub.serialize().to_vec())
        } else {
            Ok(secp_pub.serialize_uncompressed().to_vec())
        }
    }

    #[inline]
    fn wif(&self, compress: bool) -> String {
        let mut decoded: Vec<u8> = vec![PRE_WIFB];
        decoded.append(&mut self.to_vec());
        if compress { decoded.push(0x01); }
        decoded.encode_base58ck()
    }
}

impl StringManipulation for str {
    #[inline]
    fn decode_base58ck(&self) -> Result<Vec<u8>, Error> {
        let raw = bs58::decode(self).into_vec().map_err(|_| Error::Base58)?;
        if raw[raw.len() - 4..] == raw[..raw.len() - 4].hash256()[..4] {
            Ok(raw[..(raw.len() - 4)].to_vec())
        } else {
            Err(Error::Checksum)
        }
    }

    #[inline]
    fn decode_wif(&self) -> Result<([u8; 32], bool), Error> {
        if (!self.is_char_boundary(1) || !PRE_WIFC.contains(&self[..1]) ||
            self.len() != LEN_WIFC) && (!self.starts_with(PRE_WIFU) || self.len() != LEN_WIFU) {
            return Err(Error::WifKey);
        }
        let raw_bytes = self.decode_base58ck()?;
        if (raw_bytes.len() != NBBY_WIFC && raw_bytes.len() != NBBY_WIFU) ||
            raw_bytes[0] != PRE_WIFB {
            return Err(Error::WifKey)
        }
        let mut result = [0x00; 32];
        result[..].copy_from_slice(&raw_bytes[1..33]);
        Ok((result, raw_bytes.len() == NBBY_WIFC))
    }

    #[inline]
    fn decrypt_ec(&self, pass: &str) -> Result<([u8; 32], bool), Error> {
        let eprvk = self.decode_base58ck()?;
        if eprvk[..2] != PRE_EC { return Err(Error::EncKey); }
        let address_hash = &eprvk[3..7];
        let encrypted_p1 = &eprvk[15..23];
        let encrypted_p2 = &eprvk[23..39];
        let flag_byte: u8 = eprvk[2];
        let compress = (flag_byte & 0x20) == 0x20;
        let has_lot = (flag_byte & 0x04) == 0x04;
        let owner_entropy = &eprvk[7..15];
        let owner_salt = &eprvk[7..15 - (flag_byte & 0x04) as usize];
        let mut pre_factor = [0x00; 32];
        let mut pass_factor = [0x00; 32];

        scrypt::scrypt(
            pass.nfc().collect::<String>().as_bytes(),
            owner_salt,
            &Params::new(14, 8, 8).map_err(|_| Error::ScryptParam)?,
            &mut pre_factor
        ).map_err(|_| Error::ScryptFn)?;

        if has_lot {
            let mut tmp: Vec<u8> = Vec::new();
            tmp.append(&mut pre_factor.to_vec());
            tmp.append(&mut owner_entropy.to_vec());
            pass_factor[..].copy_from_slice(&tmp.hash256());
        } else {
            pass_factor = pre_factor;
        }

        let pass_point = pass_factor.public(true)?;
        let mut seed_b_pass = [0x00; 64];

        scrypt::scrypt(
            &pass_point,
            &eprvk[3..15], // 1024 log2 = 10
            &Params::new(10, 1, 1).map_err(|_| Error::ScryptParam)?,
            &mut seed_b_pass
        ).map_err(|_| Error::ScryptFn)?;

        let derived_half1 = &seed_b_pass[..32];
        let derived_half2 = &seed_b_pass[32..];

        let cipher = Aes256::new(GenericArray::from_slice(derived_half2));

        let mut de_p2 = GenericArray::clone_from_slice(encrypted_p2);

        cipher.decrypt_block(&mut de_p2);

        for idx in 0..16 {
            de_p2[idx] ^= derived_half1[idx + 16];
        }

        let seed_b_part2 = &de_p2[8..];

        let mut tmp = [0x00; 16];
        tmp[..8].copy_from_slice(encrypted_p1);
        tmp[8..].copy_from_slice(&de_p2[..8]);

        let mut de_p1 = GenericArray::clone_from_slice(&tmp);

        cipher.decrypt_block(&mut de_p1);

        for idx in 0..16 {
            de_p1[idx] ^= derived_half1[idx];
        }

        let mut seed_b = [0x00; 24];
        seed_b[..16].copy_from_slice(&de_p1);
        seed_b[16..].copy_from_slice(seed_b_part2);

        let factor_b = seed_b.hash256();

        let mut prv = SecretKey::from_slice(&pass_factor)
            .map_err(|_| Error::PrvKey)?;

        prv.mul_assign(&factor_b).map_err(|_| Error::PrvKey)?;

        let mut result = [0x00; 32];
        result[..].copy_from_slice(&prv[..]);

        let address = result.public(compress)?.p2wpkh()?;
        let checksum = &address.as_bytes().hash256()[..4];

        if checksum != address_hash { return Err(Error::Pass) }

        Ok((result, compress))
    }

    #[inline]
    fn decrypt_non_ec(&self, pass: &str) -> Result<([u8; 32], bool), Error> {
        let eprvk = self.decode_base58ck()?;
        if eprvk[..2] != PRE_NON_EC { return Err(Error::EncKey); }
        let compress = (eprvk[2] & 0x20) == 0x20;
        let mut scrypt_key = [0x00; 64];

        scrypt::scrypt(
            pass.nfc().collect::<String>().as_bytes(),
            &eprvk[3..7], // 16384 log2 = 14
            &Params::new(14, 8, 8).map_err(|_| Error::ScryptParam)?,
            &mut scrypt_key
        ).map_err(|_| Error::ScryptFn)?;

        let cipher = Aes256::new(GenericArray::from_slice(&scrypt_key[32..]));

        let mut derived_half1 = GenericArray::clone_from_slice(&eprvk[7..23]);
        let mut derived_half2 = GenericArray::clone_from_slice(&eprvk[23..39]);

        cipher.decrypt_block(&mut derived_half1);
        cipher.decrypt_block(&mut derived_half2);

        for idx in 0..16 {
            derived_half1[idx] ^= scrypt_key[idx];
            derived_half2[idx] ^= scrypt_key[idx + 16];
        }

        let mut prvk = [0x00; 32];
        prvk[..16].copy_from_slice(&derived_half1);
        prvk[16..].copy_from_slice(&derived_half2);

        let address = prvk.public(compress)?.p2wpkh()?;
        let checksum = &address.as_bytes().hash256()[..4];

        if checksum != &eprvk[3..7] { return Err(Error::Pass) }

        Ok((prvk, compress))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    /// Encrypted secret keys from bip-0038 test vectors.
    const TV_ENCRYPTED: [&str; 9] = [
        "6PRVWUbkzzsbcVac2qwfssoUJAN1Xhrg6bNk8J7Nzm5H7kxEbn2Nh2ZoGg",
        "6PRNFFkZc2NZ6dJqFfhRoFNMR9Lnyj7dYGrzdgXXVMXcxoKTePPX1dWByq",
        "6PRW5o9FLp4gJDDVqJQKJFTpMvdsSGJxMYHtHaQBF3ooa8mwD69bapcDQn",
        "6PYNKZ1EAgYgmQfmNVamxyXVWHzK5s6DGhwP4J5o44cvXdoY7sRzhtpUeo",
        "6PYLtMnXvfG3oJde97zRyLYFZCYizPU5T3LwgdYJz1fRhh16bU7u6PPmY7",
        "6PfQu77ygVyJLZjfvMLyhLMQbYnu5uguoJJ4kMCLqWwPEdfpwANVS76gTX",
        "6PfLGnQs6VZnrNpmVKfjotbnQuaJK4KZoPFrAjx1JMJUa1Ft8gnf5WxfKd",
        "6PgNBNNzDkKdhkT6uJntUXwwzQV8Rr2tZcbkDcuC9DZRsS6AtHts4Ypo1j",
        "6PgGWtx25kUg8QWvwuJAgorN6k9FbE25rv5dMRwu5SKMnfpfVe5mar2ngH"
    ];

    /// Resulting keys from bip-0038 test vectors.
    const TV_KEY: [[u8; 32]; 9] = [
        [
            0xcb, 0xf4, 0xb9, 0xf7, 0x04, 0x70, 0x85, 0x6b, 0xb4, 0xf4, 0x0f, 0x80, 0xb8, 0x7e,
            0xdb, 0x90, 0x86, 0x59, 0x97, 0xff, 0xee, 0x6d, 0xf3, 0x15, 0xab, 0x16, 0x6d, 0x71,
            0x3a, 0xf4, 0x33, 0xa5
        ],
        [
            0x09, 0xc2, 0x68, 0x68, 0x80, 0x09, 0x5b, 0x1a, 0x4c, 0x24, 0x9e, 0xe3, 0xac, 0x4e,
            0xea, 0x8a, 0x01, 0x4f, 0x11, 0xe6, 0xf9, 0x86, 0xd0, 0xb5, 0x02, 0x5a, 0xc1, 0xf3,
            0x9a, 0xfb, 0xd9, 0xae
        ],
        [
            0x64, 0xee, 0xab, 0x5f, 0x9b, 0xe2, 0xa0, 0x1a, 0x83, 0x65, 0xa5, 0x79, 0x51, 0x1e,
            0xb3, 0x37, 0x3c, 0x87, 0xc4, 0x0d, 0xa6, 0xd2, 0xa2, 0x5f, 0x05, 0xbd, 0xa6, 0x8f,
            0xe0, 0x77, 0xb6, 0x6e
        ],
        [
            0xcb, 0xf4, 0xb9, 0xf7, 0x04, 0x70, 0x85, 0x6b, 0xb4, 0xf4, 0x0f, 0x80, 0xb8, 0x7e,
            0xdb, 0x90, 0x86, 0x59, 0x97, 0xff, 0xee, 0x6d, 0xf3, 0x15, 0xab, 0x16, 0x6d, 0x71,
            0x3a, 0xf4, 0x33, 0xa5
        ],
        [
            0x09, 0xc2, 0x68, 0x68, 0x80, 0x09, 0x5b, 0x1a, 0x4c, 0x24, 0x9e, 0xe3, 0xac, 0x4e,
            0xea, 0x8a, 0x01, 0x4f, 0x11, 0xe6, 0xf9, 0x86, 0xd0, 0xb5, 0x02, 0x5a, 0xc1, 0xf3,
            0x9a, 0xfb, 0xd9, 0xae
        ],
        [
            0xa4, 0x3a, 0x94, 0x05, 0x77, 0xf4, 0xe9, 0x7f, 0x5c, 0x4d, 0x39, 0xeb, 0x14, 0xff,
            0x08, 0x3a, 0x98, 0x18, 0x7c, 0x64, 0xea, 0x7c, 0x99, 0xef, 0x7c, 0xe4, 0x60, 0x83,
            0x39, 0x59, 0xa5, 0x19
        ],
        [
            0xc2, 0xc8, 0x03, 0x6d, 0xf2, 0x68, 0xf4, 0x98, 0x09, 0x93, 0x50, 0x71, 0x8c, 0x4a,
            0x3e, 0xf3, 0x98, 0x4d, 0x2b, 0xe8, 0x46, 0x18, 0xc2, 0x65, 0x0f, 0x51, 0x71, 0xdc,
            0xc5, 0xeb, 0x66, 0x0a
        ],
        [
            0x44, 0xea, 0x95, 0xaf, 0xbf, 0x13, 0x83, 0x56, 0xa0, 0x5e, 0xa3, 0x21, 0x10, 0xdf,
            0xd6, 0x27, 0x23, 0x2d, 0x0f, 0x29, 0x91, 0xad, 0x22, 0x11, 0x87, 0xbe, 0x35, 0x6f,
            0x19, 0xfa, 0x81, 0x90
        ],
        [
            0xca, 0x27, 0x59, 0xaa, 0x4a, 0xdb, 0x0f, 0x96, 0xc4, 0x14, 0xf3, 0x6a, 0xbe, 0xb8,
            0xdb, 0x59, 0x34, 0x29, 0x85, 0xbe, 0x9f, 0xa5, 0x0f, 0xaa, 0xc2, 0x28, 0xc8, 0xe7,
            0xd9, 0x0e, 0x30, 0x06
        ]
    ];

    /// Passphrases from bip-0038 test vectors.
    const TV_PASS: [&str; 9] = [
        "TestingOneTwoThree",
        "Satoshi",
        "\u{03d2}\u{0301}\u{0000}\u{010400}\u{01f4a9}",
        "TestingOneTwoThree",
        "Satoshi",
        "TestingOneTwoThree",
        "Satoshi",
        "MOLON LABE",
        "ΜΟΛΩΝ ΛΑΒΕ"
    ];

    /// Wif private keys from bip-0038 test vectors.
    const TV_WIF: [&str; 9] = [
        "5KN7MzqK5wt2TP1fQCYyHBtDrXdJuXbUzm4A9rKAteGu3Qi5CVR",
        "5HtasZ6ofTHP6HCwTqTkLDuLQisYPah7aUnSKfC7h4hMUVw2gi5",
        "5Jajm8eQ22H3pGWLEVCXyvND8dQZhiQhoLJNKjYXk9roUFTMSZ4",
        "L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP",
        "KwYgW8gcxj1JWJXhPSu4Fqwzfhp5Yfi42mdYmMa4XqK7NJxXUSK7",
        "5K4caxezwjGCGfnoPTZ8tMcJBLB7Jvyjv4xxeacadhq8nLisLR2",
        "5KJ51SgxWaAYR13zd9ReMhJpwrcX47xTJh2D3fGPG9CM8vkv5sH",
        "5JLdxTtcTHcfYcmJsNVy1v2PMDx432JPoYcBTVVRHpPaxUrdtf8",
        "5KMKKuUmAkiNbA3DazMQiLfDq47qs8MAEThm4yL8R2PhV1ov33D"
    ];

    #[test]
    fn test_decode_wif() {
        assert_eq!(
            "KwntMbt59tTsj8xqpqYqRRWufyjGunvhSyeMo3NTYpFYzZbXJ5Hp".decode_wif(),
            Ok(([0x11; 32], true))
        );
        assert_eq!(
            "5HwoXVkHoRM8sL2KmNRS217n1g8mPPBomrY7yehCuXC1115WWsh".decode_wif(),
            Ok(([0x11; 32], false))
        );
        assert_eq!(
            "KzkcmnPaJd7mqT47Rnk9XMGRfW2wfo7ar2M2o6Yoe6Rdgbg2bHM9".decode_wif(),
            Ok(([0x69; 32], true))
        );
        assert_eq!(
            "5JciBbkdYdjKKE9rwZ7c1XscwwcLBbv9aJyeZeWQi2gZnHeiX57".decode_wif(),
            Ok(([0x69; 32], false))
        );
        assert_eq!(
            ["KzkcmnPaJd7mqT47Rnk9XMGRfW2wfo7ar2M2o6Yoe6Rdgbg2bHM9", "a"].concat().decode_wif(),
            Err(Error::WifKey)
        );
        assert_eq!(
            "KzkcmnPaJd7mqT47Rnk9XMGRfW2wfo7ar2M2o6Yoe6Rdgbg2bHM9".replace("d", "b").decode_wif(),
            Err(Error::Checksum)
        );
        assert_eq!(["a"; 51].concat().decode_wif(), Err(Error::WifKey));
        assert_eq!(["a"; 52].concat().decode_wif(), Err(Error::WifKey));
    }

    #[test]
    fn test_decrypt() {
        let mut compress = false;
        for (idx, ekey) in TV_ENCRYPTED.iter().enumerate() {
            if idx > 2 { compress = true }
            if idx > 4 { compress = false }
            assert_eq!(ekey.decrypt(TV_PASS[idx]), Ok((TV_KEY[idx], compress)));
        }
        assert!(TV_ENCRYPTED[1].decrypt("Satoshi").is_ok());
        assert_eq!(TV_ENCRYPTED[1].decrypt("wrong"), Err(Error::Pass));
        assert_eq!(TV_ENCRYPTED[1].replace("X", "x").decrypt("Satoshi"), Err(Error::Checksum));
        assert_eq!(TV_ENCRYPTED[1][1..].decrypt("Satoshi"), Err(Error::EncKey));
    }

    #[test]
    fn test_decrypt_to_wif() {
        for (idx, ekey) in TV_ENCRYPTED.iter().enumerate() {
            assert_eq!(ekey.decrypt_to_wif(TV_PASS[idx]).unwrap(), TV_WIF[idx]);
        }
        assert!(TV_ENCRYPTED[1].decrypt_to_wif("Satoshi").is_ok());
        assert_eq!(TV_ENCRYPTED[1].decrypt_to_wif("wrong"), Err(Error::Pass));
        assert_eq!(
            TV_ENCRYPTED[1].replace('X', "x").decrypt_to_wif("Satoshi"), Err(Error::Checksum)
        );
        assert_eq!(TV_ENCRYPTED[1][1..].decrypt_to_wif("Satoshi"), Err(Error::EncKey));
    }

    #[test]
    fn test_encode_base58ck() {
        assert_eq!("a".as_bytes().encode_base58ck(), "C2dGTwc");
        assert_eq!("abc".as_bytes().encode_base58ck(), "4h3c6RH52R");
    }

    #[test]
    fn test_encrypt() {
        let mut compress = false;
        for (idx, key) in TV_KEY[..5].iter().enumerate() { // the last four are ec-multiply
            if idx > 2 { compress = true }
            assert_eq!(key.encrypt(TV_PASS[idx], compress).unwrap(), TV_ENCRYPTED[idx]);
        }
        assert_eq!([0x00; 32].encrypt("I'm_a_passphrase", true), Err(Error::PrvKey));
    }

    #[test]
    fn test_encrypt_wif() {
        for (idx, wif) in TV_WIF[..5].iter().enumerate() {
            assert_eq!(wif.encrypt_wif(TV_PASS[idx]).unwrap(), TV_ENCRYPTED[idx]);
        }
        assert_eq!([TV_WIF[0], "a"].concat().encrypt_wif(TV_PASS[0]), Err(Error::WifKey));
        assert_eq!(TV_WIF[0].replace('X', "!").encrypt_wif(TV_PASS[0]), Err(Error::Base58));
        assert_eq!(TV_WIF[0].replace('X', "x").encrypt_wif(TV_PASS[0]), Err(Error::Checksum));
        assert_eq!(
            "KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73NUBByJr".encrypt_wif("pass"), // zeroed
            Err(Error::PrvKey)
        );
    }

    #[test]
    fn test_generate() {
        assert!("バンドメイド".generate(true).unwrap().decrypt("バンドメイド").is_ok());
        assert!("くるっぽー!".generate(false).unwrap() .decrypt("くるっぽー!").is_ok());
        assert_eq!(
            "something_really_dumb".generate(true).unwrap().decrypt("rocket_science"),
            Err(Error::Pass)
        );
        assert_eq!("a".generate(false).unwrap().decrypt("b"), Err(Error::Pass));
    }

    #[test]
    fn test_hash160() {
        assert_eq!(
            "a".as_bytes().hash160(),
            [
                0x99, 0x43, 0x55, 0x19, 0x9e, 0x51, 0x6f, 0xf7, 0x6c, 0x4f, 0xa4, 0xaa, 0xb3, 0x93,
                0x37, 0xb9, 0xd8, 0x4c, 0xf1, 0x2b
            ]
        );
    }

    #[test]
    fn test_hash256() {
        assert_eq!(
            "a".as_bytes().hash256(),
            [
                0xbf, 0x5d, 0x3a, 0xff, 0xb7, 0x3e, 0xfd, 0x2e, 0xc6, 0xc3, 0x6a, 0xd3, 0x11, 0x2d,
                0xd9, 0x33, 0xef, 0xed, 0x63, 0xc4, 0xe1, 0xcb, 0xff, 0xcf, 0xa8, 0x8e, 0x27, 0x59,
                0xc1, 0x44, 0xf2, 0xd8
            ]
        );
    }

    #[test]
    fn test_p2wpkh() {
        assert_eq!(
            [
                0x03, 0x4f, 0x35, 0x5b, 0xdc, 0xb7, 0xcc, 0x0a, 0xf7, 0x28, 0xef, 0x3c, 0xce, 0xb9,
                0x61, 0x5d, 0x90, 0x68, 0x4b, 0xb5, 0xb2, 0xca, 0x5f, 0x85, 0x9a, 0xb0, 0xf0, 0xb7,
                0x04, 0x07, 0x58, 0x71, 0xaa
            ].p2wpkh().unwrap(),
            "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9"
        );
        assert_eq!(
            [
                0x02, 0x66, 0x6b, 0xdf, 0x20, 0x25, 0xe3, 0x2f, 0x41, 0x08, 0x88, 0x99, 0xf2, 0xbc,
                0xb4, 0xbf, 0x69, 0x83, 0x18, 0x7f, 0x38, 0x0e, 0x72, 0xfc, 0x7d, 0xee, 0x11, 0x5b,
                0x1f, 0x99, 0x57, 0xcc, 0x72
            ].p2wpkh().unwrap(),
            "1N7qxowv8SnfdBYhmvpxZxyjsYQDPd88ES"
        );
        assert_eq!(
            [
                0x04, 0x4f, 0x35, 0x5b, 0xdc, 0xb7, 0xcc, 0x0a, 0xf7, 0x28, 0xef, 0x3c, 0xce, 0xb9,
                0x61, 0x5d, 0x90, 0x68, 0x4b, 0xb5, 0xb2, 0xca, 0x5f, 0x85, 0x9a, 0xb0, 0xf0, 0xb7,
                0x04, 0x07, 0x58, 0x71, 0xaa, 0x38, 0x5b, 0x6b, 0x1b, 0x8e, 0xad, 0x80, 0x9c, 0xa6,
                0x74, 0x54, 0xd9, 0x68, 0x3f, 0xcf, 0x2b, 0xa0, 0x34, 0x56, 0xd6, 0xfe, 0x2c, 0x4a,
                0xbe, 0x2b, 0x07, 0xf0, 0xfb, 0xdb, 0xb2, 0xf1, 0xc1
            ].p2wpkh().unwrap(),
            "1MsHWS1BnwMc3tLE8G35UXsS58fKipzB7a"
        );
        assert_eq!(
            [
                0x04, 0x66, 0x6b, 0xdf, 0x20, 0x25, 0xe3, 0x2f, 0x41, 0x08, 0x88, 0x99, 0xf2, 0xbc,
                0xb4, 0xbf, 0x69, 0x83, 0x18, 0x7f, 0x38, 0x0e, 0x72, 0xfc, 0x7d, 0xee, 0x11, 0x5b,
                0x1f, 0x99, 0x57, 0xcc, 0x72, 0x9d, 0xd9, 0x76, 0x13, 0x1c, 0x4c, 0x8e, 0x12, 0xab,
                0x10, 0x83, 0xca, 0x06, 0x54, 0xca, 0x5f, 0xdb, 0xca, 0xc8, 0xd3, 0x19, 0x8d, 0xaf,
                0x90, 0xf5, 0x81, 0xb5, 0x91, 0xd5, 0x63, 0x79, 0xca
            ].p2wpkh().unwrap(),
            "17iS4e5ib2t2Bj2UFjPbxSDdmecHNnCAwy"
        );
    }

    #[test]
    fn test_public() {
        assert_eq!(
            [0x11; 32].public(true).unwrap(),
            [
                0x03, 0x4f, 0x35, 0x5b, 0xdc, 0xb7, 0xcc, 0x0a, 0xf7, 0x28, 0xef, 0x3c, 0xce, 0xb9,
                0x61, 0x5d, 0x90, 0x68, 0x4b, 0xb5, 0xb2, 0xca, 0x5f, 0x85, 0x9a, 0xb0, 0xf0, 0xb7,
                0x04, 0x07, 0x58, 0x71, 0xaa
            ]
        );
        assert_eq!(
            [0x69; 32].public(true).unwrap(),
            [
                0x02, 0x66, 0x6b, 0xdf, 0x20, 0x25, 0xe3, 0x2f, 0x41, 0x08, 0x88, 0x99, 0xf2, 0xbc,
                0xb4, 0xbf, 0x69, 0x83, 0x18, 0x7f, 0x38, 0x0e, 0x72, 0xfc, 0x7d, 0xee, 0x11, 0x5b,
                0x1f, 0x99, 0x57, 0xcc, 0x72
            ]
        );
        assert_eq!(
            [0x11; 32].public(false).unwrap(),
            [
                0x04, 0x4f, 0x35, 0x5b, 0xdc, 0xb7, 0xcc, 0x0a, 0xf7, 0x28, 0xef, 0x3c, 0xce, 0xb9,
                0x61, 0x5d, 0x90, 0x68, 0x4b, 0xb5, 0xb2, 0xca, 0x5f, 0x85, 0x9a, 0xb0, 0xf0, 0xb7,
                0x04, 0x07, 0x58, 0x71, 0xaa, 0x38, 0x5b, 0x6b, 0x1b, 0x8e, 0xad, 0x80, 0x9c, 0xa6,
                0x74, 0x54, 0xd9, 0x68, 0x3f, 0xcf, 0x2b, 0xa0, 0x34, 0x56, 0xd6, 0xfe, 0x2c, 0x4a,
                0xbe, 0x2b, 0x07, 0xf0, 0xfb, 0xdb, 0xb2, 0xf1, 0xc1
            ]
        );
        assert_eq!(
            [0x69; 32].public(false).unwrap(),
            [
                0x04, 0x66, 0x6b, 0xdf, 0x20, 0x25, 0xe3, 0x2f, 0x41, 0x08, 0x88, 0x99, 0xf2, 0xbc,
                0xb4, 0xbf, 0x69, 0x83, 0x18, 0x7f, 0x38, 0x0e, 0x72, 0xfc, 0x7d, 0xee, 0x11, 0x5b,
                0x1f, 0x99, 0x57, 0xcc, 0x72, 0x9d, 0xd9, 0x76, 0x13, 0x1c, 0x4c, 0x8e, 0x12, 0xab,
                0x10, 0x83, 0xca, 0x06, 0x54, 0xca, 0x5f, 0xdb, 0xca, 0xc8, 0xd3, 0x19, 0x8d, 0xaf,
                0x90, 0xf5, 0x81, 0xb5, 0x91, 0xd5, 0x63, 0x79, 0xca
            ]
        );
    }

    #[test]
    fn test_wif() {
        assert_eq!([0x11; 32].wif(true), "KwntMbt59tTsj8xqpqYqRRWufyjGunvhSyeMo3NTYpFYzZbXJ5Hp");
        assert_eq!([0x11; 32].wif(false), "5HwoXVkHoRM8sL2KmNRS217n1g8mPPBomrY7yehCuXC1115WWsh");
        assert_eq!([0x69; 32].wif(true), "KzkcmnPaJd7mqT47Rnk9XMGRfW2wfo7ar2M2o6Yoe6Rdgbg2bHM9");
        assert_eq!([0x69; 32].wif(false), "5JciBbkdYdjKKE9rwZ7c1XscwwcLBbv9aJyeZeWQi2gZnHeiX57");
        assert_eq!([0xd0; 32].wif(true), "L4DczGWRanBGXnun83Fs9HcPCaXXq7ngxZrBY13Phdsw36WU1rQA");
    }
}