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
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
use core::fmt::{self, Debug, Error, Formatter};
use core::time::Duration;
use crate::Map;
use crate::{Arc, Mutex, MutexGuard};

#[cfg(feature = "backtrace")]
use backtrace::Backtrace;
use bitcoin;
use bitcoin::hashes::sha256::Hash as Sha256Hash;
use bitcoin::hashes::sha256d::Hash as Sha256dHash;
use bitcoin::hashes::Hash;
use bitcoin::secp256k1;
use bitcoin::secp256k1::{All, PublicKey, Secp256k1, SecretKey, Signature, Message};
use bitcoin::util::bip32::{ExtendedPrivKey, ExtendedPubKey};
use bitcoin::{Network, OutPoint, Script, SigHashType};
use lightning::chain::keysinterface::{BaseSign, InMemorySigner, KeysInterface};
use lightning::ln::chan_utils::{make_funding_redeemscript, ChannelPublicKeys, ChannelTransactionParameters, CommitmentTransaction, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment, HolderCommitmentTransaction, TxCreationKeys, derive_private_key};

use lightning::ln::PaymentHash;

use crate::policy::error::ValidationError;
use crate::policy::validator::{SimpleValidatorFactory, ValidatorFactory, ValidatorState};
use crate::signer::my_keys_manager::{KeyDerivationStyle, MyKeysManager};
use crate::signer::my_signer::SyncLogger;
use crate::tx::tx::{build_commitment_tx, get_commitment_transaction_number_obscure_factor, CommitmentInfo2, HTLCInfo, HTLCInfo2, build_close_tx, sign_commitment};
use crate::util::crypto_utils::{derive_public_key, derive_revocation_pubkey, payload_for_p2wpkh, derive_private_revocation_key};
use crate::util::enforcing_trait_impls::{EnforcementState, EnforcingSigner};
use crate::util::status::Status;
use crate::util::{invoice_utils, INITIAL_COMMITMENT_NUMBER};
use bitcoin::secp256k1::recovery::RecoverableSignature;
use lightning::chain;
use bitcoin::blockdata::constants::genesis_block;
use bitcoin::util::bip143::SigHashCache;
use bitcoin::secp256k1::ecdh::SharedSecret;
use crate::persist::Persist;
use crate::persist::model::NodeEntry;
use std::convert::TryFrom;
use std::str::FromStr;

#[derive(PartialEq, Eq, Hash, Clone, Copy)]
pub struct ChannelId(pub [u8; 32]);
// NOTE - this "ChannelId" does *not* correspond to the "channel_id"
// defined in BOLT #2.

impl Debug for ChannelId {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        f.write_str(hex::encode(self.0).as_str())
    }
}

impl fmt::Display for ChannelId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(hex::encode(self.0).as_str())
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CommitmentType {
    Legacy,
    StaticRemoteKey,
    Anchors,
}

#[derive(Clone)]
pub struct ChannelSetup {
    pub is_outbound: bool,
    pub channel_value_sat: u64, // DUP keys.inner.channel_value_satoshis
    pub push_value_msat: u64,
    pub funding_outpoint: OutPoint,
    /// locally imposed requirement on the remote commitment transaction to_self_delay
    pub holder_to_self_delay: u16,
    /// Maybe be None if we should generate it inside the signer
    pub holder_shutdown_script: Option<Script>,
    pub counterparty_points: ChannelPublicKeys, // DUP keys.inner.remote_channel_pubkeys
    /// remotely imposed requirement on the local commitment transaction to_self_delay
    pub counterparty_to_self_delay: u16,
    pub counterparty_shutdown_script: Script,
    pub commitment_type: CommitmentType,
}

// Need to define manually because ChannelPublicKeys doesn't derive Debug.
// BEGIN NOT TESTED
impl fmt::Debug for ChannelSetup {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ChannelSetup")
            .field("is_outbound", &self.is_outbound)
            .field("channel_value_sat", &self.channel_value_sat)
            .field("push_value_msat", &self.push_value_msat)
            .field("funding_outpoint", &self.funding_outpoint)
            .field("holder_to_self_delay", &self.holder_to_self_delay)
            .field("holder_shutdown_script", &self.holder_shutdown_script)
            .field(
                "counterparty_points",
                log_channel_public_keys!(&self.counterparty_points),
            )
            .field(
                "counterparty_to_self_delay",
                &self.counterparty_to_self_delay,
            )
            .field(
                "counterparty_shutdown_script",
                &self.counterparty_shutdown_script,
            )
            .field("commitment_type", &self.commitment_type)
            .finish()
    }
}
// END NOT TESTED

impl ChannelSetup {
    pub(crate) fn option_static_remotekey(&self) -> bool {
        self.commitment_type != CommitmentType::Legacy
    }

    pub(crate) fn option_anchor_outputs(&self) -> bool {
        self.commitment_type == CommitmentType::Anchors
    }
}

// After NewChannel, before ReadyChannel
#[derive(Clone)]
pub struct ChannelStub {
    pub node: Arc<Node>,
    pub nonce: Vec<u8>,
    pub logger: Arc<SyncLogger>,
    pub secp_ctx: Secp256k1<All>,
    pub keys: EnforcingSigner, // Incomplete, channel_value_sat is placeholder.
    pub id0: ChannelId,
}

// After ReadyChannel
#[derive(Clone)]
pub struct Channel {
    pub node: Arc<Node>,
    pub nonce: Vec<u8>,
    pub logger: Arc<SyncLogger>,
    pub secp_ctx: Secp256k1<All>,
    pub keys: EnforcingSigner,
    pub setup: ChannelSetup,
    pub id0: ChannelId,
    pub id: Option<ChannelId>,
}

pub enum ChannelSlot {
    Stub(ChannelStub),
    Ready(Channel),
}

impl ChannelSlot {
    // BEGIN NOT TESTED
    pub fn nonce(&self) -> Vec<u8> {
        match self {
            ChannelSlot::Stub(stub) => stub.nonce(),
            ChannelSlot::Ready(chan) => chan.nonce(),
        }
    }
    // END NOT TESTED
}

pub trait ChannelBase {
    // Both ChannelStub and ready Channels can handle these.
    fn get_channel_basepoints(&self) -> ChannelPublicKeys;
    fn get_per_commitment_point(&self, commitment_number: u64) -> PublicKey;
    fn get_per_commitment_secret(&self, commitment_number: u64) -> SecretKey;
    fn nonce(&self) -> Vec<u8>;
}

impl Debug for Channel {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str("channel")
    }
}

impl ChannelBase for ChannelStub {
    fn get_channel_basepoints(&self) -> ChannelPublicKeys {
        self.keys.pubkeys().clone()
    }

    fn get_per_commitment_point(&self, commitment_number: u64) -> PublicKey {
        self.keys.get_per_commitment_point(
            INITIAL_COMMITMENT_NUMBER - commitment_number,
            &self.secp_ctx,
        )
    }

    fn get_per_commitment_secret(&self, commitment_number: u64) -> SecretKey {
        let secret = self
            .keys
            .release_commitment_secret(INITIAL_COMMITMENT_NUMBER - commitment_number);
        SecretKey::from_slice(&secret).unwrap()
    }

    // BEGIN NOT TESTED
    fn nonce(&self) -> Vec<u8> {
        self.nonce.clone()
    }
    // END NOT TESTED
}

impl ChannelBase for Channel {
    fn get_channel_basepoints(&self) -> ChannelPublicKeys {
        self.keys.pubkeys().clone()
    }

    fn get_per_commitment_point(&self, commitment_number: u64) -> PublicKey {
        self.keys.get_per_commitment_point(
            INITIAL_COMMITMENT_NUMBER - commitment_number,
            &self.secp_ctx,
        )
    }

    fn get_per_commitment_secret(&self, commitment_number: u64) -> SecretKey {
        let secret = self.keys
            .release_commitment_secret(INITIAL_COMMITMENT_NUMBER - commitment_number);
        self.persist().unwrap();
        SecretKey::from_slice(&secret).unwrap()
    }

    // BEGIN NOT TESTED
    fn nonce(&self) -> Vec<u8> {
        self.nonce.clone()
    }
    // END NOT TESTED
}

impl ChannelStub {
    pub(crate) fn channel_keys_with_channel_value(&self, channel_value_sat: u64) -> InMemorySigner {
        let secp_ctx = Secp256k1::signing_only();
        let keys0 = self.keys.inner();
        InMemorySigner::new(
            &secp_ctx,
            keys0.funding_key,
            keys0.revocation_base_key,
            keys0.payment_key,
            keys0.delayed_payment_base_key,
            keys0.htlc_base_key,
            keys0.commitment_seed,
            channel_value_sat,
            keys0.channel_keys_id(),
        )
    }
}

// Phase 2
impl Channel {
    pub(crate) fn invalid_argument(&self, msg: impl Into<String>) -> Status {
        let s = msg.into();
        log_error!(self, "INVALID ARGUMENT: {}", &s);
        #[cfg(feature = "backtrace")]
        log_error!(self, "BACKTRACE:\n{:?}", Backtrace::new());
        Status::invalid_argument(s)
    }

    pub(crate) fn internal_error(&self, msg: impl Into<String>) -> Status {
        let s = msg.into();
        log_error!(self, "INTERNAL ERROR: {}", &s);
        #[cfg(feature = "backtrace")]
        log_error!(self, "BACKTRACE:\n{:?}", Backtrace::new());
        Status::internal(s)
    }

    pub(crate) fn validation_error(&self, ve: ValidationError) -> Status {
        let s: String = ve.into();
        log_error!(self, "VALIDATION ERROR: {}", &s);
        #[cfg(feature = "backtrace")]
        log_error!(self, "BACKTRACE:\n{:?}", Backtrace::new());
        Status::invalid_argument(s)
    }

    // Phase 2
    pub(crate) fn make_counterparty_tx_keys(
        &self,
        per_commitment_point: &PublicKey,
    ) -> Result<TxCreationKeys, Status> {
        let holder_points = self.keys.pubkeys();

        let counterparty_points = self.keys.counterparty_pubkeys();

        Ok(self.make_tx_keys(per_commitment_point, counterparty_points, holder_points))
    }

    pub(crate) fn make_holder_tx_keys(
        &self,
        per_commitment_point: &PublicKey,
    ) -> Result<TxCreationKeys, Status> {
        let holder_points = self.keys.pubkeys();

        let counterparty_points = self.keys.counterparty_pubkeys();

        Ok(self.make_tx_keys(per_commitment_point, holder_points, counterparty_points))
    }

    fn make_tx_keys(
        &self,
        per_commitment_point: &PublicKey,
        a_points: &ChannelPublicKeys,
        b_points: &ChannelPublicKeys,
    ) -> TxCreationKeys {
        TxCreationKeys::derive_new(
            &self.secp_ctx,
            &per_commitment_point,
            &a_points.delayed_payment_basepoint,
            &a_points.htlc_basepoint,
            &b_points.revocation_basepoint,
            &b_points.htlc_basepoint,
        )
            .expect("failed to derive keys")
    }

    fn derive_counterparty_payment_pubkey(
        &self,
        remote_per_commitment_point: &PublicKey,
    ) -> Result<PublicKey, Status> {
        let holder_points = self.keys.pubkeys();
        let counterparty_key = if self.setup.option_static_remotekey() {
            holder_points.payment_point
        } else {
            // BEGIN NOT TESTED
            derive_public_key(
                &self.secp_ctx,
                &remote_per_commitment_point,
                &holder_points.payment_point,
            )
                .map_err(|err| {
                    self.internal_error(format!("could not derive counterparty_key: {}", err))
                })?
            // END NOT TESTED
        };
        Ok(counterparty_key)
    }

    // BEGIN NOT TESTED
    fn get_commitment_transaction_number_obscure_factor(&self) -> u64 {
        get_commitment_transaction_number_obscure_factor(
            &self.keys.pubkeys().payment_point,
            &self.keys.counterparty_pubkeys().payment_point,
            self.setup.is_outbound,
        )
    }

    // forward counting commitment number
    #[allow(dead_code)]
    pub(crate) fn build_commitment_tx(
        &self,
        per_commitment_point: &PublicKey,
        commitment_number: u64,
        info: &CommitmentInfo2,
    ) -> Result<
        (
            bitcoin::Transaction,
            Vec<Script>,
            Vec<HTLCOutputInCommitment>,
        ),
        Status,
    > {
        let keys = if !info.is_counterparty_broadcaster {
            self.make_holder_tx_keys(per_commitment_point)?
        } else {
            self.make_counterparty_tx_keys(per_commitment_point)?
        };

        // TODO - consider if we can get LDK to put funding pubkeys in TxCreationKeys
        let (workaround_local_funding_pubkey, workaround_remote_funding_pubkey) =
            if !info.is_counterparty_broadcaster {
                (
                    &self.keys.pubkeys().funding_pubkey,
                    &self.keys.counterparty_pubkeys().funding_pubkey,
                )
            } else {
                (
                    &self.keys.counterparty_pubkeys().funding_pubkey,
                    &self.keys.pubkeys().funding_pubkey,
                )
            };

        let obscured_commitment_transaction_number =
            self.get_commitment_transaction_number_obscure_factor() ^ commitment_number;
        Ok(build_commitment_tx(
            &keys,
            info,
            obscured_commitment_transaction_number,
            self.setup.funding_outpoint,
            self.setup.option_anchor_outputs(),
            workaround_local_funding_pubkey,
            workaround_remote_funding_pubkey,
        ))
    }

    // END NOT TESTED

    /// Sign a counterparty commitment transaction after rebuilding it
    /// from the supplied arguments.
    // TODO anchors support once upstream supports it
    pub fn sign_counterparty_commitment_tx_phase2(
        &self,
        remote_per_commitment_point: &PublicKey,
        commitment_number: u64,
        feerate_per_kw: u32,
        to_holder_value_sat: u64,
        to_counterparty_value_sat: u64,
        offered_htlcs: Vec<HTLCInfo2>,
        received_htlcs: Vec<HTLCInfo2>,
    ) -> Result<(Vec<u8>, Vec<Vec<u8>>), Status> {
        let htlcs = Self::htlcs_info2_to_oic(offered_htlcs, received_htlcs);

        let commitment_tx = self.make_counterparty_commitment_tx(
            remote_per_commitment_point,
            commitment_number,
            feerate_per_kw,
            to_holder_value_sat,
            to_counterparty_value_sat,
            htlcs,
        );

        log_debug!(
            self,
            "channel: sign counterparty txid {}",
            commitment_tx.trust().built_transaction().txid
        );

        let sigs = self
            .keys
            .sign_counterparty_commitment(&commitment_tx, &self.secp_ctx)
            .map_err(|_| self.internal_error("failed to sign"))?;
        let mut sig = sigs.0.serialize_der().to_vec();
        sig.push(SigHashType::All as u8);
        let mut htlc_sigs = Vec::new();
        for htlc_signature in sigs.1 {
            let mut htlc_sig = htlc_signature.serialize_der().to_vec();
            htlc_sig.push(SigHashType::All as u8);
            htlc_sigs.push(htlc_sig);
        }
        Ok((sig, htlc_sigs))
    }

    pub(crate) fn make_counterparty_commitment_tx(
        &self,
        remote_per_commitment_point: &PublicKey,
        commitment_number: u64,
        feerate_per_kw: u32,
        to_holder_value_sat: u64,
        to_counterparty_value_sat: u64,
        htlcs: Vec<HTLCOutputInCommitment>,
    ) -> CommitmentTransaction {
        let keys = self
            .make_counterparty_tx_keys(remote_per_commitment_point)
            .unwrap();

        let mut htlcs_with_aux = htlcs.iter().map(|h| (h.clone(), ())).collect();
        let channel_parameters = self.make_channel_parameters();
        let parameters = channel_parameters.as_counterparty_broadcastable();
        let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
            INITIAL_COMMITMENT_NUMBER - commitment_number,
            to_counterparty_value_sat,
            to_holder_value_sat,
            keys,
            feerate_per_kw,
            &mut htlcs_with_aux,
            &parameters,
        );
        commitment_tx
    }

    /// Sign a holder commitment transaction after rebuilding it
    /// from the supplied arguments.
    // TODO anchors support once upstream supports it
    pub fn sign_holder_commitment_tx_phase2(
        &self,
        commitment_number: u64,
        feerate_per_kw: u32,
        to_holder_value_sat: u64,
        to_counterparty_value_sat: u64,
        offered_htlcs: Vec<HTLCInfo2>,
        received_htlcs: Vec<HTLCInfo2>,
    ) -> Result<(Vec<u8>, Vec<Vec<u8>>), Status> {
        let htlcs = Self::htlcs_info2_to_oic(offered_htlcs, received_htlcs);

        // We provide a dummy signature for the remote, since we don't require that sig
        // to be passed in to this call.  It would have been better if HolderCommitmentTransaction
        // didn't require the remote sig.
        // TODO consider if we actually want the sig for policy checks
        let dummy_sig = Secp256k1::new().sign(
            &secp256k1::Message::from_slice(&[42; 32]).unwrap(),
            &SecretKey::from_slice(&[42; 32]).unwrap(),
        );
        let mut htlc_dummy_sigs = Vec::with_capacity(htlcs.len());
        htlc_dummy_sigs.resize(htlcs.len(), dummy_sig);

        let commitment_tx = self.make_holder_commitment_tx(
            commitment_number,
            feerate_per_kw,
            to_holder_value_sat,
            to_counterparty_value_sat,
            htlcs,
        );
        log_debug!(
            self,
            "channel: sign holder txid {}",
            commitment_tx.trust().built_transaction().txid
        );

        let holder_commitment_tx = HolderCommitmentTransaction::new(
            commitment_tx,
            dummy_sig,
            htlc_dummy_sigs,
            &self.keys.pubkeys().funding_pubkey,
            &self.keys.counterparty_pubkeys().funding_pubkey,
        );

        let (sig, htlc_sigs) = self
            .keys
            .sign_holder_commitment_and_htlcs(&holder_commitment_tx, &self.secp_ctx)
            .map_err(|_| self.internal_error("failed to sign"))?;
        let mut sig_vec = sig.serialize_der().to_vec();
        sig_vec.push(SigHashType::All as u8);

        let mut htlc_sig_vecs = Vec::new();
        for htlc_sig in htlc_sigs {
            let mut htlc_sig_vec = htlc_sig.serialize_der().to_vec();
            htlc_sig_vec.push(SigHashType::All as u8);
            htlc_sig_vecs.push(htlc_sig_vec);
        }
        self.persist()?;
        Ok((sig_vec, htlc_sig_vecs))
    }

    pub(crate) fn make_holder_commitment_tx(
        &self,
        commitment_number: u64,
        feerate_per_kw: u32,
        to_holder_value_sat: u64,
        to_counterparty_value_sat: u64,
        htlcs: Vec<HTLCOutputInCommitment>,
    ) -> CommitmentTransaction {
        let per_commitment_point = self.get_per_commitment_point(commitment_number);
        let keys = self.make_holder_tx_keys(&per_commitment_point).unwrap();

        let mut htlcs_with_aux = htlcs.iter().map(|h| (h.clone(), ())).collect();
        let channel_parameters = self.make_channel_parameters();
        let parameters = channel_parameters.as_holder_broadcastable();
        let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
            INITIAL_COMMITMENT_NUMBER - commitment_number,
            to_holder_value_sat,
            to_counterparty_value_sat,
            keys,
            feerate_per_kw,
            &mut htlcs_with_aux,
            &parameters,
        );
        commitment_tx
    }

    fn htlcs_info2_to_oic(
        offered_htlcs: Vec<HTLCInfo2>,
        received_htlcs: Vec<HTLCInfo2>,
    ) -> Vec<HTLCOutputInCommitment> {
        let mut htlcs = Vec::new();
        for htlc in offered_htlcs {
            htlcs.push(HTLCOutputInCommitment {
                offered: true,
                amount_msat: htlc.value_sat * 1000,
                cltv_expiry: htlc.cltv_expiry,
                payment_hash: htlc.payment_hash,
                transaction_output_index: None,
            });
        }
        for htlc in received_htlcs {
            htlcs.push(HTLCOutputInCommitment {
                offered: false,
                amount_msat: htlc.value_sat * 1000,
                cltv_expiry: htlc.cltv_expiry,
                payment_hash: htlc.payment_hash,
                transaction_output_index: None,
            });
        }
        htlcs
    }

    /// Build channel parameters, used to further build a commitment transaction
    pub fn make_channel_parameters(&self) -> ChannelTransactionParameters {
        let funding_outpoint = chain::transaction::OutPoint {
            txid: self.setup.funding_outpoint.txid,
            index: self.setup.funding_outpoint.vout as u16,
        };
        let channel_parameters = ChannelTransactionParameters {
            holder_pubkeys: self.get_channel_basepoints(),
            holder_selected_contest_delay: self.setup.holder_to_self_delay,
            is_outbound_from_holder: self.setup.is_outbound,
            counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
                pubkeys: self.setup.counterparty_points.clone(),
                selected_contest_delay: self.setup.counterparty_to_self_delay,
            }),
            funding_outpoint: Some(funding_outpoint),
        };
        channel_parameters
    }

    /// Get the shutdown script where our funds will go when we mutual-close
    pub fn get_shutdown_script(&self) -> Script {
        self.setup.holder_shutdown_script
            .clone()
            .unwrap_or_else(
                || payload_for_p2wpkh(&self.node.keys_manager.get_shutdown_pubkey())
                    .script_pubkey(),
            )
    }

    /// Sign a mutual close transaction after rebuilding it from the supplied arguments
    pub fn sign_mutual_close_tx_phase2(
        &self,
        to_holder_value_sat: u64,
        to_counterparty_value_sat: u64,
        counterparty_shutdown_script: Option<Script>
    ) -> Result<Signature, Status> {
        let holder_script = self.get_shutdown_script();

        let counterparty_script = counterparty_shutdown_script
            .as_ref()
            .unwrap_or(&self.setup.counterparty_shutdown_script);

        let tx = build_close_tx(
            to_holder_value_sat,
            to_counterparty_value_sat,
            &holder_script,
            counterparty_script,
            self.setup.funding_outpoint,
        );

        let res = self.keys.sign_closing_transaction(&tx, &self.secp_ctx)
            .map_err(|_| Status::internal("failed to sign"));
        self.persist()?;
        res
    }

    /// Sign a delayed output that goes to us while sweeping a transaction we broadcast
    pub fn sign_delayed_sweep(
        &self,
        tx: &bitcoin::Transaction,
        input: usize,
        commitment_number: u64,
        redeemscript: &Script,
        htlc_amount_sat: u64,
    ) -> Result<Signature, Status> {
        let per_commitment_point = self.get_per_commitment_point(commitment_number);

        let htlc_sighash = Message::from_slice(
            &SigHashCache::new(tx).signature_hash(
                input,
                &redeemscript,
                htlc_amount_sat,
                SigHashType::All,
            )[..],
        ).map_err(|_| Status::internal("failed to sighash"))?;

        let htlc_privkey = derive_private_key(
            &self.secp_ctx,
            &per_commitment_point,
            &self.keys.delayed_payment_base_key(),
        ).map_err(|_| Status::internal("failed to derive key"))?;

        let sig = self.secp_ctx.sign(&htlc_sighash, &htlc_privkey);
        self.persist()?;
        Ok(sig)
    }

    /// Sign TODO
    pub fn sign_counterparty_htlc_sweep(
        &self,
        tx: &bitcoin::Transaction,
        input: usize,
        remote_per_commitment_point: &PublicKey,
        redeemscript: &Script,
        htlc_amount_sat: u64,
    ) -> Result<Signature, Status> {
        let htlc_sighash = Message::from_slice(
            &SigHashCache::new(tx).signature_hash(
                input,
                &redeemscript,
                htlc_amount_sat,
                SigHashType::All,
            )[..],
        ).map_err(|_| Status::internal("failed to sighash"))?;

        let htlc_privkey = derive_private_key(
            &self.secp_ctx,
            &remote_per_commitment_point,
            &self.keys.htlc_base_key(),
        ).map_err(|_| Status::internal("failed to derive key"))?;

        let sig = self.secp_ctx.sign(&htlc_sighash, &htlc_privkey);
        self.persist()?;
        Ok(sig)
    }

    /// Sign a justice transaction on an old state that the counterparty broadcast
    pub fn sign_justice_sweep(
        &self,
        tx: &bitcoin::Transaction,
        input: usize,
        revocation_secret: &SecretKey,
        redeemscript: &Script,
        htlc_amount_sat: u64,
    ) -> Result<Signature, Status> {
        let sighash = Message::from_slice(
            &SigHashCache::new(tx).signature_hash(
                input,
                &redeemscript,
                htlc_amount_sat,
                SigHashType::All,
            )[..],
        ).map_err(|_| Status::internal("failed to sighash"))?;

        let privkey = derive_private_revocation_key(
            &self.secp_ctx,
            revocation_secret,
            self.keys.revocation_base_key(),
        ).map_err(|_| Status::internal("failed to derive key"))?;

        let sig = self.secp_ctx.sign(&sighash, &privkey);
        self.persist()?;
        Ok(sig)
    }

    /// Sign a channel announcement with both the node key and the funding key
    pub fn sign_channel_announcement(&self, announcement: &Vec<u8>) -> (Signature, Signature) {
        let ann_hash = Sha256dHash::hash(announcement);
        let encmsg = secp256k1::Message::from_slice(&ann_hash[..])
            .expect("encmsg failed");

        (self.secp_ctx.sign(&encmsg, &self.node.get_node_secret()),
         self.secp_ctx.sign(&encmsg, &self.keys.funding_key()))
    }

    fn persist(&self) -> Result<(), Status> {
        self.node.persister.update_channel(&self.node.get_id(), &self)
            .map_err(|_| Status::internal("persist failed"))
    }

    pub fn network(&self) -> Network {
        self.node.network
    }
}

// Phase 1
impl Channel {
    pub(crate) fn build_counterparty_commitment_info(
        &self,
        remote_per_commitment_point: &PublicKey,
        to_holder_value_sat: u64,
        to_counterparty_value_sat: u64,
        offered_htlcs: Vec<HTLCInfo2>,
        received_htlcs: Vec<HTLCInfo2>,
    ) -> Result<CommitmentInfo2, Status> {
        let holder_points = self.keys.pubkeys();
        let secp_ctx = &self.secp_ctx;

        let to_counterparty_delayed_pubkey = derive_public_key(
            secp_ctx,
            &remote_per_commitment_point,
            &self.setup.counterparty_points.delayed_payment_basepoint,
        )
            .map_err(|err| {
                // BEGIN NOT TESTED
                self.internal_error(format!("could not derive to_holder_delayed_key: {}", err))
                // END NOT TESTED
            })?;
        let counterparty_payment_pubkey =
            self.derive_counterparty_payment_pubkey(remote_per_commitment_point)?;
        let revocation_pubkey = derive_revocation_pubkey(
            secp_ctx,
            &remote_per_commitment_point,
            &holder_points.revocation_basepoint,
        )
            .map_err(|err| self.internal_error(format!("could not derive revocation key: {}", err)))?;
        let to_holder_pubkey = counterparty_payment_pubkey.clone();
        Ok(CommitmentInfo2 {
            is_counterparty_broadcaster: true,
            to_countersigner_pubkey: to_holder_pubkey,
            to_countersigner_value_sat: to_holder_value_sat,
            revocation_pubkey,
            to_broadcaster_delayed_pubkey: to_counterparty_delayed_pubkey,
            to_broadcaster_value_sat: to_counterparty_value_sat,
            to_self_delay: self.setup.holder_to_self_delay,
            offered_htlcs,
            received_htlcs,
        })
    }

    // TODO dead code
    // BEGIN NOT TESTED
    #[allow(dead_code)]
    pub fn build_holder_commitment_info(
        &self,
        per_commitment_point: &PublicKey,
        to_holder_value_sat: u64,
        to_counterparty_value_sat: u64,
        offered_htlcs: Vec<HTLCInfo2>,
        received_htlcs: Vec<HTLCInfo2>,
    ) -> Result<CommitmentInfo2, Status> {
        let holder_points = self.keys.pubkeys();
        let counterparty_points = self.keys.counterparty_pubkeys();
        let secp_ctx = &self.secp_ctx;

        let to_holder_delayed_pubkey = derive_public_key(
            secp_ctx,
            &per_commitment_point,
            &holder_points.delayed_payment_basepoint,
        )
            .map_err(|err| {
                self.internal_error(format!(
                    "could not derive to_holder_delayed_pubkey: {}",
                    err
                ))
            })?;

        let counterparty_pubkey = if self.setup.option_static_remotekey() {
            counterparty_points.payment_point
        } else {
            derive_public_key(
                &self.secp_ctx,
                &per_commitment_point,
                &counterparty_points.payment_point,
            )
                .map_err(|err| {
                    self.internal_error(format!("could not derive counterparty_pubkey: {}", err))
                })?
        };

        let revocation_pubkey = derive_revocation_pubkey(
            secp_ctx,
            &per_commitment_point,
            &counterparty_points.revocation_basepoint,
        )
            .map_err(|err| {
                self.internal_error(format!("could not derive revocation_pubkey: {}", err))
            })?;
        let to_counterparty_pubkey = counterparty_pubkey.clone();
        Ok(CommitmentInfo2 {
            is_counterparty_broadcaster: false,
            to_countersigner_pubkey: to_counterparty_pubkey,
            to_countersigner_value_sat: to_counterparty_value_sat,
            revocation_pubkey,
            to_broadcaster_delayed_pubkey: to_holder_delayed_pubkey,
            to_broadcaster_value_sat: to_holder_value_sat,
            to_self_delay: self.setup.counterparty_to_self_delay,
            offered_htlcs,
            received_htlcs,
        })
    }
    // END NOT TESTED

    /// Phase 1
    pub fn sign_counterparty_commitment_tx(
        &self,
        tx: &bitcoin::Transaction,
        output_witscripts: &Vec<Vec<u8>>,
        remote_per_commitment_point: &PublicKey,
        channel_value_sat: u64,
        payment_hashmap: &Map<[u8; 20], PaymentHash>,
        commitment_number: u64,
    ) -> Result<Vec<u8>, Status> {
        // Set the feerate_per_kw to 0 because it is only used to
        // generate the htlc success/timeout tx signatures and these
        // signatures are discarded.
        let feerate_per_kw = 0;

        if tx.output.len() != output_witscripts.len() {
            // BEGIN NOT TESTED
            return Err(self.invalid_argument("len(tx.output) != len(witscripts)"));
            // END NOT TESTED
        }

        let validator = self
            .node
            .validator_factory
            .make_validator_phase1(self, channel_value_sat);

        // Since we didn't have the value at the real open, validate it now.
        validator
            .validate_channel_open()
            .map_err(|ve| self.validation_error(ve))?;

        // Derive a CommitmentInfo first, convert to CommitmentInfo2 below ...
        let is_counterparty = true;
        let info = validator
            .make_info(
                &self.keys,
                &self.setup,
                is_counterparty,
                tx,
                output_witscripts,
            )
            .map_err(|err| self.validation_error(err))?;

        let offered_htlcs = Self::htlcs_info1_to_info2(payment_hashmap, &info.offered_htlcs)?;
        let received_htlcs = Self::htlcs_info1_to_info2(payment_hashmap, &info.received_htlcs)?;

        let info2 = self.build_counterparty_commitment_info(
            remote_per_commitment_point,
            info.to_broadcaster_value_sat,
            info.to_countersigner_value_sat,
            offered_htlcs,
            received_htlcs,
        )?;

        // TODO(devrandom) - obtain current_height so that we can validate the HTLC CLTV
        let state = ValidatorState { current_height: 0 };
        validator
            .validate_remote_tx(&self.setup, &state, &info2)
            .map_err(|ve| {
                // BEGIN NOT TESTED
                log_debug!(
                    self,
                    "VALIDATION FAILED:\ntx={:#?}\nsetup={:#?}\nstate={:#?}\ninfo={:#?}",
                    &tx,
                    &self.setup,
                    &state,
                    &info2,
                );
                self.validation_error(ve)
                // END NOT TESTED
            })?;

        let htlcs = Self::htlcs_info2_to_oic(info2.offered_htlcs, info2.received_htlcs);

        let commitment_tx = self.make_counterparty_commitment_tx(
            remote_per_commitment_point,
            commitment_number,
            feerate_per_kw,
            info.to_countersigner_value_sat,
            info.to_broadcaster_value_sat,
            htlcs,
        );

        let funding_redeemscript = make_funding_redeemscript(
            &self.keys.pubkeys().funding_pubkey,
            &self.keys.counterparty_pubkeys().funding_pubkey,
        );
        let original_tx_sighash =
            tx.signature_hash(0, &funding_redeemscript, SigHashType::All as u32);
        let recomposed_tx_sighash = commitment_tx
            .trust()
            .built_transaction()
            .transaction
            .signature_hash(0, &funding_redeemscript, SigHashType::All as u32);
        if recomposed_tx_sighash != original_tx_sighash {
            // BEGIN NOT TESTED
            log_debug!(self, "ORIGINAL_TX={:#?}", &tx);
            log_debug!(
                self,
                "RECOMPOSED_TX={:#?}",
                &commitment_tx.trust().built_transaction().transaction
            );
            return Err(
                self.validation_error(ValidationError::Policy("sighash mismatch".to_string()))
            );
            // END NOT TESTED
        }

        // Sign the commitment.  Discard the htlc signatures for now.
        let sigs = self
            .keys
            .sign_counterparty_commitment(&commitment_tx, &self.secp_ctx)
            .map_err(|_| self.internal_error("failed to sign"))?;
        let mut sig = sigs.0.serialize_der().to_vec();
        sig.push(SigHashType::All as u8);

        self.persist()?;

        Ok(sig)
    }

    fn htlcs_info1_to_info2(
        payment_hashmap: &Map<[u8; 20], PaymentHash>,
        htlcs: &Vec<HTLCInfo>,
    ) -> Result<Vec<HTLCInfo2>, Status> {
        let mut htlcs2 = Vec::new();
        for htlc in htlcs.iter() {
            let payment_hash = payment_hashmap
                .get(&htlc.payment_hash_hash)
                .ok_or_else(|| Status::invalid_argument("unmappable htlc payment_hash"))?;
            htlcs2.push(HTLCInfo2 {
                value_sat: htlc.value_sat,
                payment_hash: payment_hash.clone(),
                cltv_expiry: htlc.cltv_expiry,
            });
        }
        Ok(htlcs2)
    }

    pub fn sign_holder_commitment_tx(
        &self,
        tx: &bitcoin::Transaction,
        funding_amount_sat: u64,
    ) -> Result<Signature, Status> {
        sign_commitment(
            &self.secp_ctx,
            &self.keys,
            &self.setup.counterparty_points.funding_pubkey,
            &tx,
            funding_amount_sat,
        ).map_err(|_| Status::internal("failed to sign"))
    }

    /// Phase 1
    pub fn sign_mutual_close_tx(
        &self,
        tx: &bitcoin::Transaction,
        funding_amount_sat: u64,
    ) -> Result<Signature, Status> {
        sign_commitment(
            &self.secp_ctx,
            &self.keys,
            &self.setup.counterparty_points.funding_pubkey,
            &tx,
            funding_amount_sat,
        ).map_err(|_| Status::internal("failed to sign"))
    }

    /// Phase 1
    pub fn sign_holder_htlc_tx(
        &self,
        tx: &bitcoin::Transaction,
        commitment_number: u64,
        opt_per_commitment_point: Option<PublicKey>,
        redeemscript: &Script,
        htlc_amount_sat: u64,
    ) -> Result<Signature, Status> {
        let per_commitment_point = opt_per_commitment_point
            .unwrap_or_else(|| self.get_per_commitment_point(commitment_number));

        let htlc_sighash = Message::from_slice(
            &SigHashCache::new(tx).signature_hash(
                0,
                redeemscript,
                htlc_amount_sat,
                SigHashType::All,
            )[..],
        ).map_err(|_| Status::internal("failed to sighash"))?;

        let htlc_privkey = derive_private_key(
            &self.secp_ctx,
            &per_commitment_point,
            &self.keys.htlc_base_key(),
        ).map_err(|_| Status::internal("failed to derive key"))?;

        let sig = self.secp_ctx.sign(&htlc_sighash, &htlc_privkey);

        self.persist()?;

        Ok(sig)
    }

    /// Phase 1
    pub fn sign_counterparty_htlc_tx(
        &self,
        tx: &bitcoin::Transaction,
        remote_per_commitment_point: &PublicKey,
        redeemscript: &Script,
        htlc_amount_sat: u64,
    ) -> Result<Signature, Status> {
        let sighash_type = if self.setup.option_anchor_outputs() {
            SigHashType::SinglePlusAnyoneCanPay
        } else {
            SigHashType::All
        };

        let htlc_sighash = Message::from_slice(
            &SigHashCache::new(tx).signature_hash(
                0,
                redeemscript,
                htlc_amount_sat,
                sighash_type,
            )[..],
        ).map_err(|_| Status::internal("failed to sighash"))?;

        let htlc_privkey = derive_private_key(
            &self.secp_ctx,
            &remote_per_commitment_point,
            &self.keys.htlc_base_key(),
        ).map_err(|_| Status::internal("failed to derive key"))?;

        Ok(self.secp_ctx.sign(&htlc_sighash, &htlc_privkey))
    }

    // TODO(devrandom) key leaking from this layer
    pub fn get_unilateral_close_key(&self, commitment_point: &Option<PublicKey>) -> Result<SecretKey, Status> {
        Ok(match commitment_point {
            Some(commitment_point) => derive_private_key(
                &self.secp_ctx,
                &commitment_point,
                &self.keys.payment_key(),
            ).map_err(|err| {
                Status::internal(format!("derive_private_key failed: {}", err))
            })?,
            None => {
                // option_static_remotekey in effect
                self.keys.payment_key().clone()
            }
        })
    }
}

#[derive(Copy, Clone)] // NOT TESTED
pub struct NodeConfig {
    pub key_derivation_style: KeyDerivationStyle,
}

/// A signer for one Lightning node.
pub struct Node {
    pub logger: Arc<SyncLogger>,
    pub node_config: NodeConfig,
    pub(crate) keys_manager: MyKeysManager,
    channels: Mutex<Map<ChannelId, Arc<Mutex<ChannelSlot>>>>,
    pub network: Network,
    validator_factory: Box<dyn ValidatorFactory>,
    pub(crate) persister: Arc<dyn Persist>,
}

impl Node {
    pub fn new(
        logger: &Arc<SyncLogger>,
        node_config: NodeConfig,
        seed: &[u8],
        network: Network,
        persister: &Arc<Persist>
    ) -> Node {
        let now = Duration::from_secs(genesis_block(network).header.time as u64);

        Node {
            logger: Arc::clone(logger),
            keys_manager: MyKeysManager::new(
                node_config.key_derivation_style,
                seed,
                network,
                Arc::clone(logger),
                now.as_secs(),
                now.subsec_nanos(),
            ),
            node_config,
            channels: Mutex::new(Map::new()),
            network,
            validator_factory: Box::new(SimpleValidatorFactory {}),
            persister: Arc::clone(persister)
        }
    }

    pub fn get_id(&self) -> PublicKey {
        let secp_ctx = Secp256k1::signing_only();
        PublicKey::from_secret_key(&secp_ctx, &self.keys_manager.get_node_secret())
    }

    #[allow(dead_code)]
    pub(crate) fn invalid_argument(&self, msg: impl Into<String>) -> Status {
        let s = msg.into();
        log_error!(self, "INVALID ARGUMENT: {}", &s);
        #[cfg(feature = "backtrace")]
        log_error!(self, "BACKTRACE:\n{:?}", Backtrace::new());
        Status::invalid_argument(s)
    }

    pub(crate) fn internal_error(&self, msg: impl Into<String>) -> Status {
        let s = msg.into();
        log_error!(self, "INTERNAL ERROR: {}", &s);
        #[cfg(feature = "backtrace")]
        log_error!(self, "BACKTRACE:\n{:?}", Backtrace::new());
        Status::internal(s)
    }

    pub fn new_channel(
        &self,
        opt_channel_id: Option<ChannelId>,
        opt_channel_nonce0: Option<Vec<u8>>,
        arc_self: &Arc<Node>,
    ) -> Result<(ChannelId, Option<ChannelStub>), Status> {
        let channel_id =
            opt_channel_id.unwrap_or_else(|| ChannelId(self.keys_manager.get_channel_id()));
        let channel_nonce0 =
            opt_channel_nonce0.unwrap_or_else(|| channel_id.0.to_vec());
        let mut channels = self.channels.lock().unwrap();
        if channels.contains_key(&channel_id) {
            // BEGIN NOT TESTED
            let msg = format!("channel already exists: {}", &channel_id);
            log_info!(self, "{}", &msg);
            // return Err(self.invalid_argument(&msg));
            return Ok((channel_id, None));
            // END NOT TESTED
        }
        let channel_value_sat = 0; // Placeholder value, not known yet.
        let inmem_keys = self.keys_manager.get_channel_keys_with_id(
            channel_id,
            channel_nonce0.as_slice(),
            channel_value_sat,
        );
        let stub = ChannelStub {
            node: Arc::clone(arc_self),
            nonce: channel_nonce0,
            logger: Arc::clone(&self.logger),
            secp_ctx: Secp256k1::new(),
            keys: EnforcingSigner::new(inmem_keys),
            id0: channel_id,
        };
        // TODO this clone is expensive
        channels.insert(
            channel_id,
            Arc::new(Mutex::new(ChannelSlot::Stub(stub.clone()))),
        );
        self.persister
            .new_channel(&self.get_id(), &stub)
            // This should only fail if the channel was previously persisted
            .expect("channel was in storage but not in memory");
        Ok((channel_id, Some(stub)))
    }

    pub fn restore_channel(
        &self,
        channel_id0: ChannelId,
        channel_id: Option<ChannelId>,
        nonce: Vec<u8>,
        channel_value_sat: u64,
        channel_setup: Option<ChannelSetup>,
        enforcement_state: EnforcementState,
        arc_self: &Arc<Node>,
    ) -> Result<Arc<Mutex<ChannelSlot>>, ()> {
        let mut channels = self.channels.lock().unwrap();
        assert!(!channels.contains_key(&channel_id0));
        let signer = self.keys_manager.get_channel_keys_with_id(
            channel_id0,
            nonce.as_slice(),
            channel_value_sat,
        );
        let mut enforcing_signer = EnforcingSigner::new_with_state(signer, enforcement_state);

        let slot = match channel_setup {
            None => {
                let stub = ChannelStub {
                    node: Arc::clone(arc_self),
                    nonce,
                    logger: Arc::clone(&self.logger),
                    secp_ctx: Secp256k1::new(),
                    keys: enforcing_signer,
                    id0: channel_id0,
                };
                // TODO this clone is expensive
                let slot = Arc::new(Mutex::new(ChannelSlot::Stub(stub.clone())));
                channels.insert(channel_id0, Arc::clone(&slot));
                channel_id.map(|id| channels.insert(id, Arc::clone(&slot)));
                slot
            }
            Some(setup) => {
                let channel_transaction_parameters =
                    Node::channel_setup_to_channel_transaction_parameters(
                        &setup,
                        enforcing_signer.inner().pubkeys(),
                    );
                enforcing_signer.ready_channel(&channel_transaction_parameters);
                let channel = Channel {
                    node: Arc::clone(arc_self),
                    nonce,
                    logger: Arc::clone(&self.logger),
                    secp_ctx: Secp256k1::new(),
                    keys: enforcing_signer,
                    setup,
                    id0: channel_id0,
                    id: channel_id,
                };
                // TODO this clone is expensive
                let slot = Arc::new(Mutex::new(ChannelSlot::Ready(channel.clone())));
                channels.insert(channel_id0, Arc::clone(&slot));
                channel_id.map(|id| channels.insert(id, Arc::clone(&slot)));
                slot
            }
        };
        Ok(slot)
    }

    pub fn restore_node(node_id: &PublicKey,
                        node_entry: NodeEntry,
                        persister: Arc<dyn Persist>,
                        logger: Arc<dyn SyncLogger>) -> Arc<Node> {
        // BEGIN NOT TESTED
        let config = NodeConfig {
            key_derivation_style: KeyDerivationStyle::try_from(node_entry.key_derivation_style)
                .unwrap(),
        };
        let network = Network::from_str(node_entry.network.as_str()).expect("bad network");
        let node = Arc::new(Node::new(
            &logger,
            config,
            node_entry.seed.as_slice(),
            network,
            &persister
        ));
        assert_eq!(&node.get_id(), node_id);
        log_info!(node, "Restore node {}", node_id);
        for (channel_id0, channel_entry) in persister.get_node_channels(node_id) {
            log_info!(node, "  Restore channel {}", channel_id0);
            node.restore_channel(
                channel_id0,
                channel_entry.id,
                channel_entry.nonce,
                channel_entry.channel_value_satoshis,
                channel_entry.channel_setup,
                channel_entry.enforcement_state,
                &node,
            ).expect("restore channel");
        }
        node
    }

    /// Ready a new channel, making it available for use.
    ///
    /// This populates fields that are known later in the channel creation flow,
    /// such as fields that are supplied by the counterparty and funding outpoint.
    ///
    /// * `channel_id0` - the original channel ID supplied to [`Node::new_channel`]
    /// * `opt_channel_id` - the permanent channel ID
    ///
    /// After this call, the channel may be referred to by either ID.
    pub fn ready_channel(
        &self,
        channel_id0: ChannelId,
        opt_channel_id: Option<ChannelId>,
        setup: ChannelSetup,
    ) -> Result<Channel, Status> {
        let chan = {
            let channels = self.channels.lock().unwrap();
            let arcobj = channels.get(&channel_id0).ok_or_else(|| {
                self.invalid_argument(format!("channel does not exist: {}", channel_id0))
            })?;
            let slot = arcobj.lock().unwrap();
            let stub = match &*slot {
                ChannelSlot::Stub(stub) => Ok(stub),
                ChannelSlot::Ready(_) => {
                    Err(self.invalid_argument(format!("channel already ready: {}", channel_id0)))
                }
            }?;
            let mut inmem_keys = stub.channel_keys_with_channel_value(setup.channel_value_sat);
            let holder_pubkeys = inmem_keys.pubkeys();
            let channel_transaction_parameters =
                Node::channel_setup_to_channel_transaction_parameters(&setup, holder_pubkeys);
            inmem_keys.ready_channel(&channel_transaction_parameters);
            Channel {
                node: Arc::clone(&stub.node),
                nonce: stub.nonce.clone(),
                logger: Arc::clone(&stub.logger),
                secp_ctx: stub.secp_ctx.clone(),
                keys: EnforcingSigner::new(inmem_keys),
                setup,
                id0: channel_id0,
                id: opt_channel_id,
            }
        };
        let validator = self.validator_factory.make_validator(&chan);
        validator
            .validate_channel_open()
            .map_err(|ve| chan.validation_error(ve))?;

        let mut channels = self.channels.lock().unwrap();

        // Wrap the ready channel with an arc so we can potentially
        // refer to it multiple times.
        // TODO this clone is expensive
        let arcobj = Arc::new(Mutex::new(ChannelSlot::Ready(chan.clone())));

        // If a permanent channel_id was provided use it, otherwise
        // continue with the initial channel_id0.
        let chan_id = opt_channel_id.unwrap_or(channel_id0);

        // Associate the new ready channel with the channel id.
        channels.insert(chan_id, arcobj.clone());

        // If we are using a new permanent channel_id additionally
        // associate the channel with the original (initial)
        // channel_id as well.
        if channel_id0 != chan_id {
            channels.insert(channel_id0, arcobj.clone());
        }

        self.persister.update_channel(&self.get_id(), &chan)
            .map_err(|_| Status::internal("persist failed"))?;

        Ok(chan)
    }

    fn channel_setup_to_channel_transaction_parameters(
        setup: &ChannelSetup,
        holder_pubkeys: &ChannelPublicKeys,
    ) -> ChannelTransactionParameters {
        let funding_outpoint = Some(chain::transaction::OutPoint {
            txid: setup.funding_outpoint.txid,
            index: setup.funding_outpoint.vout as u16,
        });
        let channel_transaction_parameters = ChannelTransactionParameters {
            holder_pubkeys: holder_pubkeys.clone(),
            holder_selected_contest_delay: setup.holder_to_self_delay,
            is_outbound_from_holder: setup.is_outbound,
            counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
                pubkeys: setup.counterparty_points.clone(),
                selected_contest_delay: setup.counterparty_to_self_delay,
            }),
            funding_outpoint,
        };
        channel_transaction_parameters
    }

    /// Get the node secret key
    /// This function will be eliminated once the node key related items
    /// are implemented.  This includes onion decoding and p2p handshake.
    // TODO leaking secret
    pub fn get_node_secret(&self) -> SecretKey {
        self.keys_manager.get_node_secret()
    }

    /// Get destination redeemScript to encumber static protocol exit points.
    pub fn get_destination_script(&self) -> Script {
        self.keys_manager.get_destination_script()
    }

    /// Get shutdown_pubkey to use as PublicKey at channel closure
    pub fn get_shutdown_pubkey(&self) -> PublicKey {
        self.keys_manager.get_shutdown_pubkey()
    }

    /// Get the layer-1 xprv
    // TODO leaking private key
    pub fn get_account_extended_key(&self) -> &ExtendedPrivKey {
        self.keys_manager.get_account_extended_key()
    }

    /// Get the layer-1 xpub
    pub fn get_account_extended_pubkey(&self) -> ExtendedPubKey {
        let secp_ctx = Secp256k1::signing_only();
        ExtendedPubKey::from_private(&secp_ctx, &self.get_account_extended_key())
    }

    /// Sign a node announcement using the node key
    pub fn sign_node_announcement(&self, na: &Vec<u8>) -> Result<Vec<u8>, Status> {
        let secp_ctx = Secp256k1::signing_only();
        let na_hash = Sha256dHash::hash(na);
        let encmsg = secp256k1::Message::from_slice(&na_hash[..])
            .map_err(|err| self.internal_error(format!("encmsg failed: {}", err)))?;
        let sig = secp_ctx.sign(&encmsg, &self.get_node_secret());
        let res = sig.serialize_der().to_vec();
        Ok(res)
    }

    /// Sign a channel update using the node key
    pub fn sign_channel_update(&self, cu: &Vec<u8>) -> Result<Vec<u8>, Status> {
        let secp_ctx = Secp256k1::signing_only();
        let cu_hash = Sha256dHash::hash(cu);
        let encmsg = secp256k1::Message::from_slice(&cu_hash[..])
            .map_err(|err| self.internal_error(format!("encmsg failed: {}", err)))?;
        let sig = secp_ctx.sign(&encmsg, &self.get_node_secret());
        let res = sig.serialize_der().to_vec();
        Ok(res)
    }

    /// Sign an invoice
    pub fn sign_invoice_in_parts(
        &self,
        data_part: &Vec<u8>,
        human_readable_part: &String,
    ) -> Result<Vec<u8>, Status> {
        use bitcoin::bech32::CheckBase32;

        let hash = invoice_utils::hash_from_parts(
            human_readable_part.as_bytes(),
            &data_part.check_base32().expect("needs to be base32 data"),
        );

        let secp_ctx = Secp256k1::signing_only();
        let encmsg = secp256k1::Message::from_slice(&hash[..])
            .map_err(|err| self.internal_error(format!("encmsg failed: {}", err)))?;
        let node_secret = SecretKey::from_slice(self.get_node_secret().as_ref()).unwrap();
        let sig = secp_ctx.sign_recoverable(&encmsg, &node_secret);
        let (rid, sig) = sig.serialize_compact();
        let mut res = sig.to_vec();
        res.push(rid.to_i32() as u8);
        Ok(res)
    }

    /// Sign an invoice
    pub fn sign_invoice(&self, invoice_preimage: &Vec<u8>) -> RecoverableSignature {
        let secp_ctx = Secp256k1::signing_only();
        let hash = Sha256Hash::hash(invoice_preimage);
        let message = secp256k1::Message::from_slice(&hash).unwrap();
        secp_ctx.sign_recoverable(&message, &self.get_node_secret())
    }

    /// Sign a Lightning message
    pub fn sign_message(&self, message: &Vec<u8>) -> Result<Vec<u8>, Status> {
        let mut buffer = String::from("Lightning Signed Message:").into_bytes();
        buffer.extend(message);
        let secp_ctx = Secp256k1::signing_only();
        let hash = Sha256dHash::hash(&buffer);
        let encmsg = secp256k1::Message::from_slice(&hash[..])
            .map_err(|err| self.internal_error(format!("encmsg failed: {}", err)))?;
        let sig = secp_ctx.sign_recoverable(&encmsg, &self.get_node_secret());
        let (rid, sig) = sig.serialize_compact();
        let mut res = sig.to_vec();
        res.push(rid.to_i32() as u8);
        Ok(res)
    }

    /// Get the channels this node knows about.
    /// Currently, channels are not pruned once closed, but this will change.
    pub fn channels(&self) -> MutexGuard<Map<ChannelId, Arc<Mutex<ChannelSlot>>>> {
        self.channels.lock().unwrap()
    }

    /// Perform an ECDH operation between the node key and a public key
    /// This can be used for onion packet decoding
    pub fn ecdh(&self, other_key: &PublicKey) -> Vec<u8> {
        let our_key = self.keys_manager.get_node_secret();
        let ss = SharedSecret::new(&other_key, &our_key);
        ss[..].to_vec()
    }
}

impl Debug for Node {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str("node")
    }
}