Harden chess against forged packets and lost moves

- Chain values count once and in order; moves need a fresh value
- Game info carries the inviter's chain value; colours come from the invite
- Accepters keep their seed; unconfirmed sends keep the move and resend it
- Check draw accept and timeout claim preconditions; drop unused minutes
- Notify in the background, keep own games under the cap, 16-bit ply
- Sanitise adopted castling rights, guard incoming handling
- Localised square labels and translations for the new strings
- Restore two Korean strings changed by mistake
This commit is contained in:
zjs81 committed 2026-11-22 17:44:28 -07:00
1 parent adead644c7
commit c2877f6875
53 files changed
+1977 -306

No files matched your search

+58 -31
View File
@@ -45,38 +45,42 @@ enum ChessEndReason {
taken,
}
/// One player's identity in a game: their name (unauthenticated) and the
/// hash chain values verified so far.
/// One player's identity in a game: their name (unauthenticated), their
/// chain commitment, and the highest chain index used up so far.
///
/// Values count once and only in order: a value is fresh when its index is
/// above [lastIndex]. Anyone can hash a revealed value back to the lower
/// ones, so once index `i` is used up nothing at or below it is accepted.
class ChessPlayer {
final String name;
final Uint8List commitment;
Uint8List lastValue;
int lastIndex;
ChessPlayer({
required this.name,
required this.commitment,
Uint8List? lastValue,
this.lastIndex = 0,
}) : lastValue = lastValue ?? commitment;
});
/// Accepts [value] when it extends this player's chain, returning true.
bool verifyAndAdvance(Uint8List value) {
final steps = hashChainDistance(value, lastValue);
if (steps == null || steps == 0) return false;
lastValue = value;
lastIndex += steps;
return true;
/// The inviter's record: index 1 is reserved for the game info.
ChessPlayer.inviter({required this.name, required this.commitment})
: lastIndex = 1;
/// Chain index of [value] when it is on this chain and not used up yet,
/// otherwise null. Does not change anything.
int? freshIndex(Uint8List value) {
final index = hashChainDistance(value, commitment);
return index != null && index > lastIndex ? index : null;
}
/// True when [value] is on this player's chain at or after the last
/// verified value (a valid new value or an exact duplicate).
bool owns(Uint8List value) => hashChainDistance(value, lastValue) != null;
/// Marks every value up to [index] as used.
void use(int index) {
if (index > lastIndex) lastIndex = index;
}
Map<String, dynamic> toJson() => {
'name': name,
'commitment': _hex(commitment),
'last': _hex(lastValue),
'index': lastIndex,
};
@@ -88,7 +92,6 @@ class ChessPlayer {
return ChessPlayer(
name: name,
commitment: commitment,
lastValue: _unhex(json['last']) ?? commitment,
lastIndex: json['index'] is int ? json['index'] as int : 0,
);
}
@@ -112,8 +115,12 @@ class ChessGame {
ChessPlayer? white;
ChessPlayer? black;
/// Our own chain seed (hex) when we are a player or the inviter.
/// Our own chain seed (hex) when we posted or accepted the invite. Kept
/// after losing an accept race, in case a later game info lists us.
String? mySeedHex;
/// Next index of our chain to reveal. Never goes back, even after a failed
/// send: the packet may have gone out.
int myNextChainIndex;
/// Which side we play, or null when watching.
@@ -122,6 +129,17 @@ class ChessGame {
/// True when we posted the invite.
bool iAmInviter;
/// False while [white] and [black] come from a game info we could not
/// check, because we never heard the invite.
bool playersConfirmed;
/// Our last move was applied but the radio did not confirm sending it.
bool moveUnconfirmed;
/// Value 1 of the inviter's chain, from the game info, so any player can
/// send the game info again.
Uint8List? inviterInfoValue;
/// Position the move history below starts from: the start position, or a
/// position adopted after missed moves.
String baseFen;
@@ -166,6 +184,9 @@ class ChessGame {
this.myNextChainIndex = 1,
this.mySide,
this.iAmInviter = false,
this.playersConfirmed = true,
this.moveUnconfirmed = false,
this.inviterInfoValue,
String? baseFen,
List<String>? uciSinceBase,
List<String?>? sanMoves,
@@ -199,6 +220,9 @@ class ChessGame {
/// Players are known (we can verify their actions).
bool get hasPlayers => white != null && black != null;
/// We posted or accepted this game.
bool get isMine => iAmInviter || mySeedHex != null;
ChessSide get sideToMove => ChessSide.moverOfPly(ply + 1);
bool get isMyTurn =>
@@ -209,10 +233,12 @@ class ChessGame {
String? nameOf(ChessSide side) => playerOf(side)?.name;
/// Which side's chain [value] belongs to, if any.
ChessSide? sideOwning(Uint8List value) {
if (white?.owns(value) ?? false) return ChessSide.white;
if (black?.owns(value) ?? false) return ChessSide.black;
/// The side whose chain holds [value] as a fresh value, with its index.
(ChessSide, int)? freshSide(Uint8List value) {
for (final side in ChessSide.values) {
final index = playerOf(side)?.freshIndex(value);
if (index != null) return (side, index);
}
return null;
}
@@ -221,11 +247,12 @@ class ChessGame {
return seed == null ? null : HashChain(seed);
}
/// The next value of our chain, advancing the counter.
Uint8List? takeMyChainValue() {
/// The next value of our chain with its index, advancing the counter.
({int index, Uint8List value})? takeMyChainValue() {
final chain = myChain;
if (chain == null || myNextChainIndex > HashChain.length) return null;
return chain.valueAt(myNextChainIndex++);
final index = myNextChainIndex++;
return (index: index, value: chain.valueAt(index));
}
/// Rules engine at the current position, with as much history as we have
@@ -314,12 +341,6 @@ class ChessGame {
/// The packed position for the current [fen].
Uint8List packedPosition() => ChessPositionCodec.encodeFen(fen);
/// Minutes since the game started, for move packets.
int minutesSinceStart(int nowMs) {
final start = startedAtMs ?? createdAtMs;
return ((nowMs - start) ~/ 60000).clamp(0, 0xFFFF);
}
Map<String, dynamic> toJson() => {
'channel': channelId,
'id': gameId,
@@ -334,6 +355,9 @@ class ChessGame {
'nextChain': myNextChainIndex,
if (mySide != null) 'side': mySide!.name,
'inviterSelf': iAmInviter,
if (!playersConfirmed) 'unconfirmed': true,
if (moveUnconfirmed) 'moveUnconfirmed': true,
if (inviterInfoValue != null) 'infoValue': _hex(inviterInfoValue!),
'baseFen': baseFen,
'uci': uciSinceBase,
'san': sanMoves,
@@ -379,6 +403,9 @@ class ChessGame {
myNextChainIndex: _int(json['nextChain']) ?? 1,
mySide: _enumByNameOrNull(ChessSide.values, json['side']),
iAmInviter: json['inviterSelf'] == true,
playersConfirmed: json['unconfirmed'] != true,
moveUnconfirmed: json['moveUnconfirmed'] == true,
inviterInfoValue: _unhex(json['infoValue']),
baseFen: json['baseFen'] as String?,
uciSinceBase: (json['uci'] as List?)?.whereType<String>().toList(),
sanMoves: (json['san'] as List?)?.map((e) => e as String?).toList(),
+29 -24
View File
@@ -60,7 +60,7 @@ enum ChessDeadline {
values.firstWhere((v) => v.code == code, orElse: () => defaultValue);
}
/// A decoded chess packet. [ply] is the half-move number modulo 256.
/// A decoded chess packet. [ply] is a half-move number (see each kind).
sealed class ChessPacket {
final int gameId;
final int ply;
@@ -196,8 +196,8 @@ class ChessAcceptPacket extends ChessPacket {
}
}
/// A declined direct challenge. Not authenticated; only the inviter acts on
/// it, and only for a challenge addressed to [declinerName].
/// A declined direct challenge. Not authenticated, so only the inviter acts
/// on it, and only for a challenge addressed to [declinerName].
class ChessDeclinePacket extends ChessPacket {
final String declinerName;
@@ -220,7 +220,6 @@ class ChessDeclinePacket extends ChessPacket {
/// One half-move. [ply] is the number of the half-move being made (the first
/// move of the game has ply 1). [position] is the packed position after it.
class ChessMovePacket extends ChessPacket {
final int minutes;
final int moveIndex;
final Uint8List chainValue;
final Uint8List position;
@@ -228,7 +227,6 @@ class ChessMovePacket extends ChessPacket {
const ChessMovePacket({
required super.gameId,
required super.ply,
required this.minutes,
required this.moveIndex,
required this.chainValue,
required this.position,
@@ -239,24 +237,30 @@ class ChessMovePacket extends ChessPacket {
@override
void writeBody(BytesBuilder out) {
writeU16(out, minutes);
out
..addByte(moveIndex)
..add(chainValue)
..add(position);
}
/// The same move carrying [value] instead of [chainValue].
ChessMovePacket withChainValue(Uint8List value) => ChessMovePacket(
gameId: gameId,
ply: ply,
moveIndex: moveIndex,
chainValue: value,
position: position,
);
static ChessMovePacket? _read(int id, int ply, GamePacketReader r) {
final minutes = r.u16();
final index = r.u8();
final chain = r.bytes(HashChain.valueBytes);
final position = r.rest();
if (minutes == null || index == null || chain == null) return null;
if (index == null || chain == null) return null;
if (position == null || position.isEmpty) return null;
return ChessMovePacket(
gameId: id,
ply: ply,
minutes: minutes,
moveIndex: index,
chainValue: chain,
position: position,
@@ -265,26 +269,22 @@ class ChessMovePacket extends ChessPacket {
}
/// Resign, draw offer, draw accept, cancel invite or timeout claim: an
/// authenticated action with no other data.
/// authenticated action with no other data. [ply] is the sender's current
/// half-move number.
class ChessActionPacket extends ChessPacket {
@override
final ChessPacketKind kind;
final int minutes;
final Uint8List chainValue;
const ChessActionPacket({
required this.kind,
required super.gameId,
required super.ply,
required this.minutes,
required this.chainValue,
});
@override
void writeBody(BytesBuilder out) {
writeU16(out, minutes);
out.add(chainValue);
}
void writeBody(BytesBuilder out) => out.add(chainValue);
static ChessActionPacket? _read(
ChessPacketKind kind,
@@ -292,25 +292,27 @@ class ChessActionPacket extends ChessPacket {
int ply,
GamePacketReader r,
) {
final minutes = r.u16();
final chain = r.bytes(HashChain.valueBytes);
if (minutes == null || chain == null) return null;
if (chain == null) return null;
return ChessActionPacket(
kind: kind,
gameId: id,
ply: ply,
minutes: minutes,
chainValue: chain,
);
}
}
/// Everything a late spectator needs to follow and verify a game.
/// The inviter's confirmation of who plays: everything a spectator needs to
/// follow and verify a game. [inviterValue] is value 1 of the inviter's
/// chain, which is used for nothing else, so anyone who heard the invite can
/// check that the inviter sent it. [ply] is the sender's current half-move.
class ChessInfoPacket extends ChessPacket {
final int startedAtUnix;
final ChessDeadline deadline;
final Uint8List whiteCommitment;
final Uint8List blackCommitment;
final Uint8List inviterValue;
final String whiteName;
final String blackName;
@@ -321,6 +323,7 @@ class ChessInfoPacket extends ChessPacket {
required this.deadline,
required this.whiteCommitment,
required this.blackCommitment,
required this.inviterValue,
required this.whiteName,
required this.blackName,
});
@@ -333,9 +336,9 @@ class ChessInfoPacket extends ChessPacket {
writeU32(out, startedAtUnix);
out
..addByte(deadline.code)
..addByte(0) // flags, reserved
..add(whiteCommitment)
..add(blackCommitment);
..add(blackCommitment)
..add(inviterValue);
writeShortString(out, whiteName);
writeShortString(out, blackName);
}
@@ -343,13 +346,14 @@ class ChessInfoPacket extends ChessPacket {
static ChessInfoPacket? _read(int id, int ply, GamePacketReader r) {
final started = r.u32();
final deadline = r.u8();
r.u8(); // flags
final white = r.bytes(HashChain.valueBytes);
final black = r.bytes(HashChain.valueBytes);
final inviterValue = r.bytes(HashChain.valueBytes);
final whiteName = r.shortString();
final blackName = r.shortString();
if (started == null || deadline == null || white == null) return null;
if (black == null || whiteName == null || blackName == null) return null;
if (black == null || inviterValue == null) return null;
if (whiteName == null || blackName == null) return null;
return ChessInfoPacket(
gameId: id,
ply: ply,
@@ -357,6 +361,7 @@ class ChessInfoPacket extends ChessPacket {
deadline: ChessDeadline.fromCode(deadline),
whiteCommitment: white,
blackCommitment: black,
inviterValue: inviterValue,
whiteName: whiteName,
blackName: blackName,
);
+30 -9
View File
@@ -83,7 +83,8 @@ abstract final class ChessPositionCodec {
/// Unpacks [bytes] into a FEN with [fullMoveNumber]. Returns null when the
/// bytes are malformed (wrong length for the occupancy, bad piece codes).
/// Does not check that the position is legal.
/// Castling and en-passant rights that the pieces rule out are dropped;
/// otherwise the position is not checked for legality.
static String? decodeToFen(Uint8List bytes, {required int fullMoveNumber}) {
if (bytes.length < _fixedBytes) return null;
final squares = <int>[];
@@ -123,17 +124,37 @@ abstract final class ChessPositionCodec {
final state = bytes[8] | (bytes[9] << 8);
final blackToMove = state & 1 != 0;
// Square indices: a1 = 0, e1 = 4, h1 = 7, a8 = 56, e8 = 60, h8 = 63.
final castling = StringBuffer();
if (state & (1 << 1) != 0) castling.write('K');
if (state & (1 << 2) != 0) castling.write('Q');
if (state & (1 << 3) != 0) castling.write('k');
if (state & (1 << 4) != 0) castling.write('q');
if (state & (1 << 1) != 0 && board[4] == 'K' && board[7] == 'R') {
castling.write('K');
}
if (state & (1 << 2) != 0 && board[4] == 'K' && board[0] == 'R') {
castling.write('Q');
}
if (state & (1 << 3) != 0 && board[60] == 'k' && board[63] == 'r') {
castling.write('k');
}
if (state & (1 << 4) != 0 && board[60] == 'k' && board[56] == 'r') {
castling.write('q');
}
final epFile = (state >> 5) & 0x0F;
if (epFile > 8) return null;
final ep = epFile == 0
? '-'
: '${String.fromCharCode('a'.codeUnitAt(0) + epFile - 1)}'
'${blackToMove ? 3 : 6}';
var ep = '-';
if (epFile != 0) {
final file = epFile - 1;
// The pawn that just moved two squares, and the two squares it passed.
final pawnSq = (blackToMove ? 3 : 4) * 8 + file;
final passed = (blackToMove ? 2 : 5) * 8 + file;
final start = (blackToMove ? 1 : 6) * 8 + file;
if (board[pawnSq] == (blackToMove ? 'P' : 'p') &&
board[passed] == null &&
board[start] == null) {
ep =
'${String.fromCharCode('a'.codeUnitAt(0) + file)}'
'${blackToMove ? 3 : 6}';
}
}
final halfmove = (state >> 9) & 0x7F;
return '${rows.join('/')} ${blackToMove ? 'b' : 'w'} '
+412 -174
View File
@@ -1,8 +1,9 @@
import 'dart:async';
import 'dart:math';
import 'dart:typed_data';
import 'package:crypto/crypto.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import '../hash_chain.dart';
import 'chess_game.dart';
@@ -14,8 +15,8 @@ import 'chess_store.dart';
/// Chess games played and watched on channels.
///
/// Packets arrive through [ChessLink.incoming]; every handler is idempotent,
/// so duplicates and repeats are harmless. Our own actions are sent first
/// and applied locally once the radio accepted them.
/// so duplicates and repeats are harmless. Each chain value counts once: the
/// first packet heard with it uses it up.
class ChessService extends ChangeNotifier {
static const Duration inviteLifetime = Duration(hours: 24);
static const Duration timeoutGrace = Duration(minutes: 10);
@@ -29,6 +30,7 @@ class ChessService extends ChangeNotifier {
final Random _random;
final Duration _answerDelayMin;
final Duration _answerDelayMax;
final bool Function() _isForeground;
final Map<String, ChessGame> _games = {};
final Set<String> _sending = {};
@@ -47,11 +49,13 @@ class ChessService extends ChangeNotifier {
Duration answerDelayMin = const Duration(seconds: 2),
Duration answerDelayMax = const Duration(seconds: 10),
bool startHousekeeping = true,
bool Function()? isForeground,
}) : store = store ?? ChessStore(),
_clock = clock ?? DateTime.now,
_random = random ?? Random.secure(),
_answerDelayMin = answerDelayMin,
_answerDelayMax = answerDelayMax {
_answerDelayMax = answerDelayMax,
_isForeground = isForeground ?? _appResumed {
_sub = link.incoming.listen(handleIncoming);
link.addListener(_onLinkChanged);
_loadScope(link.storageScope);
@@ -65,6 +69,15 @@ class ChessService extends ChangeNotifier {
int get _now => _clock().millisecondsSinceEpoch;
static bool _appResumed() {
try {
final state = WidgetsBinding.instance.lifecycleState;
return state == null || state == AppLifecycleState.resumed;
} catch (_) {
return true;
}
}
// ---- queries ---------------------------------------------------------------
/// Games on [channelId], newest activity first.
@@ -72,9 +85,19 @@ class ChessService extends ChangeNotifier {
_games.values.where((g) => g.channelId == channelId).toList()
..sort((a, b) => b.lastActivityMs.compareTo(a.lastActivityMs));
/// Live games plus open invites on [channelId].
int openCountForChannel(String channelId) =>
_games.values.where((g) => g.channelId == channelId && g.isOpen).length;
/// Live games plus open invites on [channelId], as the games sheet lists
/// them.
int openCountForChannel(String channelId) => _games.values
.where((g) => g.channelId == channelId && g.isOpen && isListed(g))
.length;
/// False for an open challenge between two other people, which the games
/// sheet does not show.
bool isListed(ChessGame game) =>
game.status != ChessGameStatus.invite ||
game.iAmInviter ||
game.targetName == null ||
_isMe(game.targetName);
ChessGame? game(String channelId, int gameId) =>
_games[ChessGame.gameKey(channelId, gameId)];
@@ -101,7 +124,8 @@ class ChessService extends ChangeNotifier {
return at != null && _clock().isAfter(at.add(timeoutGrace));
}
/// The screen showing [game] (no notifications for it), or null.
/// The screen showing [game] (no notifications for it while the app is in
/// the foreground), or null.
set viewing(ChessGame? game) => _viewingKey = game?.key;
// ---- our actions -----------------------------------------------------------
@@ -129,9 +153,15 @@ class ChessService extends ChangeNotifier {
status: ChessGameStatus.invite,
deadline: deadline,
colourPreference: colour,
inviter: ChessPlayer(name: link.selfName, commitment: chain.commitment),
inviter: ChessPlayer.inviter(
name: link.selfName,
commitment: chain.commitment,
),
targetName: targetName,
mySeedHex: bytesToHex(chain.seed),
// Value 1 is the game info's; actions start at 2.
myNextChainIndex: 2,
inviterInfoValue: chain.valueAt(1),
iAmInviter: true,
createdAtMs: _now,
);
@@ -143,27 +173,39 @@ class ChessService extends ChangeNotifier {
Future<bool> accept(ChessGame game) async {
if (game.status != ChessGameStatus.invite || game.iAmInviter) return false;
final chain = HashChain.generate(_random);
final packet = ChessAcceptPacket(
gameId: game.gameId,
commitment: chain.commitment,
accepterName: link.selfName,
);
if (!await _send(game, packet)) return false;
if (isSending(game) || !link.canSend) return false;
// Reuse the chain of an earlier attempt: that accept may have gone out.
game.mySeedHex ??= bytesToHex(HashChain.generate(_random).seed);
// Waiting from now on, so a confirmation heard mid-send is ours.
game
..mySeedHex = bytesToHex(chain.seed)
..myNextChainIndex = 1
..status = ChessGameStatus.starting
..lastActivityMs = _now;
_changed();
return true;
final ok = await _send(
game,
ChessAcceptPacket(
gameId: game.gameId,
commitment: game.myChain!.commitment,
accepterName: link.selfName,
),
);
if (!ok && game.status == ChessGameStatus.starting) {
game.status = ChessGameStatus.invite;
_changed();
}
return ok;
}
/// Re-sends our accept while waiting for the inviter's confirmation.
/// Re-sends our accept while waiting for the inviter's confirmation, or
/// after a game info listed someone else. The inviter answers with the
/// game info, which lists us if ours was the accept that counted.
Future<bool> resendAccept(ChessGame game) async {
if (game.status != ChessGameStatus.starting) return false;
final chain = game.myChain;
if (chain == null) return false;
if (chain == null || game.iAmInviter) return false;
final waiting =
game.status == ChessGameStatus.starting ||
(game.status == ChessGameStatus.active && !game.isPlayer);
if (!waiting) return false;
return _send(
game,
ChessAcceptPacket(
@@ -193,40 +235,45 @@ class ChessService extends ChangeNotifier {
}, allowedStatus: ChessGameStatus.invite);
/// Plays [uci] (e.g. `e2e4`, `e7e8q`).
///
/// Returns false when the radio did not confirm the send. The move is
/// still applied then, since it may have gone out; [requestUpdate] sends
/// it again.
Future<bool> makeMove(ChessGame game, String uci) async {
if (!game.isMyTurn || isSending(game)) return false;
if (!game.isMyTurn || isSending(game) || !link.canSend) return false;
final legal = game.legalUci();
final index = legal.indexOf(uci);
if (index < 0 || index > 255) return false;
final value = game.takeMyChainValue();
if (value == null) return false;
// Work on a copy of the position so a failed send changes nothing.
final probe = ChessGame.fromJson(game.toJson())!;
probe.applyUci(uci);
if (!probe.applyUci(uci)) return false;
final chain = game.takeMyChainValue();
if (chain == null) return false;
final packet = ChessMovePacket(
gameId: game.gameId,
ply: probe.ply & 0xFF,
minutes: game.minutesSinceStart(_now),
ply: probe.ply,
moveIndex: index,
chainValue: value,
chainValue: chain.value,
position: probe.packedPosition(),
);
if (!await _send(game, packet)) {
game.myNextChainIndex--;
return false;
final plyBefore = game.ply;
final ok = await _send(game, packet);
if (game.status != ChessGameStatus.active || game.ply != plyBefore) {
_changed();
return ok;
}
game.applyUci(uci);
game.playerOf(game.mySide!)?.verifyAndAdvance(value);
game.playerOf(game.mySide!)?.use(chain.index);
game
..lastMovePacket = packet.encode()
..lastMoveAtMs = _now;
..lastMoveAtMs = _now
..moveUnconfirmed = !ok;
_touch(game);
return true;
return ok;
}
Future<bool> resign(ChessGame game) =>
_sendAction(game, ChessPacketKind.resign, (g, side) {
g.finish(ChessEndReason.resignation, winner: side.other);
g.finish(ChessEndReason.resignation, winner: side!.other);
});
Future<bool> offerDraw(ChessGame game) =>
@@ -235,7 +282,8 @@ class ChessService extends ChangeNotifier {
});
Future<bool> acceptDraw(ChessGame game) {
if (game.drawOfferedBy == null || game.drawOfferedBy == game.mySide) {
final side = game.mySide;
if (side == null || game.drawOfferedBy != side.other) {
return Future.value(false);
}
return _sendAction(game, ChessPacketKind.drawAccept, (g, _) {
@@ -250,15 +298,25 @@ class ChessService extends ChangeNotifier {
});
}
/// Asks the players for whatever we are missing: the game info when we
/// cannot verify the players, the latest move otherwise.
/// Gets a stuck game moving. While we wait for the opponent after our own
/// move, sends that move again (the opponent answers with theirs if we
/// missed it). Otherwise asks the players for what we are missing: the
/// game info when we cannot verify the players, and the latest move.
Future<bool> requestUpdate(ChessGame game) {
if (game.status == ChessGameStatus.starting) return resendAccept(game);
if (game.status == ChessGameStatus.starting ||
(game.status == ChessGameStatus.active &&
!game.isPlayer &&
game.isMine)) {
return resendAccept(game);
}
if (_latestMoveIsMine(game) && game.status == ChessGameStatus.active) {
return _resendLatestMove(game);
}
return _send(
game,
ChessRequestPacket(
gameId: game.gameId,
ply: game.ply & 0xFF,
ply: game.ply,
wantsInfo: !game.hasPlayers,
wantsLatestMove: true,
),
@@ -273,44 +331,81 @@ class ChessService extends ChangeNotifier {
Future<bool> _sendAction(
ChessGame game,
ChessPacketKind kind,
void Function(ChessGame game, ChessSide side) apply, {
void Function(ChessGame game, ChessSide? side) apply, {
ChessGameStatus allowedStatus = ChessGameStatus.active,
}) async {
if (game.status != allowedStatus || isSending(game)) return false;
if (!link.canSend) return false;
final side = game.mySide;
if (side == null && !(kind == ChessPacketKind.cancel && game.iAmInviter)) {
return false;
}
final value = game.takeMyChainValue();
if (value == null) return false;
final packet = ChessActionPacket(
kind: kind,
gameId: game.gameId,
ply: game.ply & 0xFF,
minutes: game.minutesSinceStart(_now),
chainValue: value,
final record = kind == ChessPacketKind.cancel
? (game.iAmInviter ? game.inviter : null)
: (side == null ? null : game.playerOf(side));
if (record == null) return false;
final chain = game.takeMyChainValue();
if (chain == null) return false;
// Used up even if the send fails: the packet may have gone out.
record.use(chain.index);
final ok = await _send(
game,
ChessActionPacket(
kind: kind,
gameId: game.gameId,
ply: game.ply,
chainValue: chain.value,
),
);
if (!await _send(game, packet)) {
game.myNextChainIndex--;
if (!ok || game.status != allowedStatus) {
_changed();
return false;
}
if (side != null) {
game.playerOf(side)?.verifyAndAdvance(value);
apply(game, side);
} else {
game.inviter?.verifyAndAdvance(value);
apply(game, ChessSide.white);
}
apply(game, side);
_touch(game);
return true;
}
Future<bool> _send(ChessGame game, ChessPacket packet) async {
bool _latestMoveIsMine(ChessGame game) =>
game.isPlayer &&
game.ply > 0 &&
ChessSide.moverOfPly(game.ply) == game.mySide &&
game.lastMovePacket != null;
/// Sends our latest move again. After we revealed a later chain value
/// (a draw offer, say), receivers refuse the old value, so the move goes
/// out with the next value instead.
Future<bool> _resendLatestMove(ChessGame game) async {
final raw = game.lastMovePacket;
final chain = game.myChain;
final old = raw == null ? null : ChessPacket.decode(raw);
if (old is! ChessMovePacket || chain == null || !link.canSend) {
return false;
}
var packet = raw!;
final latest = chain.valueAt(game.myNextChainIndex - 1);
if (!bytesEqual(old.chainValue, latest)) {
final next = game.takeMyChainValue();
if (next == null) return false;
game.playerOf(game.mySide!)?.use(next.index);
packet = old.withChainValue(next.value).encode();
game.lastMovePacket = packet;
_changed();
}
final ok = await _sendRaw(game, packet);
if (ok && game.moveUnconfirmed) {
game.moveUnconfirmed = false;
_changed();
}
return ok;
}
Future<bool> _send(ChessGame game, ChessPacket packet) =>
_sendRaw(game, packet.encode());
Future<bool> _sendRaw(ChessGame game, Uint8List payload) async {
if (!link.canSend) return false;
_sending.add(game.key);
notifyListeners();
try {
return await link.send(game.channelId, packet.encode());
return await link.send(game.channelId, payload);
} finally {
_sending.remove(game.key);
if (!_disposed) notifyListeners();
@@ -328,10 +423,25 @@ class ChessService extends ChangeNotifier {
@visibleForTesting
void handleIncoming(ChessIncoming incoming) {
try {
_handle(incoming);
} catch (e) {
// A malformed packet must never break the stream listener.
debugPrint('Chess: ignored packet: $e');
}
}
void _handle(ChessIncoming incoming) {
final packet = ChessPacket.decode(incoming.payload);
if (packet == null) return;
final channelId = incoming.channelId;
final existing = game(channelId, packet.gameId);
if (existing != null &&
(packet is ChessInfoPacket ||
(packet is ChessMovePacket && packet.ply >= existing.ply))) {
// Someone answered; our own pending answer is no longer needed.
_pendingAnswers.remove(existing.key)?.cancel();
}
final changed = switch (packet) {
ChessInvitePacket p => _onInvite(channelId, existing, p),
ChessAcceptPacket p => _onAccept(existing, p),
@@ -341,11 +451,6 @@ class ChessService extends ChangeNotifier {
ChessInfoPacket p => _onInfo(channelId, existing, p),
ChessRequestPacket p => _onRequest(existing, p),
};
if ((packet is ChessInfoPacket || packet is ChessMovePacket) &&
existing != null) {
// Someone answered; our own pending answer is no longer needed.
_pendingAnswers.remove(existing.key)?.cancel();
}
if (changed) _changed();
}
@@ -357,7 +462,10 @@ class ChessService extends ChangeNotifier {
status: ChessGameStatus.invite,
deadline: p.deadline,
colourPreference: p.colour,
inviter: ChessPlayer(name: p.inviterName, commitment: p.commitment),
inviter: ChessPlayer.inviter(
name: p.inviterName,
commitment: p.commitment,
),
targetName: p.targetName,
createdAtMs: _now,
);
@@ -371,16 +479,10 @@ class ChessService extends ChangeNotifier {
bool _onAccept(ChessGame? game, ChessAcceptPacket p) {
if (game == null) return false;
if (game.iAmInviter && game.status == ChessGameStatus.active) {
// A repeated accept: the accepter may have missed our confirmation.
final accepted = game.playerOf(game.mySide!.other);
if (accepted != null && bytesEqual(accepted.commitment, p.commitment)) {
_scheduleAnswer(
game,
info: true,
latestMove: game.ply > 0,
immediate: true,
);
}
// A repeated accept: the accepter missed our confirmation, or lost to
// another accept without hearing it. The game info and the latest
// move answer both. Rate-limited like any answer.
_scheduleAnswer(game, info: true, latestMove: game.ply > 0);
return false;
}
if (game.status != ChessGameStatus.invite) return false;
@@ -421,29 +523,65 @@ class ChessService extends ChangeNotifier {
}
bool _onDecline(ChessGame? game, ChessDeclinePacket p) {
if (game == null || game.status != ChessGameStatus.invite) return false;
// Anyone can send a decline, so only the inviter acts on it.
if (game == null || !game.iAmInviter) return false;
if (game.status != ChessGameStatus.invite) return false;
final target = game.targetName;
if (target == null || !_sameName(target, p.declinerName)) return false;
game.finish(ChessEndReason.declined);
game.lastActivityMs = _now;
if (game.iAmInviter) {
_notify(game, link.l10n.chess_notifyDeclined(p.declinerName));
}
game
..finish(ChessEndReason.declined)
..lastActivityMs = _now;
_notify(game, link.l10n.chess_notifyDeclined(p.declinerName));
return true;
}
bool _onInfo(String channelId, ChessGame? game, ChessInfoPacket p) {
if (game != null && game.iAmInviter) return false; // We send these.
final inviter = game?.inviter;
if (inviter != null &&
!bytesEqual(inviter.commitment, p.whiteCommitment) &&
!bytesEqual(inviter.commitment, p.blackCommitment)) {
return false; // Not from this game's inviter.
if (game?.status == ChessGameStatus.finished) return false;
// Value 1 of the inviter's chain hashes to the inviter's commitment.
final step = hashChainStep(p.inviterValue);
final ChessSide inviterSide;
if (bytesEqual(step, p.whiteCommitment)) {
inviterSide = ChessSide.white;
} else if (bytesEqual(step, p.blackCommitment)) {
inviterSide = ChessSide.black;
} else {
return false;
}
final white = ChessPlayer(name: p.whiteName, commitment: p.whiteCommitment);
final black = ChessPlayer(name: p.blackName, commitment: p.blackCommitment);
final inviterWhite = inviterSide == ChessSide.white;
final inviterCommitment = inviterWhite
? p.whiteCommitment
: p.blackCommitment;
final accepterCommitment = inviterWhite
? p.blackCommitment
: p.whiteCommitment;
final known = game?.inviter;
if (known != null) {
if (!bytesEqual(known.commitment, inviterCommitment)) return false;
// Colours follow from the invite; don't take the packet's word.
final expected = _inviterIsWhite(
game!.colourPreference,
inviterCommitment,
accepterCommitment,
);
if (expected != inviterWhite) return false;
}
final inviter =
known ??
ChessPlayer.inviter(
name: inviterWhite ? p.whiteName : p.blackName,
commitment: inviterCommitment,
);
final accepter = ChessPlayer(
name: inviterWhite ? p.blackName : p.whiteName,
commitment: accepterCommitment,
);
final white = inviterWhite ? inviter : accepter;
final black = inviterWhite ? accepter : inviter;
final startedAtMs = p.startedAtUnix * 1000;
if (game == null) {
// We never heard the invite, so nothing ties these players to it.
final created = ChessGame(
channelId: channelId,
gameId: p.gameId,
@@ -451,8 +589,10 @@ class ChessService extends ChangeNotifier {
deadline: p.deadline,
white: white,
black: black,
playersConfirmed: false,
inviterInfoValue: p.inviterValue,
createdAtMs: _now,
startedAtMs: p.startedAtUnix * 1000,
startedAtMs: startedAtMs,
hasPosition: p.ply == 0,
ply: p.ply,
sanMoves: List<String?>.filled(p.ply, null, growable: true),
@@ -461,45 +601,85 @@ class ChessService extends ChangeNotifier {
return true;
}
final mine = game.myChain?.commitment;
final listsMe = mine != null && bytesEqual(mine, accepterCommitment);
switch (game.status) {
case ChessGameStatus.invite:
_start(game, white: white, black: black, mySide: null);
game.startedAtMs = p.startedAtUnix * 1000;
return true;
case ChessGameStatus.starting:
final mine = game.myChain?.commitment;
ChessSide? side;
if (mine != null && bytesEqual(mine, p.whiteCommitment)) {
side = ChessSide.white;
} else if (mine != null && bytesEqual(mine, p.blackCommitment)) {
side = ChessSide.black;
final accepted = game.mySeedHex != null;
_start(
game,
white: white,
black: black,
mySide: listsMe ? inviterSide.other : null,
);
game
..startedAtMs = startedAtMs
..inviterInfoValue = p.inviterValue;
if (!listsMe && p.ply > 0) {
// Watching a game already under way: the board comes with the
// next move.
game
..ply = p.ply
..hasPosition = false
..sanMoves = List<String?>.filled(p.ply, null, growable: true);
}
if (side == null) {
// Someone else's accept won. Keep watching the game.
game.mySeedHex = null;
_start(game, white: white, black: black, mySide: null);
if (listsMe && inviterSide == ChessSide.black) {
_notify(game, link.l10n.chess_notifyGameStartedYourMove);
} else if (accepted && !listsMe) {
// Someone else's accept won. Keep watching, and keep our chain in
// case a later game info lists us after all.
_notify(game, link.l10n.chess_notifyTaken);
} else {
_start(game, white: white, black: black, mySide: side);
if (side == ChessSide.white) {
_notify(game, link.l10n.chess_notifyGameStartedYourMove);
}
}
game.startedAtMs = p.startedAtUnix * 1000;
return true;
case ChessGameStatus.active:
if (game.hasPlayers) return false;
if (game.mySide == null && listsMe) {
// An earlier game info listed someone else; this one lists us.
// Whoever sent it, it puts us against the real inviter.
game
..white = white
..black = black
..mySide = inviterSide.other
..playersConfirmed = true
..inviterInfoValue = p.inviterValue
..lastActivityMs = _now;
return true;
}
if (game.hasPlayers) return false; // First heard wins.
// Followed from a move. Our inviter record, if any, must stay on
// the side we saw it move for.
for (final side in ChessSide.values) {
final seen = game.playerOf(side);
if (seen != null && identical(seen, known) && side != inviterSide) {
return false;
}
}
game
..white = white
..black = black
..startedAtMs ??= p.startedAtUnix * 1000
..playersConfirmed = known != null
..deadline = p.deadline
..inviterInfoValue = p.inviterValue
..startedAtMs ??= startedAtMs
..lastActivityMs = _now;
_useLastMoveValue(game);
return true;
case ChessGameStatus.finished:
return false;
}
}
/// Uses up the chain value of the move we followed before we knew the
/// players.
void _useLastMoveValue(ChessGame game) {
final raw = game.lastMovePacket;
final move = raw == null ? null : ChessPacket.decode(raw);
if (move is! ChessMovePacket) return;
final player = game.playerOf(ChessSide.moverOfPly(move.ply));
final index = player?.freshIndex(move.chainValue);
if (index != null) player!.use(index);
}
void _start(
ChessGame game, {
required ChessPlayer white,
@@ -522,13 +702,12 @@ class ChessService extends ChangeNotifier {
ChessMovePacket p,
Uint8List raw,
) {
final ply = p.ply;
if (ply < 1) return false;
final mover = ChessSide.moverOfPly(ply);
if (game == null) {
// A game we never heard start: follow it from this position.
final fullPly = p.ply == 0 ? 256 : p.ply;
final fen = ChessPositionCodec.decodeToFen(
p.position,
fullMoveNumber: fullPly ~/ 2 + 1,
);
final fen = _decodePosition(p);
if (fen == null || !isValidFen(fen)) return false;
final created = ChessGame(
channelId: channelId,
@@ -536,37 +715,44 @@ class ChessService extends ChangeNotifier {
status: ChessGameStatus.active,
deadline: ChessDeadline.none,
createdAtMs: _now,
)..adoptPosition(fen, fullPly);
)..adoptPosition(fen, ply);
created
..lastMovePacket = raw
..lastMoveAtMs = _now;
_games[created.key] = created;
return true;
}
if (game.status == ChessGameStatus.invite) {
// We missed the accept and confirmation; follow from here.
game
..status = ChessGameStatus.active
..startedAtMs = _now;
switch (game.status) {
case ChessGameStatus.finished:
case ChessGameStatus.starting: // Wait for the inviter's confirmation.
return false;
case ChessGameStatus.invite:
return _onMoveBeforeStart(game, p, raw);
case ChessGameStatus.active:
break;
}
if (game.status != ChessGameStatus.active) return false;
final fullPly = _unwrapPly(game.ply, p.ply);
if (fullPly <= game.ply) return false; // Old or duplicate.
final mover = ChessSide.moverOfPly(fullPly);
if (game.mySide == mover) return false; // Our own move echoed.
if (game.isPlayer && ply < game.ply) {
// The opponent is behind (our reply got lost); they need our move.
_scheduleAnswer(game, info: false, latestMove: true);
}
final player = game.playerOf(mover);
if (player != null && !player.owns(p.chainValue)) return false;
int? index;
if (player != null) {
index = player.freshIndex(p.chainValue);
if (index == null) return false; // Forged, replayed or already used.
}
if (ply < game.ply || (ply == game.ply && game.hasPosition)) {
// A move we have, sent again with a new value: just use the value up.
if (index != null) player!.use(index);
return index != null;
}
final fen = ChessPositionCodec.decodeToFen(
p.position,
fullMoveNumber: fullPly ~/ 2 + 1,
);
final fen = _decodePosition(p);
if (fen == null) return false;
var applied = false;
if (fullPly == game.ply + 1 && game.hasPosition) {
if (ply == game.ply + 1 && game.hasPosition) {
final legal = game.legalUci();
if (p.moveIndex < legal.length) {
final probe = ChessGame.fromJson(game.toJson())!;
@@ -576,21 +762,24 @@ class ChessService extends ChangeNotifier {
applied = true;
}
}
if (!applied && game.isPlayer) return false; // Does not match our board.
// Does not match our board. The value stays unused, so the real move
// can still be accepted if this one was forged.
if (!applied && game.isPlayer) return false;
} else if (game.isPlayer && game.hasPosition) {
return false; // Players cannot skip moves.
}
if (!applied) {
if (!isValidFen(fen)) return false;
game.adoptPosition(fen, fullPly);
game.adoptPosition(fen, ply);
}
player?.verifyAndAdvance(p.chainValue);
if (index != null) player!.use(index);
game
..lastMovePacket = raw
..lastMoveAtMs = _now
..lastActivityMs = _now;
if (game.isPlayer) {
game.moveUnconfirmed = false; // Their move answers ours.
final opponent = game.nameOf(mover) ?? '';
final san = game.sanMoves.isEmpty ? null : game.sanMoves.last;
if (game.status == ChessGameStatus.finished) {
@@ -602,58 +791,108 @@ class ChessService extends ChangeNotifier {
return true;
}
/// A move for an invite we watched but never saw start. Only the
/// inviter's chain can prove the game began; the other player stays
/// unknown until the game info.
bool _onMoveBeforeStart(ChessGame game, ChessMovePacket p, Uint8List raw) {
if (game.isMine) return false; // Ours, or waiting for our confirmation.
final inviter = game.inviter;
final index = inviter?.freshIndex(p.chainValue);
if (index == null) return false;
final fen = _decodePosition(p);
if (fen == null || !isValidFen(fen)) return false;
inviter!.use(index);
if (ChessSide.moverOfPly(p.ply) == ChessSide.white) {
game.white = inviter;
} else {
game.black = inviter;
}
game
..status = ChessGameStatus.active
..startedAtMs = _now
..adoptPosition(fen, p.ply);
game
..lastMovePacket = raw
..lastMoveAtMs = _now
..lastActivityMs = _now;
return true;
}
static String? _decodePosition(ChessMovePacket p) =>
ChessPositionCodec.decodeToFen(
p.position,
fullMoveNumber: p.ply ~/ 2 + 1,
);
bool _onAction(ChessGame? game, ChessActionPacket p) {
if (game == null) return false;
if (p.kind == ChessPacketKind.cancel) {
final inviter = game.inviter;
if (game.status != ChessGameStatus.invite || inviter == null) {
if (game.iAmInviter) return false;
if (game.status != ChessGameStatus.invite &&
game.status != ChessGameStatus.starting) {
return false;
}
if (!inviter.verifyAndAdvance(p.chainValue)) return false;
final inviter = game.inviter;
final index = inviter?.freshIndex(p.chainValue);
if (index == null) return false;
inviter!.use(index);
game
..finish(ChessEndReason.cancelled)
..lastActivityMs = _now;
return true;
}
if (game.status != ChessGameStatus.active) return false;
final side = game.sideOwning(p.chainValue);
if (side == null || side == game.mySide) return false;
if (!game.playerOf(side)!.verifyAndAdvance(p.chainValue)) return false;
final found = game.freshSide(p.chainValue);
if (found == null) return false;
final (side, index) = found;
if (side == game.mySide) return false;
// The value is genuine and now used up, whether or not the action
// applies to the game as we see it.
game.playerOf(side)!.use(index);
game.lastActivityMs = _now;
final current = p.ply == game.ply;
final name = game.nameOf(side) ?? '';
switch (p.kind) {
case ChessPacketKind.resign:
game.finish(ChessEndReason.resignation, winner: side.other);
if (game.isPlayer) _notify(game, link.l10n.chess_notifyResigned(name));
case ChessPacketKind.drawOffer:
if (!current) break;
game.drawOfferedBy = side;
if (game.isPlayer) {
_notify(game, link.l10n.chess_notifyDrawOffered(name));
}
case ChessPacketKind.drawAccept:
if (!current || game.drawOfferedBy != side.other) break;
game.finish(ChessEndReason.drawAgreed);
if (game.isPlayer) {
_notify(game, link.l10n.chess_notifyDrawAccepted(name));
}
case ChessPacketKind.timeoutClaim:
// Only the side waiting for a move can claim.
if (game.hasPosition && game.sideToMove == side) return false;
if (!current || !_deadlinePassed(game, side)) break;
game.finish(ChessEndReason.timeout, winner: side);
if (game.isPlayer) _notify(game, link.l10n.chess_notifyTimeout(name));
default:
return false;
break;
}
game.lastActivityMs = _now;
return true;
}
/// Whether [claimer]'s opponent is to move and the deadline has passed
/// here since the last move. No grace: the claimer already waited it out,
/// and our clock may run behind theirs.
bool _deadlinePassed(ChessGame game, ChessSide claimer) {
final d = game.deadline.duration;
if (d == null || game.sideToMove == claimer) return false;
return _now - game.lastMoveAtMs >= d.inMilliseconds;
}
bool _onRequest(ChessGame? game, ChessRequestPacket p) {
if (game == null || !game.isPlayer) return false;
if (game.status == ChessGameStatus.starting) return false;
final behind = _unwrapPly(game.ply, p.ply) < game.ply;
_scheduleAnswer(
game,
info: p.wantsInfo,
latestMove: p.wantsLatestMove && behind,
latestMove: p.wantsLatestMove && p.ply < game.ply,
);
return false;
}
@@ -688,9 +927,12 @@ class ChessService extends ChangeNotifier {
// Confirmations are not answers to a request; they don't count.
if (!immediate) game.lastAnsweredRequestAtMs = _now;
if (info) await _sendInfo(game);
if (!latestMove) return;
final move = game.lastMovePacket;
if (latestMove && move != null && link.canSend) {
await link.send(game.channelId, move);
if (_latestMoveIsMine(game)) {
await _resendLatestMove(game);
} else if (move != null) {
await _sendRaw(game, move);
}
});
}
@@ -698,16 +940,18 @@ class ChessService extends ChangeNotifier {
Future<void> _sendInfo(ChessGame game) async {
final white = game.white;
final black = game.black;
if (white == null || black == null) return;
final value = game.inviterInfoValue;
if (white == null || black == null || value == null) return;
await _send(
game,
ChessInfoPacket(
gameId: game.gameId,
ply: game.ply & 0xFF,
ply: game.ply,
startedAtUnix: (game.startedAtMs ?? game.createdAtMs) ~/ 1000,
deadline: game.deadline,
whiteCommitment: white.commitment,
blackCommitment: black.commitment,
inviterValue: value,
whiteName: white.name,
blackName: black.name,
),
@@ -716,13 +960,6 @@ class ChessService extends ChangeNotifier {
// ---- helpers ---------------------------------------------------------------
/// The full ply nearest [known] whose low byte is [wire].
static int _unwrapPly(int known, int wire) {
var delta = (wire - known) & 0xFF;
if (delta >= 128) delta -= 256;
return known + delta;
}
/// Colour rule for invites: a fixed preference wins, "random" uses bit 0
/// of SHA-256(inviter commitment ‖ accepter commitment).
static bool _inviterIsWhite(
@@ -740,16 +977,17 @@ class ChessService extends ChangeNotifier {
}
}
bool _isMe(String? name) =>
name != null &&
link.selfName.isNotEmpty &&
_sameName(name, link.selfName);
/// Whether [name] is our advert name (case and spacing aside).
bool isSelf(String name) =>
link.selfName.isNotEmpty && _sameName(name, link.selfName);
bool _isMe(String? name) => name != null && isSelf(name);
static bool _sameName(String a, String b) =>
a.trim().toLowerCase() == b.trim().toLowerCase();
void _notify(ChessGame game, String text) {
if (game.key == _viewingKey) return;
if (game.key == _viewingKey && _isForeground()) return;
link.notify(game.channelId, text);
}
@@ -792,9 +1030,9 @@ class ChessService extends ChangeNotifier {
if (_games.length > maxStoredGames) {
final byAge = _games.values.toList()
..sort((a, b) {
// Our open games last.
final ao = a.isOpen && a.isPlayer ? 1 : 0;
final bo = b.isOpen && b.isPlayer ? 1 : 0;
// Our open games (including our invites) last.
final ao = a.isOpen && a.isMine ? 1 : 0;
final bo = b.isOpen && b.isMine ? 1 : 0;
if (ao != bo) return ao - bo;
return a.lastActivityMs.compareTo(b.lastActivityMs);
});
+17 -1
View File
@@ -197,6 +197,22 @@ class _ChessBoardViewState extends State<ChessBoardView> {
);
}
/// Screen reader label of an occupied square, e.g. "e4: Pawn, white".
static String _pieceLabel(BuildContext context, String square, String piece) {
final l10n = context.l10n;
final name = switch (piece.toLowerCase()) {
'k' => l10n.chess_pieceKing,
'q' => l10n.chess_pieceQueen,
'r' => l10n.chess_pieceRook,
'b' => l10n.chess_pieceBishop,
'n' => l10n.chess_pieceKnight,
_ => l10n.chess_piecePawn,
};
return piece == piece.toUpperCase()
? l10n.chess_squareWhitePiece(square, name)
: l10n.chess_squareBlackPiece(square, name);
}
Widget _square(
BuildContext context, {
required ColorScheme scheme,
@@ -225,7 +241,7 @@ class _ChessBoardViewState extends State<ChessBoardView> {
behavior: HitTestBehavior.opaque,
onTap: () => _onTap(square),
child: Semantics(
label: piece == null ? square : '$square $piece',
label: piece == null ? square : _pieceLabel(context, square, piece),
button: isTarget || (_interactive && piece != null),
selected: isSelected,
child: SizedBox(
+6 -1
View File
@@ -267,7 +267,12 @@ class _StatusCard extends StatelessWidget {
),
);
}
if (!game.hasPlayers) lines.add(l10n.chess_statusUnverified);
if (game.moveUnconfirmed) lines.add(l10n.chess_statusMoveUnconfirmed);
if (!game.hasPlayers) {
lines.add(l10n.chess_statusUnverified);
} else if (!game.playersConfirmed) {
lines.add(l10n.chess_statusPlayersUnchecked);
}
}
return MeshCard(
child: Column(
+20 -6
View File
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../helpers/snack_bar_builder.dart';
import '../../../l10n/app_localizations.dart';
import '../../../l10n/l10n.dart';
import '../../../models/channel.dart';
import '../../../utils/radio_guard.dart';
@@ -96,8 +97,7 @@ class _ChessGamesSheetBody extends StatelessWidget {
(g) =>
g.status == ChessGameStatus.invite &&
!g.iAmInviter &&
(g.targetName == null ||
_sameName(g.targetName!, service.selfName)),
service.isListed(g),
)
.toList();
final live = games
@@ -170,9 +170,6 @@ class _ChessGamesSheetBody extends StatelessWidget {
}
}
bool _sameName(String a, String b) =>
a.trim().toLowerCase() == b.trim().toLowerCase();
class _ActionCard extends StatelessWidget {
final IconData icon;
final String title;
@@ -251,7 +248,9 @@ class _GameCard extends StatelessWidget {
: l10n.chess_statusToMove(toMove);
subtitle = l10n.chess_rowMoveTurn((game.ply ~/ 2) + 1, turn);
case ChessGameStatus.finished:
title = l10n.chessPlayers(game);
title = game.hasPlayers || game.inviter == null
? l10n.chessPlayers(game)
: _inviteTitle(l10n, service);
subtitle = l10n.chessResult(game);
}
return MeshCard(
@@ -302,6 +301,21 @@ class _GameCard extends StatelessWidget {
);
}
/// An invite that never became a game: who invited whom.
String _inviteTitle(AppLocalizations l10n, ChessService service) {
final target = game.targetName;
if (game.iAmInviter) {
return target == null
? l10n.chess_rowYourOpenInvite
: l10n.chess_rowYourChallenge(target);
}
final inviter = game.inviter?.name ?? l10n.chess_unknownPlayer;
if (target == null) return l10n.chess_rowOpenInvite(inviter);
return service.isSelf(target)
? l10n.chess_rowChallengedYou(inviter)
: l10n.chess_rowChallenge(inviter, target);
}
Future<void> _confirmCancel(
BuildContext context,
ChessService service,
+6 -5
View File
@@ -22,10 +22,10 @@ abstract final class GameApp {
static const int chess = 1;
}
/// The 4-byte header every game packet starts with:
/// `[app << 4 | kind][gameId LE16][ply mod 256]`.
/// The 5-byte header every game packet starts with:
/// `[app << 4 | kind][gameId LE16][ply LE16]`.
class GamePacketHeader {
static const int length = 4;
static const int length = 5;
final int app;
final int kind;
@@ -44,7 +44,8 @@ class GamePacketHeader {
..addByte(((app & 0x0F) << 4) | (kind & 0x0F))
..addByte(gameId & 0xFF)
..addByte((gameId >> 8) & 0xFF)
..addByte(ply & 0xFF);
..addByte(ply & 0xFF)
..addByte((ply >> 8) & 0xFF);
}
static GamePacketHeader? parse(Uint8List bytes) {
@@ -53,7 +54,7 @@ class GamePacketHeader {
app: bytes[0] >> 4,
kind: bytes[0] & 0x0F,
gameId: bytes[1] | (bytes[2] << 8),
ply: bytes[3],
ply: bytes[3] | (bytes[4] << 8),
);
}