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
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
use secp256k1::key::PublicKey;
use secp256k1::{Secp256k1, Signature};
use bitcoin::util::uint::Uint256;
use bitcoin::util::hash::Sha256dHash;
use bitcoin::network::serialize::{deserialize,serialize};
use bitcoin::blockdata::script::Script;

use std::error::Error;
use std::fmt;
use std::result::Result;

use util::{byte_utils, internal_traits, events};

pub trait MsgEncodable {
	fn encode(&self) -> Vec<u8>;
	#[inline]
	fn encoded_len(&self) -> usize { self.encode().len() }
	#[inline]
	fn encode_with_len(&self) -> Vec<u8> {
		let enc = self.encode();
		let mut res = Vec::with_capacity(enc.len() + 2);
		res.extend_from_slice(&byte_utils::be16_to_array(enc.len() as u16));
		res.extend_from_slice(&enc);
		res
	}
}
#[derive(Debug)]
pub enum DecodeError {
	/// Unknown realm byte in an OnionHopData packet
	UnknownRealmByte,
	/// Failed to decode a public key (ie it's invalid)
	BadPublicKey,
	/// Failed to decode a signature (ie it's invalid)
	BadSignature,
	/// Buffer not of right length (either too short or too long)
	WrongLength,
	/// node_announcement included more than one address of a given type!
	ExtraAddressesPerType,
}
pub trait MsgDecodable: Sized {
	fn decode(v: &[u8]) -> Result<Self, DecodeError>;
}

/// Tracks localfeatures which are only in init messages
#[derive(Clone, PartialEq)]
pub struct LocalFeatures {
	flags: Vec<u8>,
}

impl LocalFeatures {
	pub fn new() -> LocalFeatures {
		LocalFeatures {
			flags: Vec::new(),
		}
	}

	pub fn supports_data_loss_protect(&self) -> bool {
		self.flags.len() > 0 && (self.flags[0] & 3) != 0
	}
	pub fn requires_data_loss_protect(&self) -> bool {
		self.flags.len() > 0 && (self.flags[0] & 1) != 0
	}

	pub fn initial_routing_sync(&self) -> bool {
		self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
	}
	pub fn set_initial_routing_sync(&mut self) {
		if self.flags.len() == 0 {
			self.flags.resize(1, 1 << 3);
		} else {
			self.flags[0] |= 1 << 3;
		}
	}

	pub fn supports_upfront_shutdown_script(&self) -> bool {
		self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
	}
	pub fn requires_upfront_shutdown_script(&self) -> bool {
		self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
	}

	pub fn requires_unknown_bits(&self) -> bool {
		for (idx, &byte) in self.flags.iter().enumerate() {
			if idx != 0 && (byte & 0x55) != 0 {
				return true;
			} else if idx == 0 && (byte & 0x14) != 0 {
				return true;
			}
		}
		return false;
	}

	pub fn supports_unknown_bits(&self) -> bool {
		for (idx, &byte) in self.flags.iter().enumerate() {
			if idx != 0 && byte != 0 {
				return true;
			} else if idx == 0 && (byte & 0xc4) != 0 {
				return true;
			}
		}
		return false;
	}
}

/// Tracks globalfeatures which are in init messages and routing announcements
#[derive(Clone, PartialEq)]
pub struct GlobalFeatures {
	flags: Vec<u8>,
}

impl GlobalFeatures {
	pub fn new() -> GlobalFeatures {
		GlobalFeatures {
			flags: Vec::new(),
		}
	}

	pub fn requires_unknown_bits(&self) -> bool {
		for &byte in self.flags.iter() {
			if (byte & 0x55) != 0 {
				return true;
			}
		}
		return false;
	}

	pub fn supports_unknown_bits(&self) -> bool {
		for &byte in self.flags.iter() {
			if byte != 0 {
				return true;
			}
		}
		return false;
	}
}

pub struct Init {
	pub global_features: GlobalFeatures,
	pub local_features: LocalFeatures,
}

pub struct Ping {
	pub ponglen: u16,
	pub byteslen: u16,
}

pub struct Pong {
	pub byteslen: u16,
}

pub struct OpenChannel {
	pub chain_hash: Sha256dHash,
	pub temporary_channel_id: Uint256,
	pub funding_satoshis: u64,
	pub push_msat: u64,
	pub dust_limit_satoshis: u64,
	pub max_htlc_value_in_flight_msat: u64,
	pub channel_reserve_satoshis: u64,
	pub htlc_minimum_msat: u64,
	pub feerate_per_kw: u32,
	pub to_self_delay: u16,
	pub max_accepted_htlcs: u16,
	pub funding_pubkey: PublicKey,
	pub revocation_basepoint: PublicKey,
	pub payment_basepoint: PublicKey,
	pub delayed_payment_basepoint: PublicKey,
	pub htlc_basepoint: PublicKey,
	pub first_per_commitment_point: PublicKey,
	pub channel_flags: u8,
	pub shutdown_scriptpubkey: Option<Script>,
}

pub struct AcceptChannel {
	pub temporary_channel_id: Uint256,
	pub dust_limit_satoshis: u64,
	pub max_htlc_value_in_flight_msat: u64,
	pub channel_reserve_satoshis: u64,
	pub htlc_minimum_msat: u64,
	pub minimum_depth: u32,
	pub to_self_delay: u16,
	pub max_accepted_htlcs: u16,
	pub funding_pubkey: PublicKey,
	pub revocation_basepoint: PublicKey,
	pub payment_basepoint: PublicKey,
	pub delayed_payment_basepoint: PublicKey,
	pub htlc_basepoint: PublicKey,
	pub first_per_commitment_point: PublicKey,
	pub shutdown_scriptpubkey: Option<Script>,
}

pub struct FundingCreated {
	pub temporary_channel_id: Uint256,
	pub funding_txid: Sha256dHash,
	pub funding_output_index: u16,
	pub signature: Signature,
}

pub struct FundingSigned {
	pub channel_id: Uint256,
	pub signature: Signature,
}

pub struct FundingLocked {
	pub channel_id: Uint256,
	pub next_per_commitment_point: PublicKey,
}

pub struct Shutdown {
	pub channel_id: Uint256,
	pub scriptpubkey: Script,
}

pub struct ClosingSigned {
	pub channel_id: Uint256,
	pub fee_satoshis: u64,
	pub signature: Signature,
}

#[derive(Clone)]
pub struct UpdateAddHTLC {
	pub channel_id: Uint256,
	pub htlc_id: u64,
	pub amount_msat: u64,
	pub payment_hash: [u8; 32],
	pub cltv_expiry: u32,
	pub onion_routing_packet: OnionPacket,
}

#[derive(Clone)]
pub struct UpdateFulfillHTLC {
	pub channel_id: Uint256,
	pub htlc_id: u64,
	pub payment_preimage: [u8; 32],
}

#[derive(Clone)]
pub struct UpdateFailHTLC {
	pub channel_id: Uint256,
	pub htlc_id: u64,
	pub reason: OnionErrorPacket,
}

#[derive(Clone)]
pub struct UpdateFailMalformedHTLC {
	pub channel_id: Uint256,
	pub htlc_id: u64,
	pub sha256_of_onion: [u8; 32],
	pub failure_code: u16,
}

#[derive(Clone)]
pub struct CommitmentSigned {
	pub channel_id: Uint256,
	pub signature: Signature,
	pub htlc_signatures: Vec<Signature>,
}

pub struct RevokeAndACK {
	pub channel_id: Uint256,
	pub per_commitment_secret: [u8; 32],
	pub next_per_commitment_point: PublicKey,
}

pub struct UpdateFee {
	pub channel_id: Uint256,
	pub feerate_per_kw: u32,
}

pub struct ChannelReestablish {
	pub channel_id: Uint256,
	pub next_local_commitment_number: u64,
	pub next_remote_commitment_number: u64,
	pub your_last_per_commitment_secret: Option<[u8; 32]>,
	pub my_current_per_commitment_point: PublicKey,
}

#[derive(Clone)]
pub struct AnnouncementSignatures {
	pub channel_id: Uint256,
	pub short_channel_id: u64,
	pub node_signature: Signature,
	pub bitcoin_signature: Signature,
}

#[derive(Clone)]
pub enum NetAddress {
	IPv4 {
		addr: [u8; 4],
		port: u16,
	},
	IPv6 {
		addr: [u8; 16],
		port: u16,
	},
	OnionV2 {
		addr: [u8; 10],
		port: u16,
	},
	OnionV3 {
		ed25519_pubkey: [u8; 32],
		checksum: u16,
		version: u8,
		port: u16,
	},
}
impl NetAddress {
	fn get_id(&self) -> u8 {
		match self {
			&NetAddress::IPv4 {..} => { 1 },
			&NetAddress::IPv6 {..} => { 2 },
			&NetAddress::OnionV2 {..} => { 3 },
			&NetAddress::OnionV3 {..} => { 4 },
		}
	}
}

pub struct UnsignedNodeAnnouncement {
	pub features: GlobalFeatures,
	pub timestamp: u32,
	pub node_id: PublicKey,
	pub rgb: [u8; 3],
	pub alias: [u8; 32],
	/// List of addresses on which this node is reachable. Note that you may only have up to one
	/// address of each type, if you have more, they may be silently discarded or we may panic!
	pub addresses: Vec<NetAddress>,
}
pub struct NodeAnnouncement {
	pub signature: Signature,
	pub contents: UnsignedNodeAnnouncement,
}

#[derive(PartialEq, Clone)]
pub struct UnsignedChannelAnnouncement {
	pub features: GlobalFeatures,
	pub chain_hash: Sha256dHash,
	pub short_channel_id: u64,
	pub node_id_1: PublicKey,
	pub node_id_2: PublicKey,
	pub bitcoin_key_1: PublicKey,
	pub bitcoin_key_2: PublicKey,
}
#[derive(PartialEq, Clone)]
pub struct ChannelAnnouncement {
	pub node_signature_1: Signature,
	pub node_signature_2: Signature,
	pub bitcoin_signature_1: Signature,
	pub bitcoin_signature_2: Signature,
	pub contents: UnsignedChannelAnnouncement,
}

#[derive(PartialEq, Clone)]
pub struct UnsignedChannelUpdate {
	pub chain_hash: Sha256dHash,
	pub short_channel_id: u64,
	pub timestamp: u32,
	pub flags: u16,
	pub cltv_expiry_delta: u16,
	pub htlc_minimum_msat: u64,
	pub fee_base_msat: u32,
	pub fee_proportional_millionths: u32,
}
#[derive(PartialEq, Clone)]
pub struct ChannelUpdate {
	pub signature: Signature,
	pub contents: UnsignedChannelUpdate,
}

/// Used to put an error message in a HandleError
pub enum ErrorAction {
	/// Indicates an inbound HTLC add resulted in a failure, and the UpdateFailHTLC provided in msg
	/// should be sent back to the sender.
	UpdateFailHTLC {
		msg: UpdateFailHTLC
	},
	/// The peer took some action which made us think they were useless. Disconnect them.
	DisconnectPeer,
	/// The peer did something harmless that we weren't able to process, just log and ignore
	IgnoreError,
}

pub struct HandleError { //TODO: rename me
	pub err: &'static str,
	pub action: Option<ErrorAction>, //TODO: Make this required
}

/// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
/// transaction updates if they were pending.
pub struct CommitmentUpdate {
	pub update_add_htlcs: Vec<UpdateAddHTLC>,
	pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
	pub update_fail_htlcs: Vec<UpdateFailHTLC>,
	pub commitment_signed: CommitmentSigned,
}

pub enum HTLCFailChannelUpdate {
	ChannelUpdateMessage {
		msg: ChannelUpdate,
	},
	ChannelClosed {
		short_channel_id: u64,
	},
}

/// A trait to describe an object which can receive channel messages. Messages MAY be called in
/// paralell when they originate from different their_node_ids, however they MUST NOT be called in
/// paralell when the two calls have the same their_node_id.
pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
	//Channel init:
	fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
	fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
	fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
	fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
	fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;

	// Channl close:
	fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(Option<Shutdown>, Option<ClosingSigned>), HandleError>;
	fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<Option<ClosingSigned>, HandleError>;

	// HTLC handling:
	fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
	fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
	fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<Option<HTLCFailChannelUpdate>, HandleError>;
	fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
	fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
	fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;

	fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;

	// Channel-to-announce:
	fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;

	// Informational:
	/// Indicates a connection to the peer failed/an existing connection was lost. If no connection
	/// is believed to be possible in the future (eg they're sending us messages we don't
	/// understand or indicate they require unknown feature bits), no_connection_possible is set
	/// and any outstanding channels should be failed.
	fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
}

pub trait RoutingMessageHandler : Send + Sync {
	fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<(), HandleError>;
	/// Handle a channel_announcement message, returning true if it should be forwarded on, false
	/// or returning an Err otherwise.
	fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
	fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<(), HandleError>;
	fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
}

pub struct OnionRealm0HopData {
	pub short_channel_id: u64,
	pub amt_to_forward: u64,
	pub outgoing_cltv_value: u32,
	// 12 bytes of 0-padding
}

pub struct OnionHopData {
	pub realm: u8,
	pub data: OnionRealm0HopData,
	pub hmac: [u8; 32],
}
unsafe impl internal_traits::NoDealloc for OnionHopData{}

#[derive(Clone)]
pub struct OnionPacket {
	pub version: u8,
	pub public_key: PublicKey,
	pub hop_data: [u8; 20*65],
	pub hmac: [u8; 32],
}

pub struct DecodedOnionErrorPacket {
	pub hmac: [u8; 32],
	pub failuremsg: Vec<u8>,
	pub pad: Vec<u8>,
}

#[derive(Clone)]
pub struct OnionErrorPacket {
	// This really should be a constant size slice, but the spec lets these things be up to 128KB?
	// (TODO) We limit it in decode to much lower...
	pub data: Vec<u8>,
}

impl Error for DecodeError {
	fn description(&self) -> &str {
		match *self {
			DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
			DecodeError::BadPublicKey => "Invalid public key in packet",
			DecodeError::BadSignature => "Invalid signature in packet",
			DecodeError::WrongLength => "Data was wrong length for packet",
			DecodeError::ExtraAddressesPerType => "More than one address of a single type",
		}
	}
}
impl fmt::Display for DecodeError {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.write_str(self.description())
	}
}

impl fmt::Debug for HandleError {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.write_str(self.err)
	}
}

macro_rules! secp_pubkey {
	( $ctx: expr, $slice: expr ) => {
		match PublicKey::from_slice($ctx, $slice) {
			Ok(key) => key,
			Err(_) => return Err(DecodeError::BadPublicKey)
		}
	};
}

macro_rules! secp_signature {
	( $ctx: expr, $slice: expr ) => {
		match Signature::from_compact($ctx, $slice) {
			Ok(sig) => sig,
			Err(_) => return Err(DecodeError::BadSignature)
		}
	};
}

impl MsgDecodable for LocalFeatures {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 2 { return Err(DecodeError::WrongLength); }
		let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
		if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
		let mut flags = Vec::with_capacity(len);
		flags.extend_from_slice(&v[2..2 + len]);
		Ok(Self {
			flags: flags
		})
	}
}
impl MsgEncodable for LocalFeatures {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(self.flags.len() + 2);
		res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
		res.extend_from_slice(&self.flags[..]);
		res
	}
	fn encoded_len(&self) -> usize { self.flags.len() + 2 }
}

impl MsgDecodable for GlobalFeatures {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 2 { return Err(DecodeError::WrongLength); }
		let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
		if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
		let mut flags = Vec::with_capacity(len);
		flags.extend_from_slice(&v[2..2 + len]);
		Ok(Self {
			flags: flags
		})
	}
}
impl MsgEncodable for GlobalFeatures {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(self.flags.len() + 2);
		res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
		res.extend_from_slice(&self.flags[..]);
		res
	}
	fn encoded_len(&self) -> usize { self.flags.len() + 2 }
}

impl MsgDecodable for Init {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		let global_features = GlobalFeatures::decode(v)?;
		if v.len() < global_features.flags.len() + 4 {
			return Err(DecodeError::WrongLength);
		}
		let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
		Ok(Self {
			global_features: global_features,
			local_features: local_features,
		})
	}
}
impl MsgEncodable for Init {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(self.global_features.flags.len() + self.local_features.flags.len());
		res.extend_from_slice(&self.global_features.encode()[..]);
		res.extend_from_slice(&self.local_features.encode()[..]);
		res
	}
}

impl MsgDecodable for Ping {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 4 {
			return Err(DecodeError::WrongLength);
		}
		let ponglen = byte_utils::slice_to_be16(&v[0..2]);
		let byteslen = byte_utils::slice_to_be16(&v[2..4]);
		if v.len() < 4 + byteslen as usize {
			return Err(DecodeError::WrongLength);
		}
		Ok(Self {
			ponglen,
			byteslen,
		})
	}
}
impl MsgEncodable for Ping {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(self.byteslen as usize + 2);
		res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
		res.resize(2 + self.byteslen as usize, 0);
		res
	}
}

impl MsgDecodable for Pong {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 2 {
			return Err(DecodeError::WrongLength);
		}
		let byteslen = byte_utils::slice_to_be16(&v[0..2]);
		if v.len() < 2 + byteslen as usize {
			return Err(DecodeError::WrongLength);
		}
		Ok(Self {
			byteslen
		})
	}
}
impl MsgEncodable for Pong {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(self.byteslen as usize + 2);
		res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
		res.resize(2 + self.byteslen as usize, 0);
		res
	}
}

impl MsgDecodable for OpenChannel {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 2*32+6*8+4+2*2+6*33+1 {
			return Err(DecodeError::WrongLength);
		}
		let ctx = Secp256k1::without_caps();

		let mut shutdown_scriptpubkey = None;
		if v.len() >= 321 {
			let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
			if v.len() < 321+len {
				return Err(DecodeError::WrongLength);
			}
			shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
		} else if v.len() != 2*32+6*8+4+2*2+6*33+1 { // Message cant have 1 extra byte
			return Err(DecodeError::WrongLength);
		}

		Ok(OpenChannel {
			chain_hash: deserialize(&v[0..32]).unwrap(),
			temporary_channel_id: deserialize(&v[32..64]).unwrap(),
			funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
			push_msat: byte_utils::slice_to_be64(&v[72..80]),
			dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
			max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
			channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
			htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
			feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
			to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
			max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
			funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
			revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
			payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
			delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
			htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
			first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
			channel_flags: v[318],
			shutdown_scriptpubkey: shutdown_scriptpubkey
		})
	}
}
impl MsgEncodable for OpenChannel {
	fn encode(&self) -> Vec<u8> {
		let mut res = match &self.shutdown_scriptpubkey {
			&Some(ref script) => Vec::with_capacity(319 + 2 + script.len()),
			&None => Vec::with_capacity(319),
		};
		res.extend_from_slice(&serialize(&self.chain_hash).unwrap());
		res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap());
		res.extend_from_slice(&byte_utils::be64_to_array(self.funding_satoshis));
		res.extend_from_slice(&byte_utils::be64_to_array(self.push_msat));
		res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
		res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
		res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
		res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
		res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
		res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
		res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
		res.extend_from_slice(&self.funding_pubkey.serialize());
		res.extend_from_slice(&self.revocation_basepoint.serialize());
		res.extend_from_slice(&self.payment_basepoint.serialize());
		res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
		res.extend_from_slice(&self.htlc_basepoint.serialize());
		res.extend_from_slice(&self.first_per_commitment_point.serialize());
		res.push(self.channel_flags);
		if let &Some(ref script) = &self.shutdown_scriptpubkey {
			res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
			res.extend_from_slice(&script[..]);
		}
		res
	}
}

impl MsgDecodable for AcceptChannel {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 32+4*8+4+2*2+6*33 {
			return Err(DecodeError::WrongLength);
		}
		let ctx = Secp256k1::without_caps();

		let mut shutdown_scriptpubkey = None;
		if v.len() >= 272 {
			let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
			if v.len() < 272+len {
				return Err(DecodeError::WrongLength);
			}
			shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
		} else if v.len() != 32+4*8+4+2*2+6*33 { // Message cant have 1 extra byte
			return Err(DecodeError::WrongLength);
		}

		Ok(Self {
			temporary_channel_id: deserialize(&v[0..32]).unwrap(),
			dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
			max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
			channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
			htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
			minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
			to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
			max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
			funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
			revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
			payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
			delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
			htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
			first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
			shutdown_scriptpubkey: shutdown_scriptpubkey
		})
	}
}
impl MsgEncodable for AcceptChannel {
	fn encode(&self) -> Vec<u8> {
		let mut res = match &self.shutdown_scriptpubkey {
			&Some(ref script) => Vec::with_capacity(270 + 2 + script.len()),
			&None => Vec::with_capacity(270),
		};
		res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap()[..]);
		res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
		res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
		res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
		res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
		res.extend_from_slice(&byte_utils::be32_to_array(self.minimum_depth));
		res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
		res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
		res.extend_from_slice(&self.funding_pubkey.serialize());
		res.extend_from_slice(&self.revocation_basepoint.serialize());
		res.extend_from_slice(&self.payment_basepoint.serialize());
		res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
		res.extend_from_slice(&self.htlc_basepoint.serialize());
		res.extend_from_slice(&self.first_per_commitment_point.serialize());
		if let &Some(ref script) = &self.shutdown_scriptpubkey {
			res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
			res.extend_from_slice(&script[..]);
		}
		res
	}
}

impl MsgDecodable for FundingCreated {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 32+32+2+64 {
			return Err(DecodeError::WrongLength);
		}
		let ctx = Secp256k1::without_caps();
		Ok(Self {
			temporary_channel_id: deserialize(&v[0..32]).unwrap(),
			funding_txid: deserialize(&v[32..64]).unwrap(),
			funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
			signature: secp_signature!(&ctx, &v[66..130]),
		})
	}
}
impl MsgEncodable for FundingCreated {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(32+32+2+64);
		res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap()[..]);
		res.extend_from_slice(&serialize(&self.funding_txid).unwrap()[..]);
		res.extend_from_slice(&byte_utils::be16_to_array(self.funding_output_index));
		let secp_ctx = Secp256k1::without_caps();
		res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
		res
	}
}

impl MsgDecodable for FundingSigned {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 32+64 {
			return Err(DecodeError::WrongLength);
		}
		let ctx = Secp256k1::without_caps();
		Ok(Self {
			channel_id: deserialize(&v[0..32]).unwrap(),
			signature: secp_signature!(&ctx, &v[32..96]),
		})
	}
}
impl MsgEncodable for FundingSigned {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(32+64);
		res.extend_from_slice(&serialize(&self.channel_id).unwrap());
		res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps()));
		res
	}
}

impl MsgDecodable for FundingLocked {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 32+33 {
			return Err(DecodeError::WrongLength);
		}
		let ctx = Secp256k1::without_caps();
		Ok(Self {
			channel_id: deserialize(&v[0..32]).unwrap(),
			next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
		})
	}
}
impl MsgEncodable for FundingLocked {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(32+33);
		res.extend_from_slice(&serialize(&self.channel_id).unwrap());
		res.extend_from_slice(&self.next_per_commitment_point.serialize());
		res
	}
}

impl MsgDecodable for Shutdown {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 32 + 2 {
			return Err(DecodeError::WrongLength);
		}
		let scriptlen = byte_utils::slice_to_be16(&v[32..34]) as usize;
		if v.len() < 32 + 2 + scriptlen {
			return Err(DecodeError::WrongLength);
		}
		Ok(Self {
			channel_id: deserialize(&v[0..32]).unwrap(),
			scriptpubkey: Script::from(v[34..34 + scriptlen].to_vec()),
		})
	}
}
impl MsgEncodable for Shutdown {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(32 + 2 + self.scriptpubkey.len());
		res.extend_from_slice(&serialize(&self.channel_id).unwrap());
		res.extend_from_slice(&byte_utils::be16_to_array(self.scriptpubkey.len() as u16));
		res.extend_from_slice(&self.scriptpubkey[..]);
		res
	}
}

impl MsgDecodable for ClosingSigned {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 32 + 8 + 64 {
			return Err(DecodeError::WrongLength);
		}
		let secp_ctx = Secp256k1::without_caps();
		Ok(Self {
			channel_id: deserialize(&v[0..32]).unwrap(),
			fee_satoshis: byte_utils::slice_to_be64(&v[32..40]),
			signature: secp_signature!(&secp_ctx, &v[40..104]),
		})
	}
}
impl MsgEncodable for ClosingSigned {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(32+8+64);
		res.extend_from_slice(&serialize(&self.channel_id).unwrap());
		res.extend_from_slice(&byte_utils::be64_to_array(self.fee_satoshis));
		let secp_ctx = Secp256k1::without_caps();
		res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
		res
	}
}

impl MsgDecodable for UpdateAddHTLC {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 32+8+8+32+4+1+33+20*65+32 {
			return Err(DecodeError::WrongLength);
		}
		let mut payment_hash = [0; 32];
		payment_hash.copy_from_slice(&v[48..80]);
		Ok(Self{
			channel_id: deserialize(&v[0..32]).unwrap(),
			htlc_id: byte_utils::slice_to_be64(&v[32..40]),
			amount_msat: byte_utils::slice_to_be64(&v[40..48]),
			payment_hash,
			cltv_expiry: byte_utils::slice_to_be32(&v[80..84]),
			onion_routing_packet: OnionPacket::decode(&v[84..84+1366])?,
		})
	}
}
impl MsgEncodable for UpdateAddHTLC {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(32+8+8+32+4+1+1366);
		res.extend_from_slice(&serialize(&self.channel_id).unwrap());
		res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
		res.extend_from_slice(&byte_utils::be64_to_array(self.amount_msat));
		res.extend_from_slice(&self.payment_hash);
		res.extend_from_slice(&byte_utils::be32_to_array(self.cltv_expiry));
		res.extend_from_slice(&self.onion_routing_packet.encode()[..]);
		res
	}
}

impl MsgDecodable for UpdateFulfillHTLC {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 32+8+32 {
			return Err(DecodeError::WrongLength);
		}
		let mut payment_preimage = [0; 32];
		payment_preimage.copy_from_slice(&v[40..72]);
		Ok(Self{
			channel_id: deserialize(&v[0..32]).unwrap(),
			htlc_id: byte_utils::slice_to_be64(&v[32..40]),
			payment_preimage,
		})
	}
}
impl MsgEncodable for UpdateFulfillHTLC {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(32+8+32);
		res.extend_from_slice(&serialize(&self.channel_id).unwrap());
		res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
		res.extend_from_slice(&self.payment_preimage);
		res
	}
}

impl MsgDecodable for UpdateFailHTLC {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 32+8 {
			return Err(DecodeError::WrongLength);
		}
		Ok(Self{
			channel_id: deserialize(&v[0..32]).unwrap(),
			htlc_id: byte_utils::slice_to_be64(&v[32..40]),
			reason: OnionErrorPacket::decode(&v[40..])?,
		})
	}
}
impl MsgEncodable for UpdateFailHTLC {
	fn encode(&self) -> Vec<u8> {
		let reason = self.reason.encode();
		let mut res = Vec::with_capacity(32+8+reason.len());
		res.extend_from_slice(&serialize(&self.channel_id).unwrap());
		res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
		res.extend_from_slice(&reason[..]);
		res
	}
}

impl MsgDecodable for UpdateFailMalformedHTLC {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 32+8+32+2 {
			return Err(DecodeError::WrongLength);
		}
		let mut sha256_of_onion = [0; 32];
		sha256_of_onion.copy_from_slice(&v[40..72]);
		Ok(Self{
			channel_id: deserialize(&v[0..32]).unwrap(),
			htlc_id: byte_utils::slice_to_be64(&v[32..40]),
			sha256_of_onion,
			failure_code: byte_utils::slice_to_be16(&v[72..74]),
		})
	}
}
impl MsgEncodable for UpdateFailMalformedHTLC {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(32+8+32+2);
		res.extend_from_slice(&serialize(&self.channel_id).unwrap());
		res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
		res.extend_from_slice(&self.sha256_of_onion);
		res.extend_from_slice(&byte_utils::be16_to_array(self.failure_code));
		res
	}
}

impl MsgDecodable for CommitmentSigned {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 32+64+2 {
			return Err(DecodeError::WrongLength);
		}
		let htlcs = byte_utils::slice_to_be16(&v[96..98]) as usize;
		if v.len() < 32+64+2+htlcs*64 {
			return Err(DecodeError::WrongLength);
		}
		let mut htlc_signatures = Vec::with_capacity(htlcs);
		let secp_ctx = Secp256k1::without_caps();
		for i in 0..htlcs {
			htlc_signatures.push(secp_signature!(&secp_ctx, &v[98+i*64..98+(i+1)*64]));
		}
		Ok(Self {
			channel_id: deserialize(&v[0..32]).unwrap(),
			signature: secp_signature!(&secp_ctx, &v[32..96]),
			htlc_signatures,
		})
	}
}
impl MsgEncodable for CommitmentSigned {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(32+64+2+self.htlc_signatures.len()*64);
		res.extend_from_slice(&serialize(&self.channel_id).unwrap());
		let secp_ctx = Secp256k1::without_caps();
		res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
		res.extend_from_slice(&byte_utils::be16_to_array(self.htlc_signatures.len() as u16));
		for i in 0..self.htlc_signatures.len() {
			res.extend_from_slice(&self.htlc_signatures[i].serialize_compact(&secp_ctx));
		}
		res
	}
}

impl MsgDecodable for RevokeAndACK {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 32+32+33 {
			return Err(DecodeError::WrongLength);
		}
		let mut per_commitment_secret = [0; 32];
		per_commitment_secret.copy_from_slice(&v[32..64]);
		let secp_ctx = Secp256k1::without_caps();
		Ok(Self {
			channel_id: deserialize(&v[0..32]).unwrap(),
			per_commitment_secret,
			next_per_commitment_point: secp_pubkey!(&secp_ctx, &v[64..97]),
		})
	}
}
impl MsgEncodable for RevokeAndACK {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(32+32+33);
		res.extend_from_slice(&serialize(&self.channel_id).unwrap());
		res.extend_from_slice(&self.per_commitment_secret);
		res.extend_from_slice(&self.next_per_commitment_point.serialize());
		res
	}
}

impl MsgDecodable for UpdateFee {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 32+4 {
			return Err(DecodeError::WrongLength);
		}
		Ok(Self {
			channel_id: deserialize(&v[0..32]).unwrap(),
			feerate_per_kw: byte_utils::slice_to_be32(&v[32..36]),
		})
	}
}
impl MsgEncodable for UpdateFee {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(32+4);
		res.extend_from_slice(&serialize(&self.channel_id).unwrap());
		res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
		res
	}
}

impl MsgDecodable for ChannelReestablish {
	fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
		unimplemented!();
	}
}
impl MsgEncodable for ChannelReestablish {
	fn encode(&self) -> Vec<u8> {
		unimplemented!();
	}
}

impl MsgDecodable for AnnouncementSignatures {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 32+8+64*2 {
			return Err(DecodeError::WrongLength);
		}
		let secp_ctx = Secp256k1::without_caps();
		Ok(Self {
			channel_id: deserialize(&v[0..32]).unwrap(),
			short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
			node_signature: secp_signature!(&secp_ctx, &v[40..104]),
			bitcoin_signature: secp_signature!(&secp_ctx, &v[104..168]),
		})
	}
}
impl MsgEncodable for AnnouncementSignatures {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(32+8+64*2);
		res.extend_from_slice(&serialize(&self.channel_id).unwrap());
		res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
		let secp_ctx = Secp256k1::without_caps();
		res.extend_from_slice(&self.node_signature.serialize_compact(&secp_ctx));
		res.extend_from_slice(&self.bitcoin_signature.serialize_compact(&secp_ctx));
		res
	}
}

impl MsgDecodable for UnsignedNodeAnnouncement {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		let features = GlobalFeatures::decode(&v[..])?;
		if v.len() < features.encoded_len() + 4 + 33 + 3 + 32 + 2 {
			return Err(DecodeError::WrongLength);
		}
		let start = features.encoded_len();

		let mut rgb = [0; 3];
		rgb.copy_from_slice(&v[start + 37..start + 40]);

		let mut alias = [0; 32];
		alias.copy_from_slice(&v[start + 40..start + 72]);

		let addrlen = byte_utils::slice_to_be16(&v[start + 72..start + 74]) as usize;
		if v.len() < start + 74 + addrlen {
			return Err(DecodeError::WrongLength);
		}

		let mut addresses = Vec::with_capacity(4);
		let mut read_pos = start + 74;
		loop {
			if v.len() <= read_pos { break; }
			match v[read_pos] {
				0 => { read_pos += 1; },
				1 => {
					if v.len() < read_pos + 1 + 6 {
						return Err(DecodeError::WrongLength);
					}
					if addresses.len() > 0 {
						return Err(DecodeError::ExtraAddressesPerType);
					}
					let mut addr = [0; 4];
					addr.copy_from_slice(&v[read_pos + 1..read_pos + 5]);
					addresses.push(NetAddress::IPv4 {
						addr,
						port: byte_utils::slice_to_be16(&v[read_pos + 5..read_pos + 7]),
					});
					read_pos += 1 + 6;
				},
				2 => {
					if v.len() < read_pos + 1 + 18 {
						return Err(DecodeError::WrongLength);
					}
					if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
						return Err(DecodeError::ExtraAddressesPerType);
					}
					let mut addr = [0; 16];
					addr.copy_from_slice(&v[read_pos + 1..read_pos + 17]);
					addresses.push(NetAddress::IPv6 {
						addr,
						port: byte_utils::slice_to_be16(&v[read_pos + 17..read_pos + 19]),
					});
					read_pos += 1 + 18;
				},
				3 => {
					if v.len() < read_pos + 1 + 12 {
						return Err(DecodeError::WrongLength);
					}
					if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
						return Err(DecodeError::ExtraAddressesPerType);
					}
					let mut addr = [0; 10];
					addr.copy_from_slice(&v[read_pos + 1..read_pos + 11]);
					addresses.push(NetAddress::OnionV2 {
						addr,
						port: byte_utils::slice_to_be16(&v[read_pos + 11..read_pos + 13]),
					});
					read_pos += 1 + 12;
				},
				4 => {
					if v.len() < read_pos + 1 + 37 {
						return Err(DecodeError::WrongLength);
					}
					if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
						return Err(DecodeError::ExtraAddressesPerType);
					}
					let mut ed25519_pubkey = [0; 32];
					ed25519_pubkey.copy_from_slice(&v[read_pos + 1..read_pos + 33]);
					addresses.push(NetAddress::OnionV3 {
						ed25519_pubkey,
						checksum: byte_utils::slice_to_be16(&v[read_pos + 33..read_pos + 35]),
						version: v[read_pos + 35],
						port: byte_utils::slice_to_be16(&v[read_pos + 36..read_pos + 38]),
					});
					read_pos += 1 + 37;
				},
				_ => { break; } // We've read all we can, we dont understand anything higher (and they're sorted)
			}
		}

		let secp_ctx = Secp256k1::without_caps();
		Ok(Self {
			features,
			timestamp: byte_utils::slice_to_be32(&v[start..start + 4]),
			node_id: secp_pubkey!(&secp_ctx, &v[start + 4..start + 37]),
			rgb,
			alias,
			addresses,
		})
	}
}
impl MsgEncodable for UnsignedNodeAnnouncement {
	fn encode(&self) -> Vec<u8> {
		let features = self.features.encode();
		let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len());
		res.extend_from_slice(&features[..]);
		res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
		res.extend_from_slice(&self.node_id.serialize());
		res.extend_from_slice(&self.rgb);
		res.extend_from_slice(&self.alias);
		let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
		let mut addrs_to_encode = self.addresses.clone();
		addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
		addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
		for addr in addrs_to_encode.iter() {
			match addr {
				&NetAddress::IPv4{addr, port} => {
					addr_slice.push(1);
					addr_slice.extend_from_slice(&addr);
					addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
				},
				&NetAddress::IPv6{addr, port} => {
					addr_slice.push(2);
					addr_slice.extend_from_slice(&addr);
					addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
				},
				&NetAddress::OnionV2{addr, port} => {
					addr_slice.push(3);
					addr_slice.extend_from_slice(&addr);
					addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
				},
				&NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
					addr_slice.push(4);
					addr_slice.extend_from_slice(&ed25519_pubkey);
					addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
					addr_slice.push(version);
					addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
				},
			}
		}
		res.extend_from_slice(&byte_utils::be16_to_array(addr_slice.len() as u16));
		res.extend_from_slice(&addr_slice[..]);
		res
	}
}

impl MsgDecodable for NodeAnnouncement {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 64 {
			return Err(DecodeError::WrongLength);
		}
		let secp_ctx = Secp256k1::without_caps();
		Ok(Self {
			signature: secp_signature!(&secp_ctx, &v[0..64]),
			contents: UnsignedNodeAnnouncement::decode(&v[64..])?,
		})
	}
}
impl MsgEncodable for NodeAnnouncement {
	fn encode(&self) -> Vec<u8> {
		let contents = self.contents.encode();
		let mut res = Vec::with_capacity(64 + contents.len());
		let secp_ctx = Secp256k1::without_caps();
		res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
		res.extend_from_slice(&contents);
		res
	}
}

impl MsgDecodable for UnsignedChannelAnnouncement {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		let features = GlobalFeatures::decode(&v[..])?;
		if v.len() < features.encoded_len() + 32 + 8 + 33*4 {
			return Err(DecodeError::WrongLength);
		}
		let start = features.encoded_len();
		let secp_ctx = Secp256k1::without_caps();
		Ok(Self {
			features,
			chain_hash: deserialize(&v[start..start + 32]).unwrap(),
			short_channel_id: byte_utils::slice_to_be64(&v[start + 32..start + 40]),
			node_id_1: secp_pubkey!(&secp_ctx, &v[start + 40..start + 73]),
			node_id_2: secp_pubkey!(&secp_ctx, &v[start + 73..start + 106]),
			bitcoin_key_1: secp_pubkey!(&secp_ctx, &v[start + 106..start + 139]),
			bitcoin_key_2: secp_pubkey!(&secp_ctx, &v[start + 139..start + 172]),
		})
	}
}
impl MsgEncodable for UnsignedChannelAnnouncement {
	fn encode(&self) -> Vec<u8> {
		let features = self.features.encode();
		let mut res = Vec::with_capacity(172 + features.len());
		res.extend_from_slice(&features[..]);
		res.extend_from_slice(&self.chain_hash[..]);
		res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
		res.extend_from_slice(&self.node_id_1.serialize());
		res.extend_from_slice(&self.node_id_2.serialize());
		res.extend_from_slice(&self.bitcoin_key_1.serialize());
		res.extend_from_slice(&self.bitcoin_key_2.serialize());
		res
	}
}

impl MsgDecodable for ChannelAnnouncement {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 64*4 {
			return Err(DecodeError::WrongLength);
		}
		let secp_ctx = Secp256k1::without_caps();
		Ok(Self {
			node_signature_1: secp_signature!(&secp_ctx, &v[0..64]),
			node_signature_2: secp_signature!(&secp_ctx, &v[64..128]),
			bitcoin_signature_1: secp_signature!(&secp_ctx, &v[128..192]),
			bitcoin_signature_2: secp_signature!(&secp_ctx, &v[192..256]),
			contents: UnsignedChannelAnnouncement::decode(&v[256..])?,
		})
	}
}
impl MsgEncodable for ChannelAnnouncement {
	fn encode(&self) -> Vec<u8> {
		let secp_ctx = Secp256k1::without_caps();
		let contents = self.contents.encode();
		let mut res = Vec::with_capacity(64 + contents.len());
		res.extend_from_slice(&self.node_signature_1.serialize_compact(&secp_ctx));
		res.extend_from_slice(&self.node_signature_2.serialize_compact(&secp_ctx));
		res.extend_from_slice(&self.bitcoin_signature_1.serialize_compact(&secp_ctx));
		res.extend_from_slice(&self.bitcoin_signature_2.serialize_compact(&secp_ctx));
		res.extend_from_slice(&contents);
		res
	}
}

impl MsgDecodable for UnsignedChannelUpdate {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 32+8+4+2+2+8+4+4 {
			return Err(DecodeError::WrongLength);
		}
		Ok(Self {
			chain_hash: deserialize(&v[0..32]).unwrap(),
			short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
			timestamp: byte_utils::slice_to_be32(&v[40..44]),
			flags: byte_utils::slice_to_be16(&v[44..46]),
			cltv_expiry_delta: byte_utils::slice_to_be16(&v[46..48]),
			htlc_minimum_msat: byte_utils::slice_to_be64(&v[48..56]),
			fee_base_msat: byte_utils::slice_to_be32(&v[56..60]),
			fee_proportional_millionths: byte_utils::slice_to_be32(&v[60..64]),
		})
	}
}
impl MsgEncodable for UnsignedChannelUpdate {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(64);
		res.extend_from_slice(&self.chain_hash[..]);
		res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
		res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
		res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
		res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
		res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
		res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
		res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
		res
	}
}

impl MsgDecodable for ChannelUpdate {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 128 {
			return Err(DecodeError::WrongLength);
		}
		let secp_ctx = Secp256k1::without_caps();
		Ok(Self {
			signature: secp_signature!(&secp_ctx, &v[0..64]),
			contents: UnsignedChannelUpdate::decode(&v[64..])?,
		})
	}
}
impl MsgEncodable for ChannelUpdate {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(128);
		res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps())[..]);
		res.extend_from_slice(&self.contents.encode()[..]);
		res
	}
}

impl MsgDecodable for OnionRealm0HopData {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 32 {
			return Err(DecodeError::WrongLength);
		}
		Ok(OnionRealm0HopData {
			short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
			amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
			outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
		})
	}
}
impl MsgEncodable for OnionRealm0HopData {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(32);
		res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
		res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
		res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
		res.resize(32, 0);
		res
	}
}

impl MsgDecodable for OnionHopData {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 65 {
			return Err(DecodeError::WrongLength);
		}
		let realm = v[0];
		if realm != 0 {
			return Err(DecodeError::UnknownRealmByte);
		}
		let mut hmac = [0; 32];
		hmac[..].copy_from_slice(&v[33..65]);
		Ok(OnionHopData {
			realm: realm,
			data: OnionRealm0HopData::decode(&v[1..33])?,
			hmac: hmac,
		})
	}
}
impl MsgEncodable for OnionHopData {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(65);
		res.push(self.realm);
		res.extend_from_slice(&self.data.encode()[..]);
		res.extend_from_slice(&self.hmac);
		res
	}
}

impl MsgDecodable for OnionPacket {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 1+33+20*65+32 {
			return Err(DecodeError::WrongLength);
		}
		let mut hop_data = [0; 20*65];
		hop_data.copy_from_slice(&v[34..1334]);
		let mut hmac = [0; 32];
		hmac.copy_from_slice(&v[1334..1366]);
		let secp_ctx = Secp256k1::without_caps();
		Ok(Self {
			version: v[0],
			public_key: secp_pubkey!(&secp_ctx, &v[1..34]),
			hop_data,
			hmac,
		})
	}
}
impl MsgEncodable for OnionPacket {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
		res.push(self.version);
		res.extend_from_slice(&self.public_key.serialize());
		res.extend_from_slice(&self.hop_data);
		res.extend_from_slice(&self.hmac);
		res
	}
}

impl MsgDecodable for DecodedOnionErrorPacket {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 32 + 4 {
			return Err(DecodeError::WrongLength);
		}
		let failuremsg_len = byte_utils::slice_to_be16(&v[32..34]) as usize;
		if v.len() < 32 + 4 + failuremsg_len {
			return Err(DecodeError::WrongLength);
		}
		let padding_len = byte_utils::slice_to_be16(&v[34 + failuremsg_len..]) as usize;
		if v.len() < 32 + 4 + failuremsg_len + padding_len {
			return Err(DecodeError::WrongLength);
		}

		let mut hmac = [0; 32];
		hmac.copy_from_slice(&v[0..32]);
		Ok(Self {
			hmac,
			failuremsg: v[34..34 + failuremsg_len].to_vec(),
			pad: v[36 + failuremsg_len..36 + failuremsg_len + padding_len].to_vec(),
		})
	}
}
impl MsgEncodable for DecodedOnionErrorPacket {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
		res.extend_from_slice(&self.hmac);
		res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
		res.extend_from_slice(&self.failuremsg);
		res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
		res.extend_from_slice(&self.pad);
		res
	}
}

impl MsgDecodable for OnionErrorPacket {
	fn decode(v: &[u8]) -> Result<Self, DecodeError> {
		if v.len() < 2 {
			return Err(DecodeError::WrongLength);
		}
		let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
		if v.len() < 2 + len {
			return Err(DecodeError::WrongLength);
		}
		Ok(Self {
			data: v[2..len+2].to_vec(),
		})
	}
}
impl MsgEncodable for OnionErrorPacket {
	fn encode(&self) -> Vec<u8> {
		let mut res = Vec::with_capacity(2 + self.data.len());
		res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
		res.extend_from_slice(&self.data);
		res
	}
}