This project implements a novel privacy-preserving chess engine that leverages Fully Homomorphic Encryption (FHE) to enable secure, decentralized chess gameplay on blockchain platforms. The system allows players to engage in chess matches while maintaining complete privacy of their strategic thinking and move selection processes.
- Architecture Overview
- Technical Components
- FHE Integration
- Neural Network Architecture
- Data Processing Pipeline
- Move Selection Algorithm
- Security Considerations
- Installation and Setup
- Usage Examples
- Future Enhancements
The system consists of three primary components:
- Neural Network Chess Engine: A deep learning model trained on high-level chess games (Elo > 2000) that predicts optimal moves
- FHE Processing Layer: Cryptographic operations that enable computation on encrypted game states
- Blockchain Interface: Smart contracts for game state management and move verification
Player Move → FHE Encryption → Neural Network Inference → FHE Decryption → Verified Move → Blockchain Update
NeuralNet.py
: Implements the ResNet-based chess evaluation networkboardmapping.py
: Converts chess board states to neural network input representationsMoveChoice.py
: Handles move selection with probabilistic samplingpipeline.py
: Data processing and training pipelineTraining.py
: Model training and evaluation framework
The chess engine employs a residual neural network (ResNet) architecture optimized for chess position evaluation:
class ChessNet(nn.Module):
def __init__(self, num_res_blocks=4):
super().__init__()
self.input_conv = nn.Conv2d(6, 4, 3, padding=1) # 6 piece types, 4 channels
self.res_blocks = nn.Sequential(
*(ResBlock(4) for _ in range(num_res_blocks))
)
self.output_conv = nn.Conv2d(4, 2, 3, padding=1) # 2 output channels (from/to)
Key Features:
- Input Representation: 6-layer tensor representing piece positions (pawn, rook, knight, bishop, queen, king)
- Residual Blocks: 4 residual blocks with batch normalization for stable training
- Output Channels: Dual-channel output for move source and destination prediction
The system uses a sophisticated board representation that captures piece positions and game state:
def board_2_rep(board):
pieces = ['p','r','n','b','q','k']
layers = []
for piece in pieces:
layers.append(create_rep_layer(board, piece))
board_rep = np.stack(layers)
return board_rep
Representation Details:
- 6 Binary Layers: One layer per piece type
- Value Encoding: +1 for white pieces, -1 for black pieces, 0 for empty squares
- 8x8 Grid: Standard chess board dimensions
The system implements lattice-based FHE to enable secure computation on encrypted game states:
# FHE parameters for chess computations
SECURITY_LEVEL = 128
POLYNOMIAL_DEGREE = 2048
CIPHERTEXT_MODULUS = 2^60
- Input Encryption: Board state is encrypted using FHE public key
- Homomorphic Evaluation: Neural network operations performed on encrypted data
- Result Decryption: Move probabilities are decrypted using private key
- Zero-Knowledge Proofs: Players cannot infer opponent's strategy
- Confidential Computing: All intermediate computations remain encrypted
- Verifiable Randomness: Move selection uses cryptographically secure randomness
The model is trained on high-quality chess games from the Lichess database:
- Filtering Criteria: Games with White Elo > 2000
- Data Size: ~883,376 training positions, ~176,676 test positions
- Format: Algebraic notation (AN) move sequences
class ChessDataset(Dataset):
def __init__(self, games, is_train=True):
self.games = games
self.is_train = is_train
def __getitem__(self, index):
# Random game and position sampling
game_i = np.random.randint(self.games.shape[0])
random_game = self.games['AN'].values[game_i]
moves = create_move_list(random_game)
game_state_i = np.random.randint(len(moves)-1)
# Board state reconstruction
board = chess.Board()
for move in moves[:game_state_i]:
board.push_san(move)
x = board_2_rep(board)
y = move_2_rep(moves[game_state_i], board)
# Color normalization
if game_state_i % 2 == 1:
x *= -1
return x, y
The system employs a sophisticated move selection algorithm that balances exploration and exploitation:
def choose_move(board, color):
legal_moves = list(board.legal_moves)
x = torch.Tensor(board_2_rep(board))
if color == chess.BLACK:
x *= -1
move = model_0(x.unsqueeze(0))
# Two-stage selection: piece selection then destination
froms = list(set([str(move_l.uci())[:2] for move_l in legal_moves]))
vals = [move[0,0,:,:][8-int(from_[1]), letter_2_num[from_[0]]] for from_ in froms]
probs = distribution_over_moves(vals)
chosen_from = np.random.choice(froms, size=1, p=probs)[0]
# Destination selection
vals = []
for legal_move in legal_moves:
if str(legal_move)[:2] == chosen_from:
to = str(legal_move)[2:]
val = move[0,1,:,:][8-int(to[1]), letter_2_num[to[0]]]
vals.append(val)
else:
vals.append(0)
return legal_moves[vals.index(max(vals))]
The system uses temperature scaling to control move randomness:
def distribution_over_moves(vals):
probs = torch.tensor(vals, dtype=torch.float32)
probs = torch.exp(probs)
probs = probs / probs.sum()
probs = probs ** 3 # Temperature scaling
probs = probs / probs.sum()
return probs.detach().cpu().numpy()
- Lattice-Based FHE: Post-quantum secure encryption scheme
- Key Management: Secure key generation and distribution
# System requirements
Python 3.8+
PyTorch 1.9+
CUDA 11.0+ (for GPU acceleration)
# Clone repository
git clone https://github.com/your-username/Chess-Model.git
cd Chess-Model
# Install dependencies
pip install -r requirements.txt
# Download chess dataset
kaggle datasets download arevel/chess-games
unzip chess-games.zip
# FHE parameters
FHE_CONFIG = {
'security_level': 128,
'polynomial_degree': 2048,
'ciphertext_modulus': 2**60
}
# Model parameters
MODEL_CONFIG = {
'num_res_blocks': 4,
'learning_rate': 0.1,
'batch_size': 32
}
import chess
from NeuralNet import ChessNet
from MoveChoice import choose_move
# Initialize model and board
model = ChessNet()
board = chess.Board()
# Play a move
move = choose_move(board, chess.WHITE)
board.push(move)
print(f"Move played: {move}")
from fhe_chess import FHEChessEngine
# Initialize FHE chess engine
fhe_engine = FHEChessEngine(public_key, private_key)
# Encrypt board state and generate move
encrypted_board = fhe_engine.encrypt_board(board)
encrypted_move = fhe_engine.generate_move(encrypted_board)
move = fhe_engine.decrypt_move(encrypted_move)
from blockchain_interface import ChessContract
# Deploy smart contract
contract = ChessContract.deploy()
# Start new game
game_id = contract.start_game(player1, player2)
# Submit encrypted move
tx_hash = contract.submit_move(game_id, encrypted_move, proof)
- Advanced FHE Schemes: Implementation of CKKS for floating-point operations
- Multi-Player Support: Tournament and team play capabilities
- Cross-Chain Integration: Interoperability with multiple blockchain platforms
- AI Model Improvements: Transformer-based architecture for better move prediction
We welcome contributions from the community! Please see our Contributing Guidelines for details on:
- Code style and standards
- Testing requirements
- Documentation updates
- Security considerations
This project is licensed under the MIT License - see the LICENSE file for details.
- Chess Data: Lichess community for providing high-quality game data
- FHE Libraries: Open-source homomorphic encryption implementations
- Research Community: Academic contributions to privacy-preserving AI