Mayıs 6, 2025
Okuma süresi: 14 dakika
Blockchain teknolojisi, merkezi olmayan, şeffaf ve güvenli bir veri yönetimi sunarak finans, tedarik zinciri, sağlık hizmetleri ve daha birçok sektörde devrim yaratmaktadır. Bu makale, blockchain teknolojisinin temellerini anlamak ve kendi blockchain uygulamalarınızı geliştirmeye başlamak isteyenler için kapsamlı bir rehber sunmaktadır.
Blockchain, bilgilerin bloklarda saklandığı ve kriptografik olarak birbirine bağlandığı dağıtık bir veri yapısıdır. Her blok şunları içerir:
Blockchain'in en önemli özellikleri şunlardır:
Blockchain teknolojisi temel olarak kriptografiye dayanmaktadır:
// SHA-256 hash fonksiyonu örneği
const crypto = require('crypto');
function createHash(data) {
return crypto.createHash('sha256').update(data).digest('hex');
}
const blockData = "İşlem1, İşlem2, İşlem3";
console.log(createHash(blockData));
// Çıktı: 7d9f3267a2760f278c129572e52d8fb0708ea8da5652863756c7ecb44c3b7091
// Asimetrik Şifreleme Örneği
const crypto = require('crypto');
// Anahtar çifti oluşturma
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
});
// Mesajı özel anahtarla imzalama
function signMessage(message, privateKey) {
const signer = crypto.createSign('RSA-SHA256');
signer.update(message);
return signer.sign(privateKey, 'hex');
}
// İmzayı açık anahtarla doğrulama
function verifySignature(message, signature, publicKey) {
const verifier = crypto.createVerify('RSA-SHA256');
verifier.update(message);
return verifier.verify(publicKey, signature, 'hex');
}
const message = "Blockchain'e hoş geldiniz!";
const signature = signMessage(message, privateKey);
console.log(verifySignature(message, signature, publicKey)); // true
Basit bir blockchain uygulaması geliştirmeye başlarken, temel veri yapısını anlamak önemlidir:
class Block {
constructor(index, timestamp, data, previousHash = '') {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.previousHash = previousHash;
this.hash = this.calculateHash();
this.nonce = 0;
}
calculateHash() {
return crypto.createHash('sha256')
.update(this.index + this.timestamp + JSON.stringify(this.data) + this.previousHash + this.nonce)
.digest('hex');
}
mineBlock(difficulty) {
// "0" ile başlayan hash değeri bulunana kadar nonce değerini artırır
while (this.hash.substring(0, difficulty) !== Array(difficulty + 1).join("0")) {
this.nonce++;
this.hash = this.calculateHash();
}
console.log("Blok kazıldı: " + this.hash);
}
}
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
this.difficulty = 4; // 0000 ile başlayan hash değerleri
}
createGenesisBlock() {
return new Block(0, "01/01/2025", "Genesis Block", "0");
}
getLatestBlock() {
return this.chain[this.chain.length - 1];
}
addBlock(newBlock) {
newBlock.previousHash = this.getLatestBlock().hash;
newBlock.mineBlock(this.difficulty);
this.chain.push(newBlock);
}
isChainValid() {
for (let i = 1; i < this.chain.length; i++) {
const currentBlock = this.chain[i];
const previousBlock = this.chain[i - 1];
// Hash değerini yeniden hesaplayıp kontrol eder
if (currentBlock.hash !== currentBlock.calculateHash()) {
return false;
}
// Zincirdeki bağlantıyı kontrol eder
if (currentBlock.previousHash !== previousBlock.hash) {
return false;
}
}
return true;
}
}
Akıllı sözleşmeler, blockchain üzerinde otomatik olarak çalışan kod parçalarıdır. İşte Solidity ile yazılmış basit bir akıllı sözleşme örneği:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract BasicToken {
string public name = "TeknikZeka Token";
string public symbol = "TZT";
uint8 public decimals = 18;
uint256 public totalSupply = 1000000 * (10 ** uint256(decimals));
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor() {
balanceOf[msg.sender] = totalSupply;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value, "Yetersiz bakiye");
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value, "Yetersiz bakiye");
require(allowance[_from][msg.sender] >= _value, "İzin yetersiz");
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
}
}
Blockchain ağlarında veri doğruluğunu sağlamak için farklı konsensüs mekanizmaları kullanılır:
// Web3.js Örneği
const Web3 = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_KEY');
async function getBalance(address) {
const balance = await web3.eth.getBalance(address);
return web3.utils.fromWei(balance, 'ether');
}
// Ethers.js Örneği
const { ethers } = require('ethers');
const provider = new ethers.providers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR_INFURA_KEY');
async function getEthBalance(address) {
const balance = await provider.getBalance(address);
return ethers.utils.formatEther(balance);
}
# Web3.py Örneği
from web3 import Web3
web3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR_INFURA_KEY'))
def get_balance(address):
balance_wei = web3.eth.get_balance(address)
balance_eth = web3.from_wei(balance_wei, 'ether')
return balance_eth
// Mocha & Chai ile Truffle Test Örneği
const Token = artifacts.require("BasicToken");
contract("BasicToken", accounts => {
let tokenInstance;
before(async () => {
tokenInstance = await Token.deployed();
});
it("doğru başlangıç arzını ayarlamalı", async () => {
const totalSupply = await tokenInstance.totalSupply();
assert.equal(
totalSupply.toString(),
'1000000000000000000000000',
"Toplam arz 1,000,000 token olmalı"
);
});
it("para transferi yapabilmeli", async () => {
// Token gönderme
await tokenInstance.transfer(accounts[1], '1000000000000000000', { from: accounts[0] });
// Bakiyeleri kontrol etme
const account1Balance = await tokenInstance.balanceOf(accounts[1]);
assert.equal(
account1Balance.toString(),
'1000000000000000000',
"Alıcı hesaba 1 token transfer edilmeli"
);
});
});
Türkiye'deki blockchain geliştirme ekosistemi şu düzenlemelerle şekillendirilmektedir:
# Truffle ve Ganache kurulumu
npm install -g truffle
npm install -g ganache-cli
# Yeni bir Truffle projesi oluşturma
mkdir ilk-blockchain-projem
cd ilk-blockchain-projem
truffle init
contracts/EnvanterTakip.sol dosyasını oluşturun:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract EnvanterTakip {
struct Urun {
uint id;
string isim;
uint miktar;
string uretimYeri;
uint uretimTarihi;
address uretici;
}
mapping(uint => Urun) public urunler;
uint public urunSayisi;
event UrunEklendi(uint id, string isim, uint miktar);
event UrunGuncellendi(uint id, uint yeniMiktar);
function urunEkle(
string memory _isim,
uint _miktar,
string memory _uretimYeri,
uint _uretimTarihi
) public returns (uint) {
urunSayisi++;
urunler[urunSayisi] = Urun(
urunSayisi,
_isim,
_miktar,
_uretimYeri,
_uretimTarihi,
msg.sender
);
emit UrunEklendi(urunSayisi, _isim, _miktar);
return urunSayisi;
}
function urunGuncelle(uint _id, uint _yeniMiktar) public {
require(urunler[_id].uretici == msg.sender, "Sadece uretici urunu guncelleyebilir");
require(_id <= urunSayisi, "Urun bulunamadi");
urunler[_id].miktar = _yeniMiktar;
emit UrunGuncellendi(_id, _yeniMiktar);
}
function urunGetir(uint _id) public view returns (
uint id,
string memory isim,
uint miktar,
string memory uretimYeri,
uint uretimTarihi,
address uretici
) {
require(_id <= urunSayisi, "Urun bulunamadi");
Urun memory urun = urunler[_id];
return (
urun.id,
urun.isim,
urun.miktar,
urun.uretimYeri,
urun.uretimTarihi,
urun.uretici
);
}
}
migrations/2_deploy_contracts.js dosyasını oluşturun:
const EnvanterTakip = artifacts.require("EnvanterTakip");
module.exports = function(deployer) {
deployer.deploy(EnvanterTakip);
};
test/envanter_takip_test.js dosyasını oluşturun:
const EnvanterTakip = artifacts.require("EnvanterTakip");
contract("EnvanterTakip", accounts => {
let envanterTakip;
const uretici = accounts[0];
before(async () => {
envanterTakip = await EnvanterTakip.deployed();
});
it("yeni urun ekleyebilmeli", async () => {
const tx = await envanterTakip.urunEkle(
"Laptop",
100,
"Istanbul",
Date.now(),
{ from: uretici }
);
// Olayı kontrol et
assert.equal(tx.logs[0].event, "UrunEklendi", "UrunEklendi olayı yayınlanmalı");
// Ürün sayısını kontrol et
const urunSayisi = await envanterTakip.urunSayisi();
assert.equal(urunSayisi, 1, "Ürün sayısı 1 olmalı");
});
it("urun bilgilerini getirebilmeli", async () => {
const urun = await envanterTakip.urunGetir(1);
assert.equal(urun.isim, "Laptop", "Ürün ismi doğru olmalı");
assert.equal(urun.miktar, 100, "Ürün miktarı doğru olmalı");
assert.equal(urun.uretimYeri, "Istanbul", "Üretim yeri doğru olmalı");
});
it("urun miktarini guncelleyebilmeli", async () => {
await envanterTakip.urunGuncelle(1, 90, { from: uretici });
const urun = await envanterTakip.urunGetir(1);
assert.equal(urun.miktar, 90, "Güncellenen miktar doğru olmalı");
});
});
# Ganache'i başlat
ganache-cli
# Yeni bir terminal penceresinde, sözleşmeleri derle ve dağıt
truffle compile
truffle migrate
# Testleri çalıştır
truffle test
Akıllı sözleşmenizle etkileşim kuran basit bir web uygulaması geliştirebilirsiniz:
<!DOCTYPE html>
<html>
<head>
<title>Envanter Takip Sistemi</title>
<script src="https://cdn.jsdelivr.net/npm/web3@1.5.3/dist/web3.min.js"></script>
<script src="./EnvanterTakip.js"></script>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
button { background-color: #4CAF50; color: white; padding: 10px 15px; border: none; cursor: pointer; }
input, select { padding: 8px; margin: 5px 0; }
table { width: 100%; border-collapse: collapse; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
</style>
</head>
<body>
<h1>Blockchain Tabanlı Envanter Takip Sistemi</h1>
<div id="accountInfo">
<p>Hesap: <span id="account"></span></p>
<p>Bakiye: <span id="balance"></span> ETH</p>
</div>
<h2>Yeni Ürün Ekle</h2>
<div>
<input id="productName" placeholder="Ürün İsmi" />
<input id="productQuantity" type="number" placeholder="Miktar" />
<input id="productLocation" placeholder="Üretim Yeri" />
<button onclick="addProduct()">Ürün Ekle</button>
</div>
<h2>Ürün Listesi</h2>
<table id="productTable">
<thead>
<tr>
<th>ID</th>
<th>Ürün İsmi</th>
<th>Miktar</th>
<th>Üretim Yeri</th>
<th>Üretim Tarihi</th>
<th>Üretici</th>
<th>İşlemler</th>
</tr>
</thead>
<tbody id="productList"></tbody>
</table>
<script>
let web3;
let envanterTakip;
let account;
// Web3 ve Kontrat Bağlantısı
async function init() {
// Modern dapp tarayıcıları
if (window.ethereum) {
try {
web3 = new Web3(window.ethereum);
await window.ethereum.enable();
const accounts = await web3.eth.getAccounts();
account = accounts[0];
document.getElementById('account').innerText = account;
updateBalance();
// Kontrat ABI ve adresi
const contractAddress = '0x...'; // Dağıtım sonrası kontrat adresi
envanterTakip = new web3.eth.Contract(EnvanterTakipABI, contractAddress);
loadProducts();
} catch (error) {
console.error("Miktar güncellenirken hata:", error);
}
}
}
// Form alanlarını temizleme
function clearForm() {
document.getElementById('productName').value = '';
document.getElementById('productQuantity').value = '';
document.getElementById('productLocation').value = '';
}
// Sayfa yüklendiğinde başlat
window.addEventListener('load', init);
</script>
</body>
</html>
Blockchain teknolojisi, finansal sistemleri kökten değiştirme potansiyeline sahiptir:
NFT (Non-Fungible Token) teknolojisi, benzersiz dijital varlıkların sahipliğini temsil etmektedir:
Blockchain teknolojisi, iş süreçlerini optimize etmede giderek daha fazla kullanılmaktadır:
Blockchain geliştirme, çeşitli sektörlerde devrim yaratma potansiyeline sahip heyecan verici bir alandır. Bu temel bilgileri edinmek, özel veya açık blockchain uygulamaları geliştirme yolculuğunuzun sadece başlangıcıdır.
Teknoloji hızla geliştiği için, sürekli öğrenme ve topluluk ile etkileşim halinde olmak önemlidir. Blockchain tabanlı çözümler geliştirerek, daha şeffaf, güvenli ve verimli sistemlerin oluşturulmasına katkıda bulunabilirsiniz.
Unutmayın ki iyi bir blockchain uygulaması, yalnızca teknik açıdan sağlam olmakla kalmayıp, kullanıcı deneyimi, yasal uyumluluk ve sürdürülebilirlik açısından da iyi tasarlanmış olmalıdır.
Bu makale Teknik Zeka Net tarafından hazırlanmıştır, 6 Mayıs 2025.