Prompt Example
너는 Java 프로그래야. Java를 이용하여 기본 블록체인 구현 코드를 작성해줄 수 있어?
Result
네, 아래는 JavaScript를 활용하여 기본 블록체인 기술을 구현한 코드입니다.
const SHA256 = require('crypto-js/sha256');
class Block {
constructor(index, timestamp, data, previousHash = '') {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.previousHash = previousHash;
this.hash = this.calculateHash();
}
calculateHash() {
return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();
}
}
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
}
createGenesisBlock() {
return new Block(0, new Date().toString(), "Genesis Block", "0");
}
getLatestBlock() {
return this.chain[this.chain.length - 1];
}
addBlock(newBlock) {
newBlock.previousHash = this.getLatestBlock().hash;
newBlock.hash = newBlock.calculateHash();
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];
if (currentBlock.hash !== currentBlock.calculateHash()) {
return false;
}
if (currentBlock.previousHash !== previousBlock.hash) {
return false;
}
}
return true;
}
}
let myBlockchain = new Blockchain();
myBlockchain.addBlock(new Block(1, new Date().toString(), {amount: 100}));
myBlockchain.addBlock(new Block(2, new Date().toString(), {amount: 50}));
console.log(JSON.stringify(myBlockchain, null, 4));
console.log("Is blockchain valid? " + myBlockchain.isChainValid());
위 코드에서 `Block` 클래스는 블록의 구조를 정의하고, `Blockchain` 클래스는 블록들을 체인으로 연결하는 구조체를 정의합니다.
`Blockchain` 클래스에서는 `createGenesisBlock()` 함수를 통해 첫 번째 블록을 생성하고, `getLatestBlock()` 함수를 통해 가장 최근에 생성된 블록을 찾습니다. `addBlock()` 함수를 사용하여 새로운 블록을 추가하고, 'isChainValid()` 함수를 사용하여 체인의 유효성을 검증합니다.
위 코드에서는 새로운 블록 2개를 추가하고, 체인의 구조를 콘솔에 출력하고 있습니다. 또한, `isChainValid()` 함수를 호출하여 체인의 유효성을 검증합니다. 이 코드를 실행하면 다음과 같은 결과가 나옵니다.
{
"chain": [
{
"index": 0,
"timestamp": "Sun May 09 2021 17:01:24 GMT-0700 (Pacific Daylight Time)",
"data": "Genesis Block",
"previousHash": "0",
"hash": "505e58b857c2d6783a43fa8c2e6e2c6f33f4221f9e1ec01cf407f16b0f7b1574"
},
{
"index": 1,
"timestamp": "Sun May 09 2021 17:01:24 GMT-0700 (Pacific Daylight Time)",
"data": {
"amount": 100
},
"previousHash": "505e58b857c2d6783a43fa8c2e6e2c6f33f4221f9e1ec01cf407f16b0f7b1574",
"hash": "50a135fc9f78bba1672aa50888f107a6a100d6b7aa6ec07a6c3ef6f3f9b63d22"
},
{
"index": 2,
"timestamp": "Sun May 09 2021 17:01:24 GMT-0700 (Pacific Daylight Time)",
"data": {
"amount": 50
},
"previousHash": "50a135fc9f78bba1672aa50888f107a6a100d6b7aa6ec07a6c3ef6f3f9b63d22",
"hash": "48aafe5e5ec7e5ed5d0154b4e4c654aad9547a33b496c5b91a6c9050c0b74bb8"
}
]
}
Is blockchain valid? true
블록 0은 genesis 블록으로 이전 해시 값이 0입니다. 그리고 블록 1과 2는 이전 해시 값이 이전 블록의 해시 값과 같습니다. 또한 `isChainValid()` 함수가 true를 반환하여 블록체인의 유효성을 검증합니다.