2021-01-17 21:45:59 +00:00
|
|
|
#include "time_helpers.h"
|
|
|
|
|
|
|
|
#include <chrono>
|
2021-01-17 21:53:04 +00:00
|
|
|
#include <iostream>
|
2021-01-17 21:45:59 +00:00
|
|
|
|
|
|
|
namespace BareMinimumCrypto {
|
|
|
|
using namespace std;
|
|
|
|
using namespace chrono;
|
|
|
|
|
2021-01-17 23:31:28 +00:00
|
|
|
Instant::Instant (int64_t x): x (x) {}
|
|
|
|
|
|
|
|
Instant Instant::now () {
|
2021-01-17 21:45:59 +00:00
|
|
|
const auto utc_now = system_clock::now ();
|
2021-01-17 23:31:28 +00:00
|
|
|
return Instant {duration_cast <seconds> (utc_now.time_since_epoch ()).count ()};
|
|
|
|
}
|
|
|
|
|
|
|
|
bool TimeRange::contains (Instant x) const {
|
|
|
|
if (not_after < not_before) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (x.x < not_before) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (x.x > not_after) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
int64_t TimeRange::duration () const {
|
|
|
|
return not_after - not_before;
|
|
|
|
}
|
|
|
|
|
|
|
|
TimeRange TimeRange::from_start_and_dur (Instant start, int64_t dur) {
|
|
|
|
return TimeRange {
|
|
|
|
start.x,
|
|
|
|
start.x + dur
|
|
|
|
};
|
2021-01-17 21:45:59 +00:00
|
|
|
}
|
2021-01-17 21:53:04 +00:00
|
|
|
|
|
|
|
// Most tests will use a virtual clock. But just as a smoke test,
|
|
|
|
// make sure real time is realistic.
|
|
|
|
|
|
|
|
int test_time () {
|
2021-01-17 23:31:28 +00:00
|
|
|
const auto now = Instant::now ();
|
2021-01-17 21:53:04 +00:00
|
|
|
|
|
|
|
const auto time_of_writing = 1610844872;
|
2021-01-17 23:31:28 +00:00
|
|
|
const int64_t about_100_years = (int64_t)100 * 365 * 86400;
|
|
|
|
|
|
|
|
const TimeRange tr {
|
|
|
|
time_of_writing,
|
|
|
|
time_of_writing + about_100_years
|
|
|
|
};
|
|
|
|
|
|
|
|
if (! tr.contains (now)) {
|
|
|
|
cerr << "System clock is acting weird" << endl;
|
2021-01-17 21:53:04 +00:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2021-01-17 23:31:28 +00:00
|
|
|
const TimeRange bad_tr {
|
|
|
|
time_of_writing + about_100_years,
|
|
|
|
time_of_writing
|
|
|
|
};
|
|
|
|
|
|
|
|
if (bad_tr.contains (now)) {
|
|
|
|
cerr << "Invalid TimeRange should not contain any Instants" << endl;
|
2021-01-17 21:53:04 +00:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|
2021-01-17 21:45:59 +00:00
|
|
|
}
|