콘텐츠 대표 이미지 - 라라벨로 블록체인 투표 결과시각화 대시보드 개발하기
🔗 블록체인 / Web3 × 프로그램개발

라라벨로 블록체인 투표 결과
시각화 대시보드 개발하기

🗳️ 투명한 투표 + 🎨 아름다운 시각화 = 🚀 풀스택 Web3 프로젝트

야, 솔직히 말해볼게. 블록체인이라고 하면 대부분 "비트코인이나 이더리움 같은 거 아냐?" 하고 넘어가는 경우가 많잖아. 근데 블록체인의 진짜 매력 중 하나는 바로 투명하고 변조 불가능한 투표 시스템을 만들 수 있다는 거야. 🗳️


그리고 거기에 라라벨(Laravel)이라는 PHP의 끝판왕 프레임워크를 붙이면? 백엔드 API부터 데이터 집계, 그리고 멋진 시각화 대시보드까지 한 번에 해결할 수 있어. 오늘은 그 전체 여정을 같이 걸어볼 거야.


이 글에서는 단순히 "이런 게 있어요~" 수준이 아니라, 실제로 어떻게 코드를 짜고, 어떤 구조로 설계하고, 어떤 라이브러리를 쓰는지 팩트 위주로 꼼꼼하게 다룰 거야. 준비됐어? 그럼 고고! 🚀

전체 시스템 아키텍처 ⛓️ 블록체인 스마트 컨트랙트 투표 데이터 저장 이벤트 🔴 Laravel 백엔드 API 데이터 집계 인증 / 캐싱 REST API 📊 대시보드 Chart.js 시각화 실시간 업데이트 Blade 템플릿 렌더링 👤 사용자 투표 참여 결과 확인 🛠️ 기술 스택 Solidity Web3.php Laravel 10 MySQL Chart.js Redis Livewire 블록체인의 투명성 + 라라벨의 생산성 = 신뢰할 수 있는 투표 시스템 스마트 컨트랙트로 투표 → 라라벨이 데이터 수집 → 대시보드에서 시각화

🗺️ 1. 프로젝트 개요 및 왜 이 조합인가?

먼저 "왜 라라벨이야?" 라는 질문에 답해보자. 블록체인 투표 시스템을 만들 때 백엔드 선택지는 여러 개야. Node.js, Django, Spring Boot... 근데 라라벨을 선택하는 이유는 명확해.


🎯 라라벨을 선택하는 이유 1. Eloquent ORM — 블록체인에서 가져온 데이터를 DB에 저장하고 집계할 때 SQL 없이도 직관적으로 처리 가능
2. Queue 시스템 — 블록체인 이벤트 리스닝을 비동기로 처리하기 완벽한 구조
3. Blade 템플릿 — 서버사이드 렌더링으로 대시보드를 빠르게 구성
4. Livewire — 실시간 데이터 업데이트를 PHP만으로 구현 가능
5. 생태계 — Web3.php 라이브러리와의 연동이 잘 되어 있음

이 프로젝트에서 만들 것들을 정리하면 이래:


1
Solidity 스마트 컨트랙트 — 투표 로직을 블록체인에 배포 (Ethereum 테스트넷 기준)
2
Laravel 백엔드 — Web3.php로 블록체인 데이터 읽기, DB 캐싱, REST API 제공
3
시각화 대시보드 — Chart.js + Blade로 투표 결과를 파이차트, 막대그래프, 실시간 카운터로 표시
4
실시간 업데이트 — Laravel Livewire + Polling으로 새 투표가 들어오면 자동 갱신

💡 참고: 이 글에서는 Ethereum의 Sepolia 테스트넷을 기준으로 설명해. 실제 메인넷 배포 시에는 가스비 최적화와 보안 감사가 추가로 필요해!

⛓️ 2. 스마트 컨트랙트 설계 (Solidity)

블록체인 투표 시스템의 심장은 스마트 컨트랙트야. Solidity로 작성하고 Ethereum 네트워크에 배포하면, 그 이후부터는 누구도 결과를 조작할 수 없어. 이게 블록체인 투표의 핵심 가치지! 🔒


2-1. 기본 투표 컨트랙트 구조
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

contract VotingSystem {
    // 후보자 구조체
    struct Candidate {
        uint256 id;
        string name;
        string description;
        uint256 voteCount;
    }

    // 투표 정보 구조체
    struct Election {
        uint256 id;
        string title;
        uint256 startTime;
        uint256 endTime;
        bool isActive;
        uint256 totalVotes;
    }

    // 상태 변수
    address public owner;
    uint256 public electionCount;
    
    // 매핑
    mapping(uint256 => Election) public elections;
    mapping(uint256 => Candidate[]) public candidates;
    mapping(uint256 => mapping(address => bool)) public hasVoted;
    
    // 이벤트 (라라벨에서 이걸 리스닝함!)
    event VoteCast(
        uint256 indexed electionId,
        uint256 indexed candidateId,
        address indexed voter,
        uint256 timestamp
    );
    
    event ElectionCreated(
        uint256 indexed electionId,
        string title,
        uint256 startTime,
        uint256 endTime
    );
    
    // 수정자
    modifier onlyOwner() {
        require(msg.sender == owner, "Only owner");
        _;
    }
    
    modifier electionActive(uint256 _electionId) {
        Election storage e = elections[_electionId];
        require(e.isActive, "Election not active");
        require(block.timestamp >= e.startTime, "Not started");
        require(block.timestamp <= e.endTime, "Already ended");
        _;
    }
    
    constructor() {
        owner = msg.sender;
    }
    
    // 선거 생성
    function createElection(
        string memory _title,
        uint256 _startTime,
        uint256 _endTime,
        string[] memory _candidateNames,
        string[] memory _candidateDescs
    ) external onlyOwner {
        electionCount++;
        
        elections[electionCount] = Election({
            id: electionCount,
            title: _title,
            startTime: _startTime,
            endTime: _endTime,
            isActive: true,
            totalVotes: 0
        });
        
        for (uint i = 0; i < _candidateNames.length; i++) {
            candidates[electionCount].push(Candidate({
                id: i + 1,
                name: _candidateNames[i],
                description: _candidateDescs[i],
                voteCount: 0
            }));
        }
        
        emit ElectionCreated(electionCount, _title, _startTime, _endTime);
    }
    
    // 투표 실행
    function castVote(
        uint256 _electionId,
        uint256 _candidateId
    ) external electionActive(_electionId) {
        require(!hasVoted[_electionId][msg.sender], "Already voted");
        require(
            _candidateId > 0 && 
            _candidateId <= candidates[_electionId].length,
            "Invalid candidate"
        );
        
        hasVoted[_electionId][msg.sender] = true;
        candidates[_electionId][_candidateId - 1].voteCount++;
        elections[_electionId].totalVotes++;
        
        emit VoteCast(_electionId, _candidateId, msg.sender, block.timestamp);
    }
    
    // 결과 조회
    function getResults(uint256 _electionId) 
        external view 
        returns (Candidate[] memory) 
    {
        return candidates[_electionId];
    }
    
    // 투표 현황 조회
    function getElectionInfo(uint256 _electionId)
        external view
        returns (Election memory)
    {
        return elections[_electionId];
    }
}
2-2. 컨트랙트 핵심 포인트
요소 역할 라라벨 연동
event VoteCast 투표 발생 시 이벤트 발행 Web3.php로 이벤트 리스닝
hasVoted mapping 중복 투표 방지 지갑 주소 기반 검증
getResults() 결과 데이터 반환 API 엔드포인트에서 호출
electionActive modifier 시간 기반 투표 제어 대시보드 상태 표시
2-3. Hardhat으로 배포하기

컨트랙트를 작성했으면 배포해야지! Hardhat을 사용하면 테스트넷 배포가 훨씬 편해.


// hardhat.config.js
require("@nomicfoundation/hardhat-toolbox");
require("dotenv").config();

module.exports = {
  solidity: "0.8.19",
  networks: {
    sepolia: {
      url: process.env.SEPOLIA_RPC_URL,  // Alchemy 또는 Infura URL
      accounts: [process.env.PRIVATE_KEY]
    }
  },
  etherscan: {
    apiKey: process.env.ETHERSCAN_API_KEY
  }
};

// scripts/deploy.js
const hre = require("hardhat");

async function main() {
  const VotingSystem = await hre.ethers.getContractFactory("VotingSystem");
  const voting = await VotingSystem.deploy();
  await voting.waitForDeployment();
  
  console.log("VotingSystem deployed to:", await voting.getAddress());
  
  // 배포된 주소를 .env에 저장해야 함!
  // VOTING_CONTRACT_ADDRESS=0x...
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
⚠️ 중요: 배포 후 나오는 컨트랙트 주소와 ABI(Application Binary Interface)를 반드시 저장해둬야 해. 라라벨에서 이 컨트랙트와 통신할 때 필수로 필요하거든!

🔴 3. 라라벨 프로젝트 세팅 및 Web3 연동
3-1. 프로젝트 생성 및 필수 패키지 설치
# 라라벨 프로젝트 생성
composer create-project laravel/laravel blockchain-voting
cd blockchain-voting

# Web3.php 설치 (PHP에서 이더리움 통신)
composer require sc0vu/web3.php

# Livewire 설치 (실시간 UI)
composer require livewire/livewire

# Redis 드라이버 (캐싱용)
composer require predis/predis

# 환경 설정
cp .env.example .env
php artisan key:generate
3-2. .env 환경 변수 설정
# .env 파일에 추가
APP_NAME="블록체인 투표 대시보드"
APP_URL=http://localhost:8000

# 데이터베이스
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blockchain_voting
DB_USERNAME=root
DB_PASSWORD=your_password

# 블록체인 설정
ETHEREUM_RPC_URL=https://eth-sepolia.g.alchemy.com/v2/YOUR_API_KEY
VOTING_CONTRACT_ADDRESS=0xYOUR_CONTRACT_ADDRESS
CHAIN_ID=11155111

# 캐시 (Redis 권장)
CACHE_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379

# 큐 (블록체인 이벤트 처리용)
QUEUE_CONNECTION=redis
3-3. Web3 서비스 클래스 만들기

라라벨에서 블록체인과 통신하는 핵심 서비스 클래스야. 이걸 잘 만들어두면 나머지가 훨씬 편해져!


<?php
// app/Services/BlockchainService.php

namespace App\Services;

use Web3\Web3;
use Web3\Contract;
use Web3\Providers\HttpProvider;
use Web3\RequestManagers\HttpRequestManager;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class BlockchainService
{
    private Web3 $web3;
    private Contract $contract;
    private string $contractAddress;
    private array $abi;
    
    public function __construct()
    {
        $rpcUrl = config('blockchain.rpc_url');
        $this->contractAddress = config('blockchain.contract_address');
        $this->abi = json_decode(
            file_get_contents(storage_path('app/abi/VotingSystem.json')), 
            true
        );
        
        // Web3 인스턴스 생성
        $this->web3 = new Web3(
            new HttpProvider(
                new HttpRequestManager($rpcUrl, 30)
            )
        );
        
        // 컨트랙트 인스턴스 생성
        $this->contract = new Contract(
            $this->web3->provider, 
            json_encode($this->abi)
        );
        $this->contract->at($this->contractAddress);
    }
    
    /**
     * 선거 결과 가져오기 (캐싱 포함)
     */
    public function getElectionResults(int $electionId): array
    {
        $cacheKey = "election_results_{$electionId}";
        
        return Cache::remember($cacheKey, 30, function () use ($electionId) {
            return $this->fetchResultsFromChain($electionId);
        });
    }
    
    /**
     * 블록체인에서 직접 결과 조회
     */
    private function fetchResultsFromChain(int $electionId): array
    {
        $results = [];
        $error = null;
        
        $this->contract->call(
            'getResults',
            $electionId,
            function ($err, $data) use (&$results, &$error) {
                if ($err) {
                    $error = $err->getMessage();
                    Log::error('블록체인 조회 오류: ' . $error);
                    return;
                }
                $results = $this->parseResults($data);
            }
        );
        
        if ($error) {
            throw new \Exception("블록체인 조회 실패: {$error}");
        }
        
        return $results;
    }
    
    /**
     * 선거 정보 가져오기
     */
    public function getElectionInfo(int $electionId): array
    {
        $cacheKey = "election_info_{$electionId}";
        
        return Cache::remember($cacheKey, 60, function () use ($electionId) {
            $info = [];
            
            $this->contract->call(
                'getElectionInfo',
                $electionId,
                function ($err, $data) use (&$info) {
                    if (!$err) {
                        $info = $this->parseElectionInfo($data);
                    }
                }
            );
            
            return $info;
        });
    }
    
    /**
     * 총 투표 수 가져오기
     */
    public function getTotalVotes(int $electionId): int
    {
        $info = $this->getElectionInfo($electionId);
        return $info['totalVotes'] ?? 0;
    }
    
    /**
     * 결과 데이터 파싱
     */
    private function parseResults(array $data): array
    {
        $candidates = [];
        
        if (isset($data[0]) && is_array($data[0])) {
            foreach ($data[0] as $candidate) {
                $candidates[] = [
                    'id' => (int) $candidate['id']->toString(),
                    'name' => $candidate['name'],
                    'description' => $candidate['description'],
                    'voteCount' => (int) $candidate['voteCount']->toString(),
                ];
            }
        }
        
        return $candidates;
    }
    
    /**
     * 선거 정보 파싱
     */
    private function parseElectionInfo(array $data): array
    {
        if (!isset($data[0])) return [];
        
        $election = $data[0];
        return [
            'id' => (int) $election['id']->toString(),
            'title' => $election['title'],
            'startTime' => (int) $election['startTime']->toString(),
            'endTime' => (int) $election['endTime']->toString(),
            'isActive' => $election['isActive'],
            'totalVotes' => (int) $election['totalVotes']->toString(),
        ];
    }
    
    /**
     * 캐시 무효화 (새 투표 발생 시)
     */
    public function invalidateCache(int $electionId): void
    {
        Cache::forget("election_results_{$electionId}");
        Cache::forget("election_info_{$electionId}");
    }
}
💡 캐싱 전략: 블록체인 RPC 호출은 비용이 들고 느려. 그래서 결과는 30초, 선거 정보는 60초 캐싱해두는 게 좋아. 새 투표가 들어올 때만 캐시를 무효화하면 돼!
3-4. 블록체인 설정 파일
<?php
// config/blockchain.php

return [
    'rpc_url' => env('ETHEREUM_RPC_URL', 'https://eth-sepolia.g.alchemy.com/v2/'),
    'contract_address' => env('VOTING_CONTRACT_ADDRESS'),
    'chain_id' => env('CHAIN_ID', 11155111),
    
    // 이벤트 폴링 간격 (초)
    'polling_interval' => env('BLOCKCHAIN_POLLING_INTERVAL', 15),
    
    // 캐시 TTL
    'cache_ttl' => [
        'results' => 30,
        'election_info' => 60,
        'statistics' => 300,
    ],
];

🗄️ 4. 데이터베이스 설계 및 마이그레이션

블록체인 데이터를 매번 직접 조회하면 느리고 비용이 많이 들어. 그래서 라라벨 DB에 블록체인 데이터의 미러(mirror)를 만들어두는 게 핵심 전략이야. 이걸 "이벤트 소싱 패턴"이라고도 해.


4-1. 마이그레이션 파일들
<?php
// database/migrations/create_elections_table.php

Schema::create('elections', function (Blueprint $table) {
    $table->id();
    $table->unsignedInteger('blockchain_id')->unique(); // 컨트랙트의 electionId
    $table->string('title');
    $table->text('description')->nullable();
    $table->timestamp('start_time');
    $table->timestamp('end_time');
    $table->boolean('is_active')->default(true);
    $table->unsignedInteger('total_votes')->default(0);
    $table->string('contract_address', 42);
    $table->timestamps();
    
    $table->index('blockchain_id');
    $table->index('is_active');
});

// database/migrations/create_candidates_table.php
Schema::create('candidates', function (Blueprint $table) {
    $table->id();
    $table->foreignId('election_id')->constrained()->cascadeOnDelete();
    $table->unsignedInteger('blockchain_candidate_id');
    $table->string('name');
    $table->text('description')->nullable();
    $table->string('image_url')->nullable();
    $table->unsignedInteger('vote_count')->default(0);
    $table->timestamps();
    
    $table->index(['election_id', 'blockchain_candidate_id']);
});

// database/migrations/create_vote_events_table.php
Schema::create('vote_events', function (Blueprint $table) {
    $table->id();
    $table->foreignId('election_id')->constrained();
    $table->foreignId('candidate_id')->constrained();
    $table->string('voter_address', 42); // 이더리움 지갑 주소
    $table->string('transaction_hash', 66)->unique();
    $table->unsignedBigInteger('block_number');
    $table->timestamp('voted_at');
    $table->timestamps();
    
    $table->index('voter_address');
    $table->index('transaction_hash');
    $table->index('block_number');
});

// database/migrations/create_blockchain_sync_logs_table.php
Schema::create('blockchain_sync_logs', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('last_synced_block');
    $table->string('contract_address', 42);
    $table->timestamp('synced_at');
    $table->unsignedInteger('events_processed')->default(0);
    $table->timestamps();
});
4-2. Eloquent 모델
<?php
// app/Models/Election.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Election extends Model
{
    protected $fillable = [
        'blockchain_id', 'title', 'description',
        'start_time', 'end_time', 'is_active',
        'total_votes', 'contract_address'
    ];
    
    protected $casts = [
        'start_time' => 'datetime',
        'end_time' => 'datetime',
        'is_active' => 'boolean',
    ];
    
    public function candidates(): HasMany
    {
        return $this->hasMany(Candidate::class)->orderByDesc('vote_count');
    }
    
    public function voteEvents(): HasMany
    {
        return $this->hasMany(VoteEvent::class);
    }
    
    // 투표율 계산 (등록 유권자 수 대비)
    public function getParticipationRateAttribute(): float
    {
        // 실제로는 등록 유권자 수를 별도 관리해야 함
        return $this->total_votes > 0 ? 100.0 : 0.0;
    }
    
    // 선거 상태 확인
    public function getStatusAttribute(): string
    {
        $now = now();
        if ($now->lt($this->start_time)) return '예정';
        if ($now->gt($this->end_time)) return '종료';
        return '진행중';
    }
    
    // 선두 후보
    public function getLeadingCandidateAttribute(): ?Candidate
    {
        return $this->candidates->first();
    }
    
    // 시간별 투표 통계 (대시보드용)
    public function getHourlyStatsAttribute(): array
    {
        return $this->voteEvents()
            ->selectRaw('HOUR(voted_at) as hour, COUNT(*) as count')
            ->groupBy('hour')
            ->orderBy('hour')
            ->pluck('count', 'hour')
            ->toArray();
    }
}

// app/Models/Candidate.php
class Candidate extends Model
{
    protected $fillable = [
        'election_id', 'blockchain_candidate_id',
        'name', 'description', 'image_url', 'vote_count'
    ];
    
    public function election()
    {
        return $this->belongsTo(Election::class);
    }
    
    // 득표율 계산
    public function getVotePercentageAttribute(): float
    {
        $total = $this->election->total_votes;
        if ($total === 0) return 0.0;
        return round(($this->vote_count / $total) * 100, 2);
    }
}

🔄 5. 블록체인 이벤트 동기화 시스템

이 부분이 진짜 핵심이야! 블록체인에서 투표가 발생하면, 그 이벤트를 라라벨이 감지하고 DB에 저장해야 해. 이걸 이벤트 리스닝(Event Listening)이라고 해.


5-1. 블록체인 동기화 커맨드
<?php
// app/Console/Commands/SyncBlockchainEvents.php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\BlockchainService;
use App\Services\EventSyncService;
use App\Models\BlockchainSyncLog;

class SyncBlockchainEvents extends Command
{
    protected $signature = 'blockchain:sync 
                            {--from-block= : 시작 블록 번호}
                            {--to-block= : 종료 블록 번호}';
    
    protected $description = '블록체인 투표 이벤트를 DB에 동기화';
    
    public function __construct(
        private BlockchainService $blockchainService,
        private EventSyncService $eventSyncService
    ) {
        parent::__construct();
    }
    
    public function handle(): int
    {
        $this->info('🔗 블록체인 이벤트 동기화 시작...');
        
        // 마지막 동기화 블록 확인
        $lastSync = BlockchainSyncLog::latest()->first();
        $fromBlock = $this->option('from-block') 
            ?? ($lastSync ? $lastSync->last_synced_block + 1 : 0);
        
        // 현재 블록 번호 가져오기
        $currentBlock = $this->blockchainService->getCurrentBlockNumber();
        $toBlock = $this->option('to-block') ?? $currentBlock;
        
        $this->info("블록 범위: {$fromBlock} ~ {$toBlock}");
        
        // 이벤트 가져오기 및 처리
        $processedCount = $this->eventSyncService->syncVoteEvents(
            $fromBlock, 
            $toBlock
        );
        
        // 동기화 로그 저장
        BlockchainSyncLog::create([
            'last_synced_block' => $toBlock,
            'contract_address' => config('blockchain.contract_address'),
            'synced_at' => now(),
            'events_processed' => $processedCount,
        ]);
        
        $this->info("✅ 동기화 완료! 처리된 이벤트: {$processedCount}개");
        
        return Command::SUCCESS;
    }
}

// app/Services/EventSyncService.php
class EventSyncService
{
    public function syncVoteEvents(int $fromBlock, int $toBlock): int
    {
        $web3 = app(BlockchainService::class);
        $processedCount = 0;
        
        // VoteCast 이벤트 필터 생성
        $filter = [
            'fromBlock' => '0x' . dechex($fromBlock),
            'toBlock' => '0x' . dechex($toBlock),
            'address' => config('blockchain.contract_address'),
            'topics' => [
                // VoteCast 이벤트 시그니처 해시
                '0x' . keccak256('VoteCast(uint256,uint256,address,uint256)')
            ]
        ];
        
        $logs = $web3->getLogs($filter);
        
        foreach ($logs as $log) {
            $this->processVoteEvent($log);
            $processedCount++;
        }
        
        return $processedCount;
    }
    
    private function processVoteEvent(array $log): void
    {
        // 이벤트 데이터 디코딩
        $electionId = hexdec($log['topics'][1]);
        $candidateId = hexdec($log['topics'][2]);
        $voterAddress = '0x' . substr($log['topics'][3], 26);
        $txHash = $log['transactionHash'];
        $blockNumber = hexdec($log['blockNumber']);
        
        // 중복 처리 방지
        if (VoteEvent::where('transaction_hash', $txHash)->exists()) {
            return;
        }
        
        DB::transaction(function () use (
            $electionId, $candidateId, $voterAddress, 
            $txHash, $blockNumber, $log
        ) {
            $election = Election::where('blockchain_id', $electionId)->first();
            $candidate = Candidate::where([
                'election_id' => $election->id,
                'blockchain_candidate_id' => $candidateId
            ])->first();
            
            // 투표 이벤트 저장
            VoteEvent::create([
                'election_id' => $election->id,
                'candidate_id' => $candidate->id,
                'voter_address' => strtolower($voterAddress),
                'transaction_hash' => $txHash,
                'block_number' => $blockNumber,
                'voted_at' => now(), // 실제로는 블록 타임스탬프 사용
            ]);
            
            // 득표수 업데이트
            $candidate->increment('vote_count');
            $election->increment('total_votes');
            
            // 캐시 무효화
            app(BlockchainService::class)->invalidateCache($electionId);
        });
    }
}
5-2. 스케줄러 등록
<?php
// app/Console/Kernel.php

protected function schedule(Schedule $schedule): void
{
    // 15초마다 블록체인 동기화
    $schedule->command('blockchain:sync')
             ->everyFifteenSeconds()
             ->withoutOverlapping()
             ->runInBackground();
    
    // 매시간 통계 캐시 갱신
    $schedule->command('blockchain:refresh-stats')
             ->hourly();
}

// crontab에 등록 (서버에서)
// * * * * * cd /path/to/project && php artisan schedule:run >> /dev/null 2>&1
💡 성능 팁: 블록체인 동기화는 withoutOverlapping()을 꼭 써야 해. 이전 동기화가 끝나기 전에 새 동기화가 시작되면 중복 처리가 발생할 수 있거든!

🌐 6. REST API 컨트롤러 설계

대시보드가 데이터를 가져올 API를 만들어보자. Chart.js가 이 API를 호출해서 차트를 그리게 돼.


6-1. 라우트 설정
<?php
// routes/api.php

use App\Http\Controllers\Api\ElectionController;
use App\Http\Controllers\Api\StatisticsController;

Route::prefix('v1')->group(function () {
    // 선거 관련
    Route::get('/elections', [ElectionController::class, 'index']);
    Route::get('/elections/{id}', [ElectionController::class, 'show']);
    Route::get('/elections/{id}/results', [ElectionController::class, 'results']);
    Route::get('/elections/{id}/statistics', [StatisticsController::class, 'election']);
    
    // 실시간 데이터
    Route::get('/elections/{id}/live', [ElectionController::class, 'live']);
    
    // 투표 이벤트 히스토리
    Route::get('/elections/{id}/events', [ElectionController::class, 'events']);
    
    // 전체 통계
    Route::get('/statistics/overview', [StatisticsController::class, 'overview']);
});

// routes/web.php
Route::get('/', [DashboardController::class, 'index'])->name('dashboard');
Route::get('/elections/{id}', [DashboardController::class, 'election'])->name('election.show');
Route::get('/elections/{id}/live', [DashboardController::class, 'live'])->name('election.live');
6-2. 선거 컨트롤러
<?php
// app/Http/Controllers/Api/ElectionController.php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Election;
use App\Services\BlockchainService;
use Illuminate\Http\JsonResponse;

class ElectionController extends Controller
{
    public function __construct(
        private BlockchainService $blockchainService
    ) {}
    
    // 선거 목록
    public function index(): JsonResponse
    {
        $elections = Election::with('candidates')
            ->orderByDesc('created_at')
            ->get()
            ->map(fn($e) => [
                'id' => $e->id,
                'blockchain_id' => $e->blockchain_id,
                'title' => $e->title,
                'status' => $e->status,
                'total_votes' => $e->total_votes,
                'start_time' => $e->start_time->toIso8601String(),
                'end_time' => $e->end_time->toIso8601String(),
                'candidate_count' => $e->candidates->count(),
            ]);
        
        return response()->json([
            'success' => true,
            'data' => $elections,
        ]);
    }
    
    // 투표 결과 (차트용)
    public function results(int $id): JsonResponse
    {
        $election = Election::with('candidates')->findOrFail($id);
        
        // 차트 데이터 형식으로 변환
        $chartData = [
            'labels' => $election->candidates->pluck('name')->toArray(),
            'datasets' => [[
                'data' => $election->candidates->pluck('vote_count')->toArray(),
                'backgroundColor' => [
                    '#5b8fa8', '#82b87a', '#e0a96d', 
                    '#9b8fc0', '#e07a7a', '#7ab3cc'
                ],
                'borderWidth' => 2,
                'borderColor' => '#ffffff',
            ]],
        ];
        
        return response()->json([
            'success' => true,
            'election' => [
                'id' => $election->id,
                'title' => $election->title,
                'total_votes' => $election->total_votes,
                'status' => $election->status,
            ],
            'chart_data' => $chartData,
            'candidates' => $election->candidates->map(fn($c) => [
                'id' => $c->id,
                'name' => $c->name,
                'vote_count' => $c->vote_count,
                'percentage' => $c->vote_percentage,
            ]),
        ]);
    }
    
    // 실시간 데이터 (폴링용)
    public function live(int $id): JsonResponse
    {
        $election = Election::with('candidates')->findOrFail($id);
        
        // 최근 5분간 투표 추이
        $recentVotes = VoteEvent::where('election_id', $election->id)
            ->where('voted_at', '>=', now()->subMinutes(5))
            ->selectRaw('MINUTE(voted_at) as minute, COUNT(*) as count')
            ->groupBy('minute')
            ->orderBy('minute')
            ->get();
        
        return response()->json([
            'total_votes' => $election->total_votes,
            'candidates' => $election->candidates->map(fn($c) => [
                'id' => $c->id,
                'name' => $c->name,
                'vote_count' => $c->vote_count,
                'percentage' => $c->vote_percentage,
            ]),
            'recent_activity' => $recentVotes,
            'last_updated' => now()->toIso8601String(),
        ]);
    }
}
6-3. 통계 컨트롤러
<?php
// app/Http/Controllers/Api/StatisticsController.php

class StatisticsController extends Controller
{
    // 선거별 상세 통계
    public function election(int $id): JsonResponse
    {
        $election = Election::findOrFail($id);
        
        // 시간별 투표 분포
        $hourlyData = VoteEvent::where('election_id', $id)
            ->selectRaw('HOUR(voted_at) as hour, COUNT(*) as count')
            ->groupBy('hour')
            ->orderBy('hour')
            ->get();
        
        // 일별 투표 추이
        $dailyData = VoteEvent::where('election_id', $id)
            ->selectRaw('DATE(voted_at) as date, COUNT(*) as count')
            ->groupBy('date')
            ->orderBy('date')
            ->get();
        
        // 후보별 시간대 분포
        $candidateHourly = VoteEvent::where('election_id', $id)
            ->join('candidates', 'vote_events.candidate_id', '=', 'candidates.id')
            ->selectRaw('candidates.name, HOUR(voted_at) as hour, COUNT(*) as count')
            ->groupBy('candidates.name', 'hour')
            ->orderBy('hour')
            ->get();
        
        return response()->json([
            'hourly_distribution' => [
                'labels' => $hourlyData->pluck('hour')
                    ->map(fn($h) => "{$h}시")->toArray(),
                'data' => $hourlyData->pluck('count')->toArray(),
            ],
            'daily_trend' => [
                'labels' => $dailyData->pluck('date')->toArray(),
                'data' => $dailyData->pluck('count')->toArray(),
            ],
            'candidate_hourly' => $candidateHourly,
            'peak_hour' => $hourlyData->sortByDesc('count')->first()?->hour,
            'unique_voters' => VoteEvent::where('election_id', $id)
                ->distinct('voter_address')->count(),
        ]);
    }
}

🎨 7. 시각화 대시보드 구현 (Blade + Chart.js)

드디어 눈에 보이는 부분이야! 🎉 Blade 템플릿으로 대시보드 레이아웃을 잡고, Chart.js로 멋진 차트를 그려보자.


7-1. 메인 레이아웃
<!-- resources/views/layouts/dashboard.blade.php -->
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>블록체인 투표 대시보드</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    
    <!-- Tailwind CSS -->
    @vite(['resources/css/app.css', 'resources/js/app.js'])
    
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
    
    <!-- Livewire -->
    @livewireStyles
</head>
<body class="bg-gray-50 min-h-screen">
    <!-- 네비게이션 -->
    <nav class="bg-white shadow-sm border-b border-gray-100">
        <div class="max-w-7xl mx-auto px-4 py-4 flex items-center justify-between">
            <div class="flex items-center gap-3">
                <span class="text-2xl">⛓️</span>
                <h1 class="text-xl font-bold text-gray-800">블록체인 투표 대시보드</h1>
            </div>
            <div class="flex items-center gap-2">
                <span class="w-2 h-2 bg-green-400 rounded-full animate-pulse"></span>
                <span class="text-sm text-gray-500">Sepolia 테스트넷 연결됨</span>
            </div>
        </div>
    </nav>
    
    <main class="max-w-7xl mx-auto px-4 py-8">
        @yield('content')
    </main>
    
    @livewireScripts
    @stack('scripts')
</body>
</html>
7-2. 선거 대시보드 뷰
<!-- resources/views/elections/show.blade.php -->
@extends('layouts.dashboard')

@section('content')
<!-- 선거 헤더 -->
<div class="bg-white rounded-2xl shadow-sm p-6 mb-6">
    <div class="flex items-start justify-between">
        <div>
            <span class="inline-block px-3 py-1 rounded-full text-xs font-bold
                @if($election->status === '진행중') bg-green-100 text-green-700
                @elseif($election->status === '종료') bg-gray-100 text-gray-600
                @else bg-blue-100 text-blue-700 @endif">
                {{ $election->status }}
            </span>
            <h2 class="text-2xl font-bold text-gray-800 mt-2">{{ $election->title }}</h2>
            <p class="text-gray-500 mt-1">
                {{ $election->start_time->format('Y.m.d H:i') }} ~ 
                {{ $election->end_time->format('Y.m.d H:i') }}
            </p>
        </div>
        <div class="text-right">
            <p class="text-4xl font-black text-blue-600">
                {{ number_format($election->total_votes) }}
            </p>
            <p class="text-sm text-gray-500">총 투표 수</p>
        </div>
    </div>
</div>

<!-- 차트 그리드 -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
    
    <!-- 파이 차트 -->
    <div class="bg-white rounded-2xl shadow-sm p-6">
        <h3 class="text-lg font-bold text-gray-700 mb-4">📊 득표 현황</h3>
        <canvas id="pieChart" height="280"></canvas>
    </div>
    
    <!-- 막대 차트 -->
    <div class="bg-white rounded-2xl shadow-sm p-6">
        <h3 class="text-lg font-bold text-gray-700 mb-4">📈 후보별 득표수</h3>
        <canvas id="barChart" height="280"></canvas>
    </div>
</div>

<!-- 시간별 투표 추이 -->
<div class="bg-white rounded-2xl shadow-sm p-6 mb-6">
    <h3 class="text-lg font-bold text-gray-700 mb-4">⏰ 시간별 투표 추이</h3>
    <canvas id="lineChart" height="150"></canvas>
</div>

<!-- 후보자 카드 -->
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
    @foreach($election->candidates as $index => $candidate)
    <div class="bg-white rounded-2xl shadow-sm p-5 border-l-4
        @if($index === 0) border-blue-400 @elseif($index === 1) border-green-400 @else border-orange-400 @endif">
        <div class="flex items-center justify-between mb-3">
            <h4 class="font-bold text-gray-800">{{ $candidate->name }}</h4>
            @if($index === 0)
            <span class="text-yellow-500 text-xl">🥇</span>
            @elseif($index === 1)
            <span class="text-gray-400 text-xl">🥈</span>
            @else
            <span class="text-orange-400 text-xl">🥉</span>
            @endif
        </div>
        <p class="text-3xl font-black text-gray-800">
            {{ number_format($candidate->vote_count) }}
        </p>
        <p class="text-sm text-gray-500">표 ({{ $candidate->vote_percentage }}%)</p>
        <!-- 진행바 -->
        <div class="mt-3 bg-gray-100 rounded-full h-2">
            <div class="h-2 rounded-full transition-all duration-500
                @if($index === 0) bg-blue-400 @elseif($index === 1) bg-green-400 @else bg-orange-400 @endif"
                style="width: {{ $candidate->vote_percentage }}%">
            </div>
        </div>
    </div>
    @endforeach
</div>

<!-- 블록체인 검증 정보 -->
<div class="bg-gray-800 rounded-2xl p-6 text-white">
    <h3 class="font-bold mb-3">🔗 블록체인 검증 정보</h3>
    <div class="grid grid-cols-2 gap-4 text-sm">
        <div>
            <p class="text-gray-400">컨트랙트 주소</p>
            <p class="font-mono text-green-400 text-xs break-all">
                {{ config('blockchain.contract_address') }}
            </p>
        </div>
        <div>
            <p class="text-gray-400">네트워크</p>
            <p class="text-green-400">Ethereum Sepolia Testnet</p>
        </div>
    </div>
</div>
@endsection
7-3. Chart.js 초기화 스크립트
// resources/js/dashboard.js

class VotingDashboard {
    constructor(electionId) {
        this.electionId = electionId;
        this.charts = {};
        this.pollingInterval = null;
        this.init();
    }
    
    async init() {
        await this.loadData();
        this.startPolling();
    }
    
    async loadData() {
        try {
            const response = await fetch(`/api/v1/elections/${this.electionId}/results`);
            const data = await response.json();
            
            this.renderPieChart(data.chart_data, data.candidates);
            this.renderBarChart(data.candidates);
            
            // 통계 데이터 로드
            const statsResponse = await fetch(`/api/v1/elections/${this.electionId}/statistics`);
            const stats = await statsResponse.json();
            
            this.renderLineChart(stats.hourly_distribution);
        } catch (error) {
            console.error('데이터 로드 실패:', error);
        }
    }
    
    renderPieChart(chartData, candidates) {
        const ctx = document.getElementById('pieChart').getContext('2d');
        
        if (this.charts.pie) {
            this.charts.pie.destroy();
        }
        
        this.charts.pie = new Chart(ctx, {
            type: 'doughnut',
            data: chartData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            padding: 20,
                            font: { size: 13 }
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const candidate = candidates[context.dataIndex];
                                return ` ${candidate.name}: ${candidate.vote_count}표 (${candidate.percentage}%)`;
                            }
                        }
                    }
                },
                cutout: '65%',
                animation: {
                    animateRotate: true,
                    duration: 800
                }
            }
        });
    }
    
    renderBarChart(candidates) {
        const ctx = document.getElementById('barChart').getContext('2d');
        
        if (this.charts.bar) {
            this.charts.bar.destroy();
        }
        
        this.charts.bar = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: candidates.map(c => c.name),
                datasets: [{
                    label: '득표수',
                    data: candidates.map(c => c.vote_count),
                    backgroundColor: [
                        'rgba(91, 143, 168, 0.8)',
                        'rgba(130, 184, 122, 0.8)',
                        'rgba(224, 169, 109, 0.8)',
                        'rgba(155, 143, 192, 0.8)',
                    ],
                    borderColor: [
                        '#5b8fa8', '#82b87a', '#e0a96d', '#9b8fc0'
                    ],
                    borderWidth: 2,
                    borderRadius: 8,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: { color: 'rgba(0,0,0,0.05)' },
                        ticks: { font: { size: 12 } }
                    },
                    x: {
                        grid: { display: false },
                        ticks: { font: { size: 12 } }
                    }
                },
                animation: { duration: 600 }
            }
        });
    }
    
    renderLineChart(hourlyData) {
        const ctx = document.getElementById('lineChart').getContext('2d');
        
        if (this.charts.line) {
            this.charts.line.destroy();
        }
        
        this.charts.line = new Chart(ctx, {
            type: 'line',
            data: {
                labels: hourlyData.labels,
                datasets: [{
                    label: '시간별 투표수',
                    data: hourlyData.data,
                    borderColor: '#5b8fa8',
                    backgroundColor: 'rgba(91, 143, 168, 0.1)',
                    borderWidth: 2.5,
                    pointBackgroundColor: '#5b8fa8',
                    pointRadius: 5,
                    fill: true,
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: { color: 'rgba(0,0,0,0.05)' }
                    },
                    x: {
                        grid: { display: false }
                    }
                }
            }
        });
    }
    
    // 실시간 폴링 (15초마다)
    startPolling() {
        this.pollingInterval = setInterval(async () => {
            try {
                const response = await fetch(`/api/v1/elections/${this.electionId}/live`);
                const data = await response.json();
                this.updateCharts(data);
            } catch (error) {
                console.error('폴링 오류:', error);
            }
        }, 15000);
    }
    
    updateCharts(liveData) {
        // 막대 차트 업데이트
        if (this.charts.bar) {
            this.charts.bar.data.datasets[0].data = 
                liveData.candidates.map(c => c.vote_count);
            this.charts.bar.update('active');
        }
        
        // 파이 차트 업데이트
        if (this.charts.pie) {
            this.charts.pie.data.datasets[0].data = 
                liveData.candidates.map(c => c.vote_count);
            this.charts.pie.update('active');
        }
        
        // 총 투표수 업데이트
        document.getElementById('total-votes').textContent = 
            liveData.total_votes.toLocaleString();
    }
    
    destroy() {
        if (this.pollingInterval) {
            clearInterval(this.pollingInterval);
        }
        Object.values(this.charts).forEach(chart => chart.destroy());
    }
}

// 초기화
document.addEventListener('DOMContentLoaded', () => {
    const electionId = document.getElementById('election-data').dataset.id;
    window.dashboard = new VotingDashboard(electionId);
});

📊 대시보드 차트 구성 득표율 도넛 차트 파이/도넛 차트 후보별 득표 비율 막대 차트 후보별 득표수 비교 라인 차트 시간별 투표 추이 Chart.js v4 기반 반응형 차트 15초 폴링으로 실시간 업데이트 · 모바일 최적화 · 애니메이션 효과

⚡ 8. Livewire로 실시간 대시보드 구현

Livewire는 라라벨의 진짜 킬러 기능 중 하나야. JavaScript 없이도 PHP만으로 실시간 UI를 만들 수 있거든. 블록체인 투표 대시보드에 딱이지! 🔥


8-1. Livewire 컴포넌트 생성
# Livewire 컴포넌트 생성
php artisan make:livewire VotingDashboard
php artisan make:livewire LiveVoteCounter
php artisan make:livewire RecentVotesFeed
8-2. 실시간 투표 카운터 컴포넌트
<?php
// app/Livewire/LiveVoteCounter.php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Election;
use App\Models\VoteEvent;

class LiveVoteCounter extends Component
{
    public int $electionId;
    public int $totalVotes = 0;
    public array $candidateVotes = [];
    public string $lastUpdated = '';
    
    // 15초마다 자동 폴링
    protected $polling = '15s';
    
    public function mount(int $electionId): void
    {
        $this->electionId = $electionId;
        $this->refresh();
    }
    
    public function refresh(): void
    {
        $election = Election::with('candidates')->find($this->electionId);
        
        if (!$election) return;
        
        $this->totalVotes = $election->total_votes;
        $this->candidateVotes = $election->candidates->map(fn($c) => [
            'id' => $c->id,
            'name' => $c->name,
            'votes' => $c->vote_count,
            'percentage' => $c->vote_percentage,
        ])->toArray();
        
        $this->lastUpdated = now()->format('H:i:s');
    }
    
    public function render()
    {
        return view('livewire.live-vote-counter');
    }
}

// app/Livewire/RecentVotesFeed.php
class RecentVotesFeed extends Component
{
    public int $electionId;
    public array $recentVotes = [];
    
    protected $polling = '10s';
    
    public function mount(int $electionId): void
    {
        $this->electionId = $electionId;
        $this->loadRecentVotes();
    }
    
    public function loadRecentVotes(): void
    {
        $this->recentVotes = VoteEvent::where('election_id', $this->electionId)
            ->with('candidate')
            ->latest('voted_at')
            ->take(10)
            ->get()
            ->map(fn($v) => [
                'voter' => substr($v->voter_address, 0, 6) . '...' . substr($v->voter_address, -4),
                'candidate' => $v->candidate->name,
                'tx_hash' => substr($v->transaction_hash, 0, 10) . '...',
                'time' => $v->voted_at->diffForHumans(),
            ])
            ->toArray();
    }
    
    public function render()
    {
        return view('livewire.recent-votes-feed');
    }
}
8-3. Livewire 뷰 파일
<!-- resources/views/livewire/live-vote-counter.blade.php -->
<div class="bg-white rounded-2xl shadow-sm p-6">
    <div class="flex items-center justify-between mb-4">
        <h3 class="text-lg font-bold text-gray-700">🔴 실시간 투표 현황</h3>
        <div class="flex items-center gap-2">
            <span class="w-2 h-2 bg-red-400 rounded-full animate-pulse"></span>
            <span class="text-xs text-gray-400">{{ $lastUpdated }} 기준</span>
        </div>
    </div>
    
    <!-- 총 투표수 -->
    <div class="text-center mb-6">
        <p class="text-5xl font-black text-blue-600">
            {{ number_format($totalVotes) }}
        </p>
        <p class="text-gray-500 mt-1">총 투표 수</p>
    </div>
    
    <!-- 후보별 현황 -->
    @foreach($candidateVotes as $candidate)
    <div class="mb-4">
        <div class="flex justify-between items-center mb-1">
            <span class="font-medium text-gray-700">{{ $candidate['name'] }}</span>
            <span class="text-sm font-bold text-gray-600">
                {{ number_format($candidate['votes']) }}표 ({{ $candidate['percentage'] }}%)
            </span>
        </div>
        <div class="bg-gray-100 rounded-full h-3">
            <div class="bg-blue-400 h-3 rounded-full transition-all duration-700"
                style="width: {{ $candidate['percentage'] }}%">
            </div>
        </div>
    </div>
    @endforeach
</div>

<!-- resources/views/livewire/recent-votes-feed.blade.php -->
<div class="bg-white rounded-2xl shadow-sm p-6">
    <h3 class="text-lg font-bold text-gray-700 mb-4">📋 최근 투표 내역</h3>
    
    <div class="space-y-3">
        @forelse($recentVotes as $vote)
        <div class="flex items-center justify-between py-2 border-b border-gray-50">
            <div>
                <p class="font-mono text-sm text-gray-600">{{ $vote['voter'] }}</p>
                <p class="text-xs text-gray-400">→ {{ $vote['candidate'] }}</p>
            </div>
            <div class="text-right">
                <p class="text-xs text-gray-400">{{ $vote['time'] }}</p>
                <a href="https://sepolia.etherscan.io/tx/{{ $vote['tx_hash'] }}"
                   target="_blank"
                   class="text-xs text-blue-400 hover:underline">
                    Etherscan ↗
                </a>
            </div>
        </div>
        @empty
        <p class="text-gray-400 text-center py-4">아직 투표 내역이 없습니다</p>
        @endforelse
    </div>
</div>
💡 Livewire 폴링 vs WebSocket: Livewire의 폴링 방식은 설정이 간단하지만, 투표가 매우 빈번하게 발생하는 경우엔 Laravel Echo + Pusher 조합의 WebSocket이 더 효율적이야. 이 프로젝트에서는 블록체인 특성상 15초 블록 타임을 고려해 폴링이 충분해!

🔒 9. 보안 및 성능 최적화

블록체인 기반 시스템이라고 해서 보안을 소홀히 하면 안 돼. 특히 라라벨 백엔드 레이어에서 추가적인 보안 처리가 필요해.


9-1. API 보안
<?php
// app/Http/Middleware/BlockchainApiMiddleware.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;

class BlockchainApiMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        // Rate Limiting: IP당 분당 60회
        $key = 'blockchain-api:' . $request->ip();
        
        if (RateLimiter::tooManyAttempts($key, 60)) {
            return response()->json([
                'error' => '요청 한도 초과. 잠시 후 다시 시도해주세요.',
                'retry_after' => RateLimiter::availableIn($key)
            ], 429);
        }
        
        RateLimiter::hit($key, 60);
        
        // 컨트랙트 주소 검증
        $contractAddress = config('blockchain.contract_address');
        if (empty($contractAddress) || strlen($contractAddress) !== 42) {
            return response()->json(['error' => '블록체인 설정 오류'], 500);
        }
        
        return $next($request);
    }
}

// routes/api.php에 미들웨어 적용
Route::prefix('v1')
    ->middleware(['throttle:60,1', BlockchainApiMiddleware::class])
    ->group(function () {
        // ... 라우트들
    });
9-2. 성능 최적화 전략
최적화 항목 방법 효과
블록체인 RPC 캐싱 Redis + 30초 TTL RPC 호출 90% 감소
DB 쿼리 최적화 Eager Loading, 인덱스 N+1 문제 해결
이벤트 동기화 Queue + 비동기 처리 응답 시간 단축
차트 데이터 API 응답 캐싱 5분 서버 부하 감소
정적 자산 Vite 번들링 + CDN 로딩 속도 향상
9-3. 지갑 주소 검증
<?php
// app/Rules/EthereumAddress.php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class EthereumAddress implements Rule
{
    public function passes($attribute, $value): bool
    {
        // 이더리움 주소 형식 검증 (0x + 40자 hex)
        return preg_match('/^0x[0-9a-fA-F]{40}$/', $value) === 1;
    }
    
    public function message(): string
    {
        return '유효하지 않은 이더리움 주소입니다.';
    }
}

// 사용 예시
$request->validate([
    'voter_address' => ['required', new EthereumAddress()],
    'election_id' => 'required|integer|exists:elections,blockchain_id',
]);
9-4. 환경별 설정 분리
# 개발 환경 (.env.development)
ETHEREUM_RPC_URL=https://eth-sepolia.g.alchemy.com/v2/DEV_KEY
VOTING_CONTRACT_ADDRESS=0xDEV_CONTRACT_ADDRESS
CHAIN_ID=11155111  # Sepolia

# 프로덕션 환경 (.env.production)
ETHEREUM_RPC_URL=https://eth-mainnet.g.alchemy.com/v2/PROD_KEY
VOTING_CONTRACT_ADDRESS=0xPROD_CONTRACT_ADDRESS
CHAIN_ID=1  # Ethereum Mainnet

# 캐시 설정 (프로덕션에서 더 길게)
BLOCKCHAIN_CACHE_TTL=60
BLOCKCHAIN_POLLING_INTERVAL=30

🧪 10. 테스트 작성

블록체인 시스템에서 테스트는 선택이 아니라 필수야. 특히 실제 블록체인 호출 없이 테스트하려면 Mock 객체를 잘 활용해야 해.


<?php
// tests/Unit/BlockchainServiceTest.php

namespace Tests\Unit;

use Tests\TestCase;
use App\Services\BlockchainService;
use Mockery;

class BlockchainServiceTest extends TestCase
{
    public function test_get_election_results_returns_cached_data(): void
    {
        // BlockchainService Mock
        $mockService = Mockery::mock(BlockchainService::class);
        $mockService->shouldReceive('getElectionResults')
            ->with(1)
            ->once()
            ->andReturn([
                ['id' => 1, 'name' => '후보 A', 'voteCount' => 150],
                ['id' => 2, 'name' => '후보 B', 'voteCount' => 100],
                ['id' => 3, 'name' => '후보 C', 'voteCount' => 75],
            ]);
        
        $this->app->instance(BlockchainService::class, $mockService);
        
        $results = app(BlockchainService::class)->getElectionResults(1);
        
        $this->assertCount(3, $results);
        $this->assertEquals('후보 A', $results[0]['name']);
        $this->assertEquals(150, $results[0]['voteCount']);
    }
    
    public function test_vote_percentage_calculation(): void
    {
        $election = Election::factory()->create(['total_votes' => 200]);
        $candidate = Candidate::factory()->create([
            'election_id' => $election->id,
            'vote_count' => 100
        ]);
        
        $this->assertEquals(50.0, $candidate->vote_percentage);
    }
}

// tests/Feature/ElectionApiTest.php
class ElectionApiTest extends TestCase
{
    use RefreshDatabase;
    
    public function test_results_endpoint_returns_chart_data(): void
    {
        $election = Election::factory()
            ->has(Candidate::factory()->count(3))
            ->create();
        
        $response = $this->getJson("/api/v1/elections/{$election->id}/results");
        
        $response->assertStatus(200)
            ->assertJsonStructure([
                'success',
                'election' => ['id', 'title', 'total_votes', 'status'],
                'chart_data' => ['labels', 'datasets'],
                'candidates' => [
                    '*' => ['id', 'name', 'vote_count', 'percentage']
                ]
            ]);
    }
    
    public function test_live_endpoint_returns_realtime_data(): void
    {
        $election = Election::factory()->create();
        
        $response = $this->getJson("/api/v1/elections/{$election->id}/live");
        
        $response->assertStatus(200)
            ->assertJsonStructure([
                'total_votes',
                'candidates',
                'recent_activity',
                'last_updated'
            ]);
    }
}
💡 테스트 팁: 실제 블록체인 RPC를 테스트에서 호출하면 느리고 비용이 들어. Mockery나 라라벨의 Http::fake()를 활용해서 블록체인 응답을 모킹하는 게 좋아!

🚀 11. 배포 및 운영
11-1. Docker Compose 설정
# docker-compose.yml
version: '3.8'

services:
  app:
    build: .
    ports:
      - "8000:8000"
    environment:
      - APP_ENV=production
    depends_on:
      - mysql
      - redis
    volumes:
      - .:/var/www/html
  
  mysql:
    image: mysql:8.0
    environment:
      MYSQL_DATABASE: blockchain_voting
      MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
    volumes:
      - mysql_data:/var/lib/mysql
  
  redis:
    image: redis:7-alpine
    command: redis-server --appendonly yes
    volumes:
      - redis_data:/data
  
  queue_worker:
    build: .
    command: php artisan queue:work --sleep=3 --tries=3
    depends_on:
      - mysql
      - redis
  
  scheduler:
    build: .
    command: php artisan schedule:work
    depends_on:
      - mysql
      - redis

volumes:
  mysql_data:
  redis_data:
11-2. 운영 체크리스트
🔍 배포 전 체크리스트 1 APP_ENV=production, APP_DEBUG=false 확인

2 컨트랙트 주소와 ABI 파일이 올바른지 확인

3 Redis 연결 상태 확인 (php artisan tinker에서 Cache::put('test', 1))

4 큐 워커 실행 중인지 확인 (php artisan queue:work)

5 스케줄러 crontab 등록 확인

6 블록체인 동기화 초기 실행 (php artisan blockchain:sync --from-block=0)

7 Etherscan에서 컨트랙트 검증 완료 여부 확인

💡 12. 확장 아이디어 및 고급 기능

기본 시스템을 완성했다면, 이제 더 멋진 기능들을 추가해볼 수 있어! 재능넷 같은 플랫폼에서 이런 프로젝트를 포트폴리오로 보여주면 정말 임팩트 있을 거야. 😎


🗺️
지역별
투표 히트맵
📱
MetaMask
연동 투표
🔔
투표 완료
알림 시스템
📊
AI 예측
분석
🌐
다국어
지원
12-1. MetaMask 연동 투표 기능
// resources/js/metamask-voting.js

class MetaMaskVoting {
    constructor() {
        this.provider = null;
        this.signer = null;
        this.contract = null;
    }
    
    async connect() {
        if (!window.ethereum) {
            alert('MetaMask를 설치해주세요!');
            return false;
        }
        
        try {
            // 지갑 연결 요청
            const accounts = await window.ethereum.request({
                method: 'eth_requestAccounts'
            });
            
            // ethers.js로 프로바이더 설정
            this.provider = new ethers.BrowserProvider(window.ethereum);
            this.signer = await this.provider.getSigner();
            
            // 컨트랙트 인스턴스
            this.contract = new ethers.Contract(
                CONTRACT_ADDRESS,
                CONTRACT_ABI,
                this.signer
            );
            
            return accounts[0];
        } catch (error) {
            console.error('MetaMask 연결 실패:', error);
            return false;
        }
    }
    
    async castVote(electionId, candidateId) {
        if (!this.contract) {
            await this.connect();
        }
        
        try {
            // 트랜잭션 전송
            const tx = await this.contract.castVote(electionId, candidateId);
            
            // 트랜잭션 확인 대기
            const receipt = await tx.wait();
            
            return {
                success: true,
                txHash: receipt.hash,
                blockNumber: receipt.blockNumber
            };
        } catch (error) {
            if (error.code === 'ACTION_REJECTED') {
                return { success: false, error: '사용자가 거부했습니다.' };
            }
            return { success: false, error: error.message };
        }
    }
}
12-2. 투표 결과 PDF 내보내기
<?php
// app/Http/Controllers/ExportController.php

use Barryvdh\DomPDF\Facade\Pdf;

class ExportController extends Controller
{
    public function exportPdf(int $electionId): \Illuminate\Http\Response
    {
        $election = Election::with('candidates', 'voteEvents')->findOrFail($electionId);
        
        $pdf = Pdf::loadView('exports.election-results', [
            'election' => $election,
            'generatedAt' => now()->format('Y년 m월 d일 H:i:s'),
            'contractAddress' => config('blockchain.contract_address'),
        ]);
        
        return $pdf->download("선거결과_{$election->title}.pdf");
    }
}
🎯 이 프로젝트를 포트폴리오로 활용하려면? 재능넷 같은 재능 공유 플랫폼에서 블록체인 개발 서비스를 제공할 때, 이런 풀스택 프로젝트는 정말 강력한 포트폴리오가 돼. 특히 라라벨 + 블록체인 조합을 할 수 있는 개발자는 아직 많지 않아서 차별화 포인트가 될 수 있어!

🗺️ 개발 로드맵 ⛓️ 1단계 스마트 컨트랙트 작성 및 배포 🔴 2단계 라라벨 백엔드 API 개발 🔄 3단계 이벤트 동기화 시스템 구축 📊 4단계 대시보드 시각화 Chart.js + Livewire 1~2일 Solidity 작성 2~3일 서비스 레이어 1~2일 큐 & 스케줄러 2~3일 UI & 차트 ⏱️ 총 예상 개발 기간 약 6~10일 (혼자 개발 기준) Solidity · Laravel · Web3.php · Chart.js · Livewire · Redis · MySQL Hardhat · Alchemy · Etherscan · Docker · Tailwind CSS

🎉 13. 마무리 및 핵심 정리

자, 여기까지 왔으면 진짜 대단한 거야! 👏 라라벨로 블록체인 투표 결과 시각화 대시보드를 만드는 전체 여정을 함께 걸어봤어. 핵심을 다시 한번 정리해볼게.


🔑 핵심 포인트 총정리 1. 스마트 컨트랙트 (Solidity)
— 투표 로직은 블록체인에서 처리. 변조 불가능한 투명성 보장
— event VoteCast로 라라벨이 감지할 이벤트 발행

2. 라라벨 백엔드
— Web3.php로 블록체인 데이터 읽기
— Redis 캐싱으로 RPC 호출 최소화
— Queue + Scheduler로 이벤트 비동기 동기화

3. 데이터베이스 설계
— 블록체인 데이터의 DB 미러링으로 빠른 조회
— 이벤트 소싱 패턴으로 히스토리 관리

4. 시각화 대시보드
— Chart.js로 파이/막대/라인 차트 구현
— Livewire 폴링으로 실시간 업데이트
— Blade 템플릿으로 서버사이드 렌더링

이 프로젝트는 단순한 토이 프로젝트가 아니야. 실제 DAO(탈중앙화 자율 조직) 거버넌스 투표, 기업 내부 의사결정 시스템, 학교 학생회 선거 등 다양한 실제 사용 사례에 적용할 수 있어.


그리고 재능넷에서 블록체인 개발 서비스를 제공하고 싶다면, 이런 풀스택 프로젝트 경험이 정말 큰 무기가 될 거야. 라라벨과 블록체인을 동시에 다룰 수 있는 개발자는 아직 희귀하거든! 💎


⚠️ 실제 배포 시 주의사항 — 메인넷 배포 전 반드시 스마트 컨트랙트 보안 감사 받기
— 개인키는 절대 코드에 하드코딩 금지 (환경변수 사용)
— Alchemy/Infura API 키 사용량 모니터링
— 가스비 최적화를 위한 컨트랙트 코드 리뷰
— 법적 규제 확인 (국가별 전자투표 관련 법률)

블록체인과 라라벨의 만남, 어때? 생각보다 훨씬 재미있고 실용적이지? 이 두 기술의 조합은 앞으로 더 많은 곳에서 활용될 거야. 지금 시작하면 선점 효과를 누릴 수 있어! 🚀


궁금한 점이나 막히는 부분이 있으면 언제든지 질문해. 같이 해결해나가는 게 개발의 묘미니까! 😄

🔗 블록체인/Web3 × 프로그램개발 라라벨 · 솔리디티 · Web3.php · Chart.js · Livewire

댓글 작성

이 글에 대한 여러분의 생각을 들려주세요

댓글 0
댓글을 불러오는 중입니다.

아직 댓글이 없습니다.