Merge pull request #95 from savil/rm-bitcoin-util-hexbytes
[rust-lightning] / src / chain / transaction.rs
1 use bitcoin::util::hash::Sha256dHash;
2
3 /// A reference to a transaction output.
4 /// Differs from bitcoin::blockdata::transaction::TxOutRef as the index is a u16 instead of usize
5 /// due to LN's restrictions on index values. Should reduce (possibly) unsafe conversions this way.
6 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
7 pub struct OutPoint {
8         /// The referenced transaction's txid.
9         pub txid: Sha256dHash,
10         /// The index of the referenced output in its transaction's vout.
11         pub index: u16,
12 }
13
14 impl OutPoint {
15         /// Creates a new `OutPoint` from the txid an the index.
16         pub fn new(txid: Sha256dHash, index: u16) -> OutPoint {
17                 OutPoint { txid, index }
18         }
19
20         /// Convert an `OutPoint` to a lightning channel id.
21         pub fn to_channel_id(&self) -> [u8; 32] {
22                 let mut res = [0; 32];
23                 res[..].copy_from_slice(&self.txid[..]);
24                 res[30] ^= ((self.index >> 8) & 0xff) as u8;
25                 res[31] ^= ((self.index >> 0) & 0xff) as u8;
26                 res
27         }
28 }
29
30 #[cfg(test)]
31 mod tests {
32         use chain::transaction::OutPoint;
33
34         use bitcoin::blockdata::transaction::Transaction;
35         use bitcoin::network::serialize;
36
37         use hex;
38
39         #[test]
40         fn test_channel_id_calculation() {
41                 let tx: Transaction = serialize::deserialize(&hex::decode("020000000001010e0adef48412e4361325ac1c6e36411299ab09d4f083b9d8ddb55fbc06e1b0c00000000000feffffff0220a1070000000000220020f81d95e040bd0a493e38bae27bff52fe2bb58b93b293eb579c01c31b05c5af1dc072cfee54a3000016001434b1d6211af5551905dc2642d05f5b04d25a8fe80247304402207f570e3f0de50546aad25a872e3df059d277e776dda4269fa0d2cc8c2ee6ec9a022054e7fae5ca94d47534c86705857c24ceea3ad51c69dd6051c5850304880fc43a012103cb11a1bacc223d98d91f1946c6752e358a5eb1a1c983b3e6fb15378f453b76bd00000000").unwrap()[..]).unwrap();
42                 assert_eq!(&OutPoint {
43                         txid: tx.txid(),
44                         index: 0
45                 }.to_channel_id(), &hex::decode("3e88dd7165faf7be58b3c5bb2c9c452aebef682807ea57080f62e6f6e113c25e").unwrap()[..]);
46                 assert_eq!(&OutPoint {
47                         txid: tx.txid(),
48                         index: 1
49                 }.to_channel_id(), &hex::decode("3e88dd7165faf7be58b3c5bb2c9c452aebef682807ea57080f62e6f6e113c25f").unwrap()[..]);
50         }
51 }