304 lines
11 KiB
C++
304 lines
11 KiB
C++
#include "game_server/NetworkProtocol.h"
|
|
#include "game_server/MessageAuth.h"
|
|
#include "LocationState.h"
|
|
#include <cstdlib>
|
|
#include <iostream>
|
|
#include <string>
|
|
|
|
namespace {
|
|
|
|
void require(bool condition, const char* message)
|
|
{
|
|
if (condition) return;
|
|
std::cerr << "NetworkProtocolTests: " << message << '\n';
|
|
std::exit(EXIT_FAILURE);
|
|
}
|
|
|
|
FRG::Vec3fp point(float x, float y, float z)
|
|
{
|
|
return {FRG::fp(x), FRG::fp(y), FRG::fp(z)};
|
|
}
|
|
|
|
bool samePoint(const FRG::Vec3fp& left, const FRG::Vec3fp& right)
|
|
{
|
|
return left.x == right.x && left.y == right.y && left.z == right.z;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
int main()
|
|
{
|
|
FRG::LocationNetworkState locationState;
|
|
nlohmann::json savedLocationState;
|
|
locationState.save(savedLocationState);
|
|
const nlohmann::json original{
|
|
{"schemaVersion", 2},
|
|
{"campaignId", "battle_zone_multiplayer"},
|
|
{"players", {{"player1", {{"hp", 200.0}}}}},
|
|
{"locations", {{"park_korea", {{"state", savedLocationState}}}}}
|
|
};
|
|
FRG::InitialStateMessage initial;
|
|
initial.state = original;
|
|
initial.assignedPlayerId = "player1";
|
|
initial.snapshotTick = 42;
|
|
initial.compatibilityFingerprint = "lockstep-v2:battle_zone_multiplayer";
|
|
initial.sessionSecret = FRG::auth::generateSessionSecretHex();
|
|
const std::string message = FRG::makeInitialStateMessage(initial);
|
|
FRG::InitialStateMessage parsed;
|
|
std::string error;
|
|
require(
|
|
FRG::parseInitialStateMessage(message, parsed, error),
|
|
"valid initial-state envelope was rejected");
|
|
require(parsed.state == original, "state payload did not round trip");
|
|
require(
|
|
parsed.sessionSecret == initial.sessionSecret &&
|
|
parsed.sessionSecret.size() == 64,
|
|
"session secret did not round trip");
|
|
require(parsed.snapshotTick == 42, "snapshot tick did not round trip");
|
|
require(
|
|
parsed.assignedPlayerId == "player1",
|
|
"assigned player did not round trip");
|
|
require(
|
|
!parsed.state["locations"]["park_korea"]["state"].contains("cameraAzimuth") &&
|
|
!parsed.state["locations"]["park_korea"]["state"].contains("cameraInclination"),
|
|
"local camera state leaked into the network payload");
|
|
|
|
FRG::DestinationInputMessage input;
|
|
input.clientSequence = 7;
|
|
input.target = point(1.234f, 0.f, -5.678f);
|
|
FRG::DestinationInputMessage parsedInput;
|
|
require(
|
|
FRG::parseDestinationInputMessage(
|
|
FRG::makeDestinationInputMessage(input), parsedInput, error),
|
|
"destination input did not round trip");
|
|
require(
|
|
parsedInput.clientSequence == 7 &&
|
|
samePoint(parsedInput.target, input.target),
|
|
"destination input was not normalized");
|
|
|
|
FRG::CharacterActionInputMessage actionInput{
|
|
8, "set_target", "hostile_npc"};
|
|
FRG::CharacterActionInputMessage parsedActionInput;
|
|
require(
|
|
FRG::parseCharacterActionInputMessage(
|
|
FRG::makeCharacterActionInputMessage(actionInput),
|
|
parsedActionInput, error),
|
|
"character action input did not round trip");
|
|
require(
|
|
parsedActionInput.clientSequence == 8 &&
|
|
parsedActionInput.action == "set_target" &&
|
|
parsedActionInput.targetId == "hostile_npc",
|
|
"character action input fields did not round trip");
|
|
require(
|
|
!FRG::parseCharacterActionInputMessage(
|
|
R"({"protocolVersion":2,"type":"character_action","payload":{"clientSequence":1,"action":"unknown","targetId":""}})",
|
|
parsedActionInput, error),
|
|
"unknown character action was accepted");
|
|
require(
|
|
!FRG::parseCharacterActionInputMessage(
|
|
R"({"protocolVersion":2,"type":"character_action","payload":{"clientSequence":1,"action":"set_target","targetId":""}})",
|
|
parsedActionInput, error),
|
|
"empty attack target was accepted");
|
|
|
|
FRG::TickMessage tick;
|
|
tick.tickId = 43;
|
|
tick.commands.push_back(FRG::ScheduledDestinationCommand{
|
|
1, "player1", parsedInput.target});
|
|
tick.commands.push_back(FRG::ScheduledCharacterEnabledCommand{
|
|
2, "park_korea", "player2", true});
|
|
tick.commands.push_back(FRG::ScheduledCharacterActionCommand{
|
|
3, "player1", "set_target", "hostile_npc"});
|
|
tick.stateHash = "0123456789abcdef";
|
|
FRG::TickMessage parsedTick;
|
|
require(
|
|
FRG::parseTickMessage(
|
|
FRG::makeTickMessage(tick), parsedTick, error),
|
|
"tick message did not round trip");
|
|
require(
|
|
parsedTick.tickId == 43 && parsedTick.commands.size() == 3 &&
|
|
std::holds_alternative<FRG::ScheduledCharacterEnabledCommand>(
|
|
parsedTick.commands[1]) &&
|
|
std::get<FRG::ScheduledCharacterEnabledCommand>(
|
|
parsedTick.commands[1]).enabled &&
|
|
std::holds_alternative<FRG::ScheduledCharacterActionCommand>(
|
|
parsedTick.commands[2]) &&
|
|
std::get<FRG::ScheduledCharacterActionCommand>(
|
|
parsedTick.commands[2]).targetId == "hostile_npc",
|
|
"tick contents did not round trip");
|
|
|
|
require(
|
|
!FRG::parseInitialStateMessage(
|
|
R"({"protocolVersion":1,"type":"initial_state","payload":{}})",
|
|
parsed, error),
|
|
"unknown protocol version was accepted");
|
|
require(
|
|
!FRG::parseDestinationInputMessage(
|
|
R"({"protocolVersion":2,"type":"command","payload":{}})",
|
|
parsedInput, error),
|
|
"unknown message type was accepted");
|
|
require(
|
|
!FRG::parseInitialStateMessage("not json", parsed, error),
|
|
"malformed JSON was accepted");
|
|
require(
|
|
!FRG::parseDestinationInputMessage(
|
|
R"({"protocolVersion":2,"type":"destination_input","payload":{"clientSequence":1,"target":[1e999,0,0]}})",
|
|
parsedInput, error),
|
|
"non-finite destination was accepted");
|
|
std::string errorCode;
|
|
std::string errorDetail;
|
|
require(
|
|
FRG::parseErrorMessage(
|
|
FRG::makeErrorMessage("server_full", "No slot"),
|
|
errorCode, errorDetail) &&
|
|
errorCode == "server_full" && errorDetail == "No slot",
|
|
"error message did not round trip");
|
|
|
|
nlohmann::json hashState = original;
|
|
hashState["savedAt"] = "first";
|
|
const std::string firstHash = FRG::canonicalStateHash(hashState);
|
|
hashState["savedAt"] = "second";
|
|
require(
|
|
firstHash == FRG::canonicalStateHash(hashState),
|
|
"persistence timestamp changed deterministic hash");
|
|
|
|
FRG::LockstepTimeline timeline(2);
|
|
const std::uint64_t firstSequence =
|
|
timeline.schedule("player1", point(1.f, 0.f, 1.f));
|
|
const std::uint64_t secondSequence =
|
|
timeline.schedule("player2", point(2.f, 0.f, 2.f));
|
|
const FRG::TickMessage emptyTick = timeline.advance();
|
|
require(
|
|
emptyTick.tickId == 1 && emptyTick.commands.empty(),
|
|
"input-delay tick was not empty");
|
|
const FRG::TickMessage commandTick = timeline.advance();
|
|
require(
|
|
commandTick.tickId == 2 && commandTick.commands.size() == 2 &&
|
|
std::get<FRG::ScheduledDestinationCommand>(
|
|
commandTick.commands[0]).commandSequence == firstSequence &&
|
|
std::get<FRG::ScheduledDestinationCommand>(
|
|
commandTick.commands[1]).commandSequence == secondSequence,
|
|
"scheduled commands were not finalized in stable order");
|
|
|
|
timeline.scheduleCharacterEnabled("park_korea", "player2", true);
|
|
timeline.scheduleCharacterAction("player1", "clear_attack_target");
|
|
const FRG::TickMessage presenceTick = timeline.advance();
|
|
require(
|
|
presenceTick.commands.size() == 1 &&
|
|
std::holds_alternative<FRG::ScheduledCharacterEnabledCommand>(
|
|
presenceTick.commands[0]),
|
|
"character enabled command was not scheduled for the next tick");
|
|
const FRG::TickMessage actionTick =
|
|
timeline.advance();
|
|
require(
|
|
actionTick.commands.size() == 1 &&
|
|
std::holds_alternative<FRG::ScheduledCharacterActionCommand>(
|
|
actionTick.commands[0]),
|
|
"character action was not scheduled with input delay");
|
|
|
|
// Primitives against published test vectors.
|
|
{
|
|
const FRG::auth::Digest abc =
|
|
FRG::auth::sha256(FRG::auth::toBytes("abc"));
|
|
require(
|
|
FRG::auth::hexEncode(abc.data(), abc.size()) ==
|
|
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
|
|
"SHA-256 test vector failed");
|
|
const FRG::auth::Digest mac = FRG::auth::hmacSha256(
|
|
FRG::auth::Bytes(20, 0x0b), FRG::auth::toBytes("Hi There"));
|
|
require(
|
|
FRG::auth::hexEncode(mac.data(), mac.size()) ==
|
|
"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7",
|
|
"HMAC-SHA256 RFC 4231 test vector failed");
|
|
require(
|
|
FRG::auth::generateSessionSecretHex() !=
|
|
FRG::auth::generateSessionSecretHex(),
|
|
"session secrets are not random");
|
|
require(
|
|
FRG::auth::deriveMessageKey({1}, FRG::auth::appPepper(), 1) !=
|
|
FRG::auth::deriveMessageKey({1}, FRG::auth::appPepper(), 2),
|
|
"message key does not depend on the sequence");
|
|
}
|
|
|
|
// Signed input messages.
|
|
{
|
|
const std::string secret = FRG::auth::generateSessionSecretHex();
|
|
const std::string otherSecret = FRG::auth::generateSessionSecretHex();
|
|
const std::string signedMessage = FRG::signInputMessage(
|
|
FRG::makeDestinationInputMessage({5, point(1.f, 0.f, 2.f)}), secret);
|
|
std::uint64_t sequence = 0;
|
|
std::string authError;
|
|
require(
|
|
FRG::verifyInputMessage(signedMessage, secret, sequence, authError) &&
|
|
sequence == 5,
|
|
"valid signature was rejected");
|
|
FRG::DestinationInputMessage stillParses;
|
|
require(
|
|
FRG::parseDestinationInputMessage(signedMessage, stillParses, authError),
|
|
"signed message no longer parses");
|
|
require(
|
|
!FRG::verifyInputMessage(signedMessage, otherSecret, sequence, authError),
|
|
"signature verified under another session secret");
|
|
require(
|
|
!FRG::verifyInputMessage(
|
|
FRG::makeDestinationInputMessage({5, point(1.f, 0.f, 2.f)}),
|
|
secret, sequence, authError),
|
|
"unsigned message was accepted");
|
|
nlohmann::json tampered = nlohmann::json::parse(signedMessage);
|
|
tampered["payload"]["target"][0] = 50.0;
|
|
require(
|
|
!FRG::verifyInputMessage(tampered.dump(), secret, sequence, authError),
|
|
"tampered payload was accepted");
|
|
nlohmann::json resequenced = nlohmann::json::parse(signedMessage);
|
|
resequenced["payload"]["clientSequence"] = 6;
|
|
require(
|
|
!FRG::verifyInputMessage(resequenced.dump(), secret, sequence, authError),
|
|
"re-sequenced message was accepted");
|
|
const std::string action = FRG::signInputMessage(
|
|
FRG::makeCharacterActionInputMessage({9, "set_target", "npc_1"}), secret);
|
|
require(
|
|
FRG::verifyInputMessage(action, secret, sequence, authError) &&
|
|
sequence == 9,
|
|
"signed character action was rejected");
|
|
}
|
|
|
|
// Several orders in one frame: only the player's last order survives.
|
|
FRG::LockstepTimeline burst(2);
|
|
burst.schedule("player1", point(1.f, 0.f, 1.f));
|
|
burst.scheduleCharacterAction("player1", "clear_attack_target");
|
|
burst.scheduleCharacterAction("player1", "try_attack_combo");
|
|
burst.schedule("player2", point(9.f, 0.f, 9.f));
|
|
burst.scheduleCharacterAction("player1", "set_target", "npc_1");
|
|
burst.advance();
|
|
const FRG::TickMessage burstTick = burst.advance();
|
|
require(
|
|
burstTick.commands.size() == 3,
|
|
"superseded orders were not coalesced");
|
|
require(
|
|
std::holds_alternative<FRG::ScheduledCharacterActionCommand>(
|
|
burstTick.commands[0]) &&
|
|
std::get<FRG::ScheduledCharacterActionCommand>(
|
|
burstTick.commands[0]).action == "try_attack_combo",
|
|
"combo was dropped or reordered");
|
|
require(
|
|
std::get<FRG::ScheduledDestinationCommand>(
|
|
burstTick.commands[1]).playerId == "player2",
|
|
"another player's order was coalesced away");
|
|
require(
|
|
std::get<FRG::ScheduledCharacterActionCommand>(
|
|
burstTick.commands[2]).action == "set_target",
|
|
"last order did not win");
|
|
|
|
FRG::LockstepTimeline reversed(2);
|
|
reversed.scheduleCharacterAction("player1", "set_target", "npc_1");
|
|
reversed.schedule("player1", point(3.f, 0.f, 3.f));
|
|
reversed.advance();
|
|
const FRG::TickMessage reversedTick = reversed.advance();
|
|
require(
|
|
reversedTick.commands.size() == 1 &&
|
|
std::holds_alternative<FRG::ScheduledDestinationCommand>(
|
|
reversedTick.commands[0]),
|
|
"destination after attack did not replace the attack order");
|
|
|
|
return EXIT_SUCCESS;
|
|
}
|