/*
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef FCP_BASE_RANDOM_TOKEN_H_
#define FCP_BASE_RANDOM_TOKEN_H_

#include <stdint.h>

#include <array>
#include <string>
#include <utility>

#include "absl/types/span.h"

namespace fcp {

enum { kRandomTokenSizeInBytes = 16 };

/**
 * A RandomToken is a unique and "unguessable" value, thus usable as a
 * 'password-capability' (even in an adversarial / network context). Each is
 * comprised of 128 random bits, sourced from a CSRNG.
 *
 * The current implementation uses BoringSSL's RAND_bytes. Unless someone calls
 * RAND_enable_fork_unsafe_buffering, it should be well-behaved even under
 * fork(); i.e. tokens should not collide with those generated by new child
 * processes.
 */
class RandomToken {
 public:
  /**
   * Generates a new token. This sources bits from a CSRNG. The returned token
   * can be assumed to have the desired properties (unique and unguessable) -
   * unlike one that was deserialized from an untrusted source.
   */
  static RandomToken Generate();

  /**
   * Deserializes a token, serialized with ToBytes() or ToString().
   * Note that tokens from untrusted sources might not have been generated
   * correctly, so should not be assumed unique and unguessable.
   *
   * Precondition: bytes.size() == kRandomTokenSizeInBytes
   */
  static RandomToken FromBytes(absl::Span<char const> bytes);

  /**
   * Serializes a token, to something usable by FromBytes().
   */
  std::array<char, kRandomTokenSizeInBytes> ToBytes() const;

  /**
   * Serializes a token, to an std::string usable by FromBytes().
   *
   * Postcondition: returned_string.size() == kRandomTokenSizeInBytes.
   */
  std::string ToString() const;

  /**
   * Returns a hex-string representation (suitable for log output etc.)
   */
  std::string ToPrintableString() const;

  constexpr bool operator==(RandomToken other) const {
    return words_[0] == other.words_[0] && words_[1] == other.words_[1];
  }

  constexpr bool operator!=(RandomToken other) const {
    return !(*this == other);
  }

  template <typename H>
  friend H AbslHashValue(H h, RandomToken t) {
    return H::combine(std::move(h), t.words_[0], t.words_[1]);
  }

 private:
  explicit constexpr RandomToken(uint64_t a, uint64_t b) : words_{a, b} {}

  // It would have been nice to write char bytes[16], with alignas(16).
  // Surprisingly, even current compilers were found prone to unrolling
  // byte-by-byte comparison loops etc. This representation yields very compact
  // code.
  uint64_t words_[2];
};

static_assert(sizeof(RandomToken) == kRandomTokenSizeInBytes,
              "Incorrect RandomToken size");

}  // namespace fcp

#endif  // FCP_BASE_RANDOM_TOKEN_H_
