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
use super::consumption::integer_consumption::*;
use super::consumption::Consumption;
use super::common;
use std::io::{Read, Write};
use proj_crypto::asymmetric::{sign, commitments};
use gmp::mpz::Mpz;
use std::io;
use std::path::Path;
use std::io::BufReader;
use std::io::BufRead;
use std::iter::Iterator;
pub static DEFAULT_PARAMS_PATH: &'static str = "dhparams.txt";
pub fn read_or_gen_params<P: AsRef<Path> + Clone>(path: P) -> commitments::DHParams {
match commitments::read_dhparams(path.clone()) {
Ok(params) => params,
Err(_) => {
let params = commitments::gen_dh_params().unwrap();
let _ = commitments::write_dhparams(¶ms, path);
params
}
}
}
pub struct MeterState<T: Read + Write> {
channel: T,
sk: sign::SecretKey,
params: commitments::DHParams,
}
fn stringify_bytes(bytes: &[u8]) -> String {
let mut ret = String::new();
for byte in bytes {
ret += &format!("{} ", byte);
}
ret
}
fn unstringify_bytes(string: &str) -> Vec<u8> {
let mut ret = Vec::new();
for str in string.split_whitespace() {
ret.push(u8::from_str_radix(str, 10).unwrap());
}
ret
}
fn read_up_to_newline<R: Read>(source: &mut io::Bytes<R>) -> Vec<u8> {
let mut ret: Vec<u8> = Vec::new();
for result in source {
let byte = match result {
Ok(b) => b,
Err(_) => { let ret_clone = ret.clone(); panic!("Error unwrapping in read_up_to_newline. Input up to now was {:?} => {:?}", ret_clone, String::from_utf8(ret)) },
};
if byte == b'\n' {
return ret;
}
ret.push(byte);
}
panic!("left read_up_to_newline loop without finding a newline. ret = {:?}. If you are running the automated test then the client is probably not keeping up with this thread. Increase the thread sleep. Rust lies about the infinite read timeout.", ret);
}
fn meter_consume<W: Write>(params: &commitments::DHParams, sk: &sign::SecretKey, channel: &mut W, consumption: &IntegerConsumption) {
assert!(consumption.is_valid());
let cons_int = consumption.units_consumed;
let a = commitments::random_a(¶ms.1);
let a_str = a.to_str_radix(16);
let commit_context = commitments::CommitmentContext::from_opening((Mpz::from(cons_int), a), params.clone()).unwrap();
let commitment = commit_context.to_commitment();
let commitment_str = commitment.x.to_str_radix(16);
let touple_str = format!("{} {}", cons_int, a_str);
let thing_to_sign = format!("{} {}", commitment_str, consumption.hour_of_week);
let signed_commitment = sign::sign(&thing_to_sign.as_bytes(), &sk);
let message_str = touple_str + "\n" + &stringify_bytes(&signed_commitment) + "\n";
let message = message_str.as_bytes();
match channel.write(&message) {
Ok(s) => assert_eq!(s, message.len()),
Err(e) => panic!("Failed to send the consumption data. The error was {}", e),
};
}
fn customer_read_consumption<R: Read>(channel: &mut R, meter_key: &sign::PublicKey, table: &mut Vec<ConsumptionTableRow>) {
let buf = BufReader::new(channel);
let mut lines = buf.lines();
loop {
let touple_str = match lines.next() {
Some(opt) => {
match opt {
Ok(s) => s,
Err(_) => return,
}
},
None => return,
};
let signed_commitment_str = lines.next().unwrap().unwrap();
let signed_commitment_other = unstringify_bytes(&signed_commitment_str);
let commitment_other_bytes = sign::verify(&signed_commitment_other, meter_key).unwrap();
let commit_other_str = String::from_utf8(commitment_other_bytes).unwrap();
let mut commit_other_iter = commit_other_str.split_whitespace();
let _ = commit_other_iter.next().unwrap();
let other_str = commit_other_iter.next().unwrap();
assert_eq!(None, commit_other_iter.next());
let mut touple_iter = touple_str.split_whitespace();
let cons_str = touple_iter.next().unwrap();
let a_str = touple_iter.next().unwrap();
assert_eq!(None, touple_iter.next());
let cons = i32::from_str_radix(&cons_str, 10).unwrap();
let other = u64::from_str_radix(&other_str, 10).unwrap();
let a = Mpz::from_str_radix(&a_str, 16).unwrap();
let table_row = ConsumptionTableRow {
signed_commitment: signed_commitment_str,
cons: cons,
other: other,
a: a,
};
table.push(table_row);
}
}
impl<T: Read + Write> MeterState<T> {
pub fn new(channel: T, sk: sign::SecretKey, params: commitments::DHParams) -> MeterState<T> {
MeterState {
channel: channel,
sk: sk,
params: params
}
}
pub fn consume(&mut self, consumption: &IntegerConsumption) {
meter_consume(&self.params, &self.sk, &mut self.channel, consumption);
}
}
struct ConsumptionTableRow {
signed_commitment: String,
cons: i32,
other: u64,
a: Mpz,
}
pub struct CustomerState<P: Read + Write, M: Read + Write> {
meter_channel: M,
provider_channel: P,
consumption_table: Vec<ConsumptionTableRow>,
pub prices: Prices,
provider_key: sign::PublicKey,
meter_key: sign::PublicKey,
params: commitments::DHParams,
}
impl<P: Read + Write, M: Read + Write> CustomerState<P, M> {
pub fn new(meter_channel: M, provider_channel: P, prices: Prices, provider_key: sign::PublicKey,
meter_key: sign::PublicKey, params: commitments::DHParams)
-> CustomerState<P, M> {
CustomerState {
meter_channel: meter_channel,
provider_channel: provider_channel,
consumption_table: Vec::new(),
prices: prices,
provider_key: provider_key,
meter_key: meter_key,
params: params,
}
}
pub fn readable_consumption_table(&self) -> String {
let mut out = String::new();
for row in &self.consumption_table {
let row = format!("cons: {}, other: {}\n", row.cons, row.other);
out = out + row.as_str();
}
out
}
pub fn send_billing_information(&mut self) -> i64 {
let mut bill = 0 as i64;
let mut a = Mpz::zero();
if self.consumption_table.len() == 0 {
println!("I can't bill an empty consumption table!");
return 0;
}
for row in &self.consumption_table {
let price = self.prices[(row.other % (24*7)) as usize] as i64;
bill += row.cons as i64 * price;
a = (a + row.a.clone() * price).modulus(&self.params.0);
}
let const_len_part_str = format!("{}\n{}\n{}\n", bill, a.to_str_radix(16), self.consumption_table.len());
let const_len_part = const_len_part_str.as_bytes();
match self.provider_channel.write(&const_len_part) {
Ok(s) => assert_eq!(s, const_len_part.len()),
Err(e) => panic!("Failed to send the constant part of the billing info. The error was {}", e),
};
for row in &self.consumption_table {
let string = format!("{}\n", row.signed_commitment);
let bytes = string.as_bytes();
match self.provider_channel.write(&bytes) {
Ok(s) => assert_eq!(s, bytes.len()),
Err(e) => panic!("Failed to send a signed_commitment to the provider. The error was {}", e),
};
}
self.consumption_table.clear();
bill
}
pub fn read_meter_messages(&mut self) {
customer_read_consumption(&mut self.meter_channel, &self.meter_key, &mut self.consumption_table);
}
pub fn read_provider_messages(&mut self) {
if let Some(new_prices) = common::check_for_new_prices::<P, i32, u64, IntegerConsumption>(&mut self.provider_channel, &self.provider_key) {
self.prices = new_prices;
}
}
}
pub struct ProviderState<T: Read + Write> {
channel: T,
pub prices: Prices,
keys: super::Keys,
params: commitments::DHParams,
bill_total: i64,
}
impl<T: Read + Write> ProviderState<T> {
pub fn new(channel: T, prices: Prices, keys: super::Keys, params: commitments::DHParams) -> ProviderState<T> {
ProviderState {
channel: channel,
prices: prices,
keys: keys,
params: params,
bill_total: 0,
}
}
pub fn pay_bill(&mut self) -> i64 {
let ret = self.bill_total;
self.bill_total = 0;
ret
}
pub fn receive_billing_information(&mut self) {
let buf = BufReader::new(&mut self.channel);
let mut iterator = buf.bytes();
let bill_bytes = read_up_to_newline(&mut iterator);
let a_bytes = read_up_to_newline(&mut iterator);
let length_bytes = read_up_to_newline(&mut iterator);
let bill = i64::from_str_radix(&String::from_utf8(bill_bytes).unwrap(), 10).unwrap();
let a = Mpz::from_str_radix(&String::from_utf8(a_bytes).unwrap(), 16).unwrap();
let length = usize::from_str_radix(&String::from_utf8(length_bytes).unwrap(), 10).unwrap();
let mut commitments = Vec::new();
let mut others = Vec::new();
if length == 0 {
assert_eq!(bill, 0);
return;
}
for _ in 0..length {
let signed_commitment_bytes = read_up_to_newline(&mut iterator);
let signed_commitment = unstringify_bytes(&String::from_utf8(signed_commitment_bytes).unwrap());
let commitment_bytes = sign::verify(&signed_commitment, &self.keys.their_pk).unwrap();
let commit_other_str = String::from_utf8(commitment_bytes).unwrap();
let mut commit_other_iter = commit_other_str.split_whitespace();
let commit_str = commit_other_iter.next().unwrap();
let other_str = commit_other_iter.next().unwrap();
assert_eq!(None, commit_other_iter.next());
let commitment = Mpz::from_str_radix(&commit_str, 16).unwrap();
commitments.push(commitments::Commitment::from_parts(commitment, self.params.0.clone(), false).unwrap());
let other = u64::from_str_radix(&other_str, 10).unwrap();
others.push(other);
}
let expected_commit = commitments::CommitmentContext::from_opening(
(Mpz::from(bill), a), self.params.clone()).unwrap().to_commitment();
let mut calculated_commit = commitments[0].clone() * Mpz::from(self.prices[(others[0] % (24*7)) as usize]);
for i in 1..length {
calculated_commit = calculated_commit + (commitments[i].clone() * Mpz::from(self.prices[(others[i] % (24*7)) as usize]));
}
assert!(expected_commit == calculated_commit);
self.bill_total += bill;
}
pub fn change_prices(&mut self, prices: &Prices) {
common::change_prices::<T, i32, u64, IntegerConsumption>(&mut self.channel, &self.keys.my_sk, prices);
self.prices = *prices;
}
}
#[cfg(test)]
pub mod tests {
use super::super::tests::{random_hour_of_week};
use sodiumoxide;
use super::super::consumption::integer_consumption::*;
use super::super::consumption::Consumption;
use proj_crypto::asymmetric::sign;
use std::thread;
use std::time::Duration;
use std::os::unix::net::*;
use super::super::BillingProtocol;
use super::*;
#[test]
fn stringify() {
let test_vec = vec!(0 as u8, 6, 213, 47, 8, 61, 2, 31, 2, 49, 0, 8, 71, 58, 96, 5);
let string = stringify_bytes(&test_vec);
let res = unstringify_bytes(&string);
assert_eq!(res, test_vec);
}
#[test]
fn meter_consume_message() {
sodiumoxide::init();
let units = super::super::tests::random_positive_i32();
let hour = random_hour_of_week() as u64;
let consumption = IntegerConsumption::new(units, hour);
let mut channel: Vec<u8> = Vec::new();
let params = read_or_gen_params(DEFAULT_PARAMS_PATH);
let (pk, sk) = sign::gen_keypair();
let mut table = Vec::new();
meter_consume(¶ms, &sk, &mut channel, &consumption);
customer_read_consumption(&mut channel.as_slice(), &pk, &mut table);
let ref row = table[0];
assert_eq!(row.cons, units);
assert_eq!(row.other, hour);
}
enum Role<P: Read + Write, M: Read + Write> {
Server(ProviderState<P>),
Client(MeterState<M>, CustomerState<P, M>),
}
pub struct ThreeParty<T: Read + Write> {
role: Role<T, UnixStream>,
}
impl<T: Read + Write> BillingProtocol<T, i64> for ThreeParty<T> {
type Consumption = IntegerConsumption;
type Prices = Prices;
fn null_prices() -> Self::Prices {
[0; 7*24]
}
fn consume(&mut self, consumption: &Self::Consumption) {
let (ref mut meter, ref mut customer) = match self.role {
Role::Client(ref mut m, ref mut c) => (m, c),
_ => panic!("This function should be called on the Client"),
};
meter.consume(consumption);
customer.read_meter_messages();
}
fn send_billing_information(&mut self) {
let ref mut customer = match self.role {
Role::Client(_, ref mut c) => c,
_ => panic!("This function should be called on the Client"),
};
customer.read_provider_messages();
customer.send_billing_information();
}
fn pay_bill(&mut self) -> i64 {
let ref mut provider = match self.role {
Role::Server(ref mut s) => s,
_ => panic!("This function should be called on the Server"),
};
provider.receive_billing_information();
provider.pay_bill()
}
fn change_prices(&mut self, prices: &Prices) {
let ref mut provider = match self.role {
Role::Server(ref mut s) => s,
_ => panic!("This function should be called on the Server"),
};
provider.change_prices(prices);
}
fn new_meter(provider_channel: T, prices: &Prices, keys: super::super::MeterKeys) -> ThreeParty<T> {
let socket_path = "./meter_to_customer_test_socket".to_string();
let socket_path_closure = socket_path.clone();
let connect_thread = move || -> UnixStream {
let mut remaining_tries = 10;
let mut stream_option = None;
while remaining_tries > 0 {
thread::sleep(Duration::from_millis(2));
let socket_path_clone = socket_path_closure.clone();
let result = UnixStream::connect(socket_path_clone);
if result.is_ok() {
stream_option = Some(result.unwrap());
break;
}
remaining_tries = remaining_tries - 1;
};
stream_option.unwrap()
};
let (m_sk, m_pk, p_pk) = match keys {
super::super::MeterKeys::ThreeParty(ms, mp, pp) => (ms, mp, pp),
_ => panic!("Wrong sort of MeterKeys"),
};
let listener = UnixListener::bind(socket_path).unwrap();
let connector = thread::spawn(connect_thread);
let stream1 = listener.accept().unwrap().0;
stream1.set_nonblocking(true).unwrap();
let stream2 = connector.join().unwrap();
stream2.set_nonblocking(true).unwrap();
let params = read_or_gen_params(DEFAULT_PARAMS_PATH);
let meter = MeterState::new(stream1, m_sk, params.clone());
let mut prices_clone = [0 as i32; 7*24];
for i in 0..(7*24) {
prices_clone[i] = prices[i];
}
let customer = CustomerState::new(stream2, provider_channel, prices_clone, p_pk, m_pk, params);
ThreeParty {
role: Role::Client(meter, customer),
}
}
fn new_server(channel: T, keys: super::super::Keys, prices: &Prices) -> ThreeParty<T> {
let params = read_or_gen_params(DEFAULT_PARAMS_PATH);
let mut prices_clone = [0 as i32; 7*24];
for i in 0..(7*24) {
prices_clone[i] = prices[i];
}
ThreeParty {
role: Role::Server( ProviderState::new(channel, prices_clone, keys, params) ),
}
}
}
}