core > BlockChainStarter

package core;

import java.util.ArrayList;

public class BlockChainStarter {
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Block block1 = new Block(1, null, 0, new ArrayList<Transaction>());
		block1.mine();
		block1.getInformation();
		
		Block block2 = new Block(2, block1.getBlockHash(), 0, new ArrayList<Transaction>());
		block2.addTransaction(new Transaction("이승엽", "홍길동", 1.5));
		block2.addTransaction(new Transaction("이근혁", "홍길동", 0.7));
		block2.mine();
		block2.getInformation();
		
		Block block3 = new Block(3, block2.getBlockHash(), 0, new ArrayList<Transaction>());
		block3.addTransaction(new Transaction("리로이", "다니엘", 8.2));
		block3.addTransaction(new Transaction("홍길동", "이승엽", 0.4));
		block3.mine();
		block3.getInformation();
		
		Block block4 = new Block(4, block3.getBlockHash(), 0, new ArrayList<Transaction>());
		block4.addTransaction(new Transaction("다니엘", "리로이", 0.1));
		block4.mine();
		block4.getInformation();
	}
}

core > Block

package core;

import java.util.ArrayList;
import util.Util;

public class Block {

	private int blockID; // 블록 아이디
	private String previousBlockHash; // 이전 블록의 해시 값
	private int nonce; // 채굴을 위한 정답
	private ArrayList<Transaction> transactionList; // 블록에 들어가는 데이터(해당 블록이 생성되기 전까지 발생한 신규 트랜잭션들의 정보)
	
	public Block(int blockID, String previousBlockHash, int nonce, ArrayList<Transaction> transactionList) {
		this.blockID = blockID;
		this.previousBlockHash = previousBlockHash;
		this.nonce = nonce;
		this.transactionList = transactionList;
	}
	
	public int getBlockID() {
		return blockID;
	}
	
	public void setBlockID(int blockID) {
		this.blockID = blockID;
	}
	
	public String getPreviousBlockHash() {
		return previousBlockHash;
	}

	public void setPreviousBlockHash(String previousBlockHash) {
		this.previousBlockHash = previousBlockHash;
	}
	
	public int getNonce() {
		return nonce;
	}
	
	public void setNonce(int nonce) {
		this.nonce = nonce;
	}
	
	public void addTransaction(Transaction transaction) {
		transactionList.add(transaction);
	}
	
	public String getBlockHash() { // 해당 블록의 해시 값
		String transactionInformations = "";
		
		for(int i = 0; i < transactionList.size(); i++) {
			transactionInformations += transactionList.get(i).getInformation();
		}
		
		return Util.getHash(nonce + transactionInformations + previousBlockHash);
	}
	
	public void getInformation() { // 특정한 한 개의 블록이 있을 때 이 블록에 대한 정보를 출력
		System.out.println("----------------------------------");
		System.out.println("블록 아이디 : " + getBlockID());
		System.out.println("이전 블록의 해시 값: " + getPreviousBlockHash());
		System.out.println("채굴 정답 : " + getNonce());
		System.out.println("트랜잭션 개수 : " + transactionList.size() + "개");
		
		for(int i = 0; i < transactionList.size(); i++) {
			System.out.println(transactionList.get(i).getInformation());
		}
		
		System.out.println("블록의 해시 값 : " + getBlockHash());
		System.out.println("----------------------------------");
	}
	
	public void mine() {
		while(true) {
			if(getBlockHash().substring(0, 4).equals("0000")) { // nonce + transactionInformations + previousBlockHash의 해시 값이 "0000"으로 시작할 때 채굴에 성공 // 채굴 난이도 고정
				System.out.println(blockID + "번째 블록의 채굴에 성공했습니다.");
				break;
			}
			nonce++;
		}
	}
}

core > Transaction

package core;

public class Transaction {
	
	String sender;
	String receiver;
	double amount;
	
	public Transaction(String sender, String receiver, double amount) {
		this.sender = sender;
		this.receiver = receiver;
		this.amount = amount;
	}
	
	public String getSender() {
		return sender;
	}
	
	public void setSender(String sender) {
		this.sender = sender;
	}
	
	public String getReceiver() {
		return receiver;
	}
	
	public void setReceiver(String receiver) {
		this.receiver = receiver;
	}
	
	public double getAmount() {
		return amount;
	}
	
	public void setAmount(double amount) {
		this.amount = amount;
	}
	
	public String getInformation() {
		return sender + "이(가) " + receiver + "에게 " + amount + "개의 코인을 보냈습니다.";
	}
}

util > Util

package util;

import java.security.MessageDigest;

public class Util {
	
	public static String getHash(String input) { // 단순 문자열 input
		StringBuffer result = new StringBuffer();
		
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-256"); // Secure Hash Algorithm // 256비트로 구성 // 64자리 문자열 반환
			md.update(input.getBytes());
			byte bytes[] = md.digest();
			
			for(int i = 0; i < bytes.length; i++) {
				result.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return result.toString(); // SHA-256 해시를 적용한 결과 리턴
	}
}

 

 

'Block Chain' 카테고리의 다른 글

[Block Chain] Java 실습-2  (0) 2022.12.21
[Block Chain] Java 실습-1  (0) 2022.12.19
[Block Chain] 암호화폐  (0) 2022.12.01
[Block Chain] 해시  (0) 2022.12.01
[Block Chain] 쉽게 이해하기  (0) 2022.11.30

core > BlockChainStarter

package core;

public class BlockChainStarter {
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Block block1 = new Block(1, null, 0, "데이터"); // 블록 아이디, 이전 블록의 해시 값, 채굴을 위한 정답, 블록에 들어가는 데이터
		block1.mine();
		block1.getInformation();
		
		Block block2 = new Block(2, block1.getBlockHash(), 0, "데이터");
		block2.mine();
		block2.getInformation();
		
		Block block3 = new Block(3, block2.getBlockHash(), 0, "데이터");
		block3.mine();
		block3.getInformation();
		
		Block block4 = new Block(4, block3.getBlockHash(), 0, "데이터");
		block4.mine();
		block4.getInformation();
	}
}

core > Block

package core;

import util.Util;

public class Block {

	private int blockID; // 블록 아이디
	private String previousBlockHash; // 이전 블록의 해시 값
	private int nonce; // 채굴을 위한 정답
	private String data; // 블록에 들어가는 데이터
	
	public Block(int blockID, String previousBlockHash, int nonce, String data) {
		this.blockID = blockID;
		this.previousBlockHash = previousBlockHash;
		this.nonce = nonce;
		this.data = data;
	}
	
	public int getBlockID() {
		return blockID;
	}
	
	public void setBlockID(int blockID) {
		this.blockID = blockID;
	}
	
	public String getPreviousBlockHash() {
		return previousBlockHash;
	}

	public void setPreviousBlockHash(String previousBlockHash) {
		this.previousBlockHash = previousBlockHash;
	}
	
	public int getNonce() {
		return nonce;
	}
	
	public void setNonce(int nonce) {
		this.nonce = nonce;
	}
	
	public String getData() {
		return data;
	}
	
	public void setData(String data) {
		this.data = data;
	}
	
	public String getBlockHash() { // 해당 블록의 해시 값
		return Util.getHash(nonce + data + previousBlockHash);
	}
	
	public void getInformation() { // 특정한 한 개의 블록이 있을 때 이 블록에 대한 정보를 출력
		System.out.println("----------------------------------");
		System.out.println("블록 아이디 : " + getBlockID());
		System.out.println("이전 블록의 해시 값: " + getPreviousBlockHash());
		System.out.println("채굴 정답 : " + getNonce());
		System.out.println("블록 데이터 : " + getData());
		System.out.println("블록의 해시 값 : " + getBlockHash());
		System.out.println("----------------------------------");
	}
	
	public void mine() {
		while(true) {
			if(getBlockHash().substring(0, 4).equals("0000")) { // nonce + data + previousBlockHash의 해시 값이 "0000"으로 시작할 때 채굴에 성공 // 채굴 난이도 고정
				System.out.println(blockID + "번째 블록의 채굴에 성공했습니다.");
				break;
			}
			nonce++;
		}
	}
}

util > Util

package util;

import java.security.MessageDigest;

public class Util {
	
	public static String getHash(String input) { // 단순 문자열 input
		StringBuffer result = new StringBuffer();
		
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-256"); // Secure Hash Algorithm // 256비트로 구성 // 64자리 문자열 반환
			md.update(input.getBytes());
			byte bytes[] = md.digest();
			
			for(int i = 0; i < bytes.length; i++) {
				result.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return result.toString(); // SHA-256 해시를 적용한 결과 리턴
	}
}

 

<정상적인 경우>

<특정 블록의 데이터 변조>

 

<블록체인 해킹이 불가능한 이유>

1. 특정 블록의 데이터가 변조된다면 이후 모든 블록의 해시 값이 달라진다.

즉, 특정 블록의 데이터 변조를 위해서는 이후 모든 블록에 대한 채굴을 다시 수행해야 한다는 것

2. 이후 모든 블록에 대한 채굴을 다시 수행하여 이전에 발생했던 트랜잭션 정보를

변조하는데 성공했다고 하더라도 전체 네트워크에서 50% 이상의 컴퓨팅 파워를 갖고 있지 않은 이상

올바른 블록체인으로 인정받을 수 없다.

해커의 블록체인 vs 그 외 모든 사람들(과반수)의 블록체인 => 해커의 블록체인은 무시됨

'Block Chain' 카테고리의 다른 글

[Block Chain] Java 실습-3  (0) 2022.12.21
[Block Chain] Java 실습-1  (0) 2022.12.19
[Block Chain] 암호화폐  (0) 2022.12.01
[Block Chain] 해시  (0) 2022.12.01
[Block Chain] 쉽게 이해하기  (0) 2022.11.30

core > BlockChainStarter

package core;

import util.Util;

public class BlockChainStarter {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// STEP 1. 해시 알고리즘은 입력 값이 조금만 바뀌어도 결과는 완전히 다른 값이 나온다. 채굴의 원리는 이러한 눈사태 효과에서 출발한다.
		System.out.println(Util.getHash("이승엽")); // 0c2bc0396e93dcc356680303162ced49c0fe2fed31ed1da7753113e413a2c06a
		System.out.println(Util.getHash("이승엽1")); // 55868675c69c4009a2dc5baa44b5326f93429b587b10828a622de61bca097bd7
		
		// STEP 2. 작업 증명(Proof of Work) : 비트코인에서 사용되고 있는 채굴 방식
		int nonce = 0;
		
		while(true) { // 채굴
			
			// 16진수 6자리 => 16 x 16 x 16 x 16 x 16 x 16 => 2의 24승(난이도)
			if(Util.getHash(nonce + "").substring(0, 6).equals("000000")) { // 어떠한 숫자 nonce를 문자열 형태로 바꾼 후 이것의 해시 값이 "000000"으로 시작할 때 채굴에 성공
				System.out.println("정답 : " + nonce); // 665782
				System.out.println("해시 값 : " + Util.getHash(nonce + "")); // 0000000399c6aea5ad0c709a9bc331a3ed6494702bd1d129d8c817a0257a1462
				break;
			}
			
			nonce++; // nonce 1씩 증가
		}
		// 작업 증명이라는 합의 알고리즘을 사용하는 블록체인 시스템은 이처럼 무작위의 입력값을 대입하여 정답(nonce)을 구하는 방식으로 채굴이 가능하도록 설계가 되어있다.
	}
}

util > Util

package util;

import java.security.MessageDigest;

public class Util {
	
	public static String getHash(String input) { // 단순 문자열 input
		StringBuffer result = new StringBuffer();
		
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-256"); // Secure Hash Algorithm // 256비트로 구성 // 64자리 문자열 반환
			md.update(input.getBytes());
			byte bytes[] = md.digest();
			
			for(int i = 0; i < bytes.length; i++) {
				result.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return result.toString(); // SHA-256 해시를 적용한 결과 리턴
	}
}

 

 

'Block Chain' 카테고리의 다른 글

[Block Chain] Java 실습-3  (0) 2022.12.21
[Block Chain] Java 실습-2  (0) 2022.12.21
[Block Chain] 암호화폐  (0) 2022.12.01
[Block Chain] 해시  (0) 2022.12.01
[Block Chain] 쉽게 이해하기  (0) 2022.11.30
public class Solution {
	
	// 잃어버린 괄호 - Greedy 1541번
	
	public static int solution(String str) {
		String[] strArr1 = str.split("-"); // 문자 "-" 기준으로 split
		int totalSum = 0;
		int tempSum = 0;
		
		// strArr1 = {"55", "50+40", "20", "30+40"}
		
		for (int i = 0; i < strArr1.length; i++) {
			
			tempSum = 0;
			
			String[] strArr2 = strArr1[i].split("\\+"); // 특수문자 "+" 기준으로 split (특수문자의 경우 \\특수문자 or [특수문자])
			
			for (int j = 0; j < strArr2.length; j++) {
				tempSum += Integer.parseInt(strArr2[j]);
			}
			
			if (i == 0) { // 처음 구간은 +
				totalSum += tempSum; // +55
			} else { // 이후 구간은 -
				totalSum -= tempSum; // -90-20-70
			}
		}
		
		return totalSum;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str = "55-50+40-20-30+40"; // (55)-(50+40)-(20)-(30+40) 이 값이 최소가 된다.
		
		System.out.println(solution(str)); // -125
	}
}

백준 Greedy 1541번 잃어버린 괄호

'Java > 백준' 카테고리의 다른 글

[Java] 백준 [11048] 이동하기  (0) 2022.12.26
[Java] 백준 [2178] 미로 탐색  (0) 2022.12.24
[Java] 백준 [7570] 줄 세우기  (0) 2022.12.17
[Java] 백준 [2631] 줄 세우기  (0) 2022.12.17
[Java] 백준 [9095] 1, 2, 3 더하기  (0) 2022.12.16
import java.util.Arrays;

public class Solution {
	
	// 줄 세우기 - DP 7570번
	// 제일 앞 또는 제일 뒤로만 이동 가능
	// 연속된 가장 긴 증가하는 부분 수열 이용
	
	static int n = 7;
	static int[] arr = {3, 7, 5, 2, 6, 1, 4};
	static int[] dp = {1, 1, 1, 1, 1, 1, 1};
	
	public static void setLine() {
		
		int clisCnt = 0;
		
		for (int i = 0; i < n; i++) {
			
			for (int j = 0; j < i; j++) {
				
				if (arr[i] == arr[j] + 1) {
					dp[i] = Math.max(dp[i], dp[j] + 1);
				}
			}
		}
		
		// arr = {3, 7, 5, 2, 6, 1, 4}
		// dp = {1, 1, 1, 1, 2, 1, 2}
		
		Arrays.sort(dp);
		
		clisCnt = dp[n - 1]; // 2
		
		// 3, 4 또는 5, 6이 연속된 가장 긴 증가하는 부분 수열이므로 나머지 5개의 숫자를 이동해 1, 2, 3, 4, 5, 6, 7로 줄 세우기 가능
		System.out.println(n - clisCnt + "번의 이동만으로 줄 세우기 가능");
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		setLine();
	}
}

백준 DP 7570번 줄 세우기

'Java > 백준' 카테고리의 다른 글

[Java] 백준 [2178] 미로 탐색  (0) 2022.12.24
[Java] 백준 [1541] 잃어버린 괄호  (0) 2022.12.18
[Java] 백준 [2631] 줄 세우기  (0) 2022.12.17
[Java] 백준 [9095] 1, 2, 3 더하기  (0) 2022.12.16
[Java] 백준 [1697] 숨바꼭질  (0) 2022.12.12
import java.util.Arrays;

public class Solution {
	
	// 줄 세우기 - DP 2631번
	// 이동 위치 제한 없음
	// 가장 긴 증가하는 부분 수열(LIS) 이용
	
	static int n = 7;
	static int[] arr = {3, 7, 5, 2, 6, 1, 4};
	static int[] dp = {1, 1, 1, 1, 1, 1, 1};
	
	public static void setLine() {
		
		int lisCnt = 0;
		
		for (int i = 0; i < n; i++) {
			
			for (int j = 0; j < i; j++) {
				
				if (arr[i] > arr[j] && dp[i] <= dp[j]) {
					dp[i] = dp[j] + 1;
				}
			}
		}
		
		// arr = {3, 7, 5, 2, 6, 1, 4}
		// dp = {1, 2, 2, 1, 3, 1, 2}
		
		Arrays.sort(dp);
		
		lisCnt = dp[n - 1]; // 3
		
		// 3, 5, 6이 가장 긴 증가하는 부분 수열이므로 나머지 4개의 숫자를 이동해 1, 2, 3, 4, 5, 6, 7로 줄 세우기 가능
		System.out.println(n - lisCnt + "번의 이동만으로 줄 세우기 가능");
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		setLine();
	}
}

백준 DP 2631번 줄 세우기

'Java > 백준' 카테고리의 다른 글

[Java] 백준 [1541] 잃어버린 괄호  (0) 2022.12.18
[Java] 백준 [7570] 줄 세우기  (0) 2022.12.17
[Java] 백준 [9095] 1, 2, 3 더하기  (0) 2022.12.16
[Java] 백준 [1697] 숨바꼭질  (0) 2022.12.12
[Java] 백준 [1303] 전쟁 - 전투  (0) 2022.12.10
public class Solution {

	// 1, 2, 3 더하기 - DP 9095번
	// n을 1, 2, 3의 합으로 나타내는 방법의 수
	
	static int n = 4;
	static int[] dp = new int[101];
	
	// 1+1+1+1
	// 1+1+2
	// 1+2+1
	// 2+1+1
	// 2+2
	// 1+3
	// 3+1
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// n은 1일 때 1
		// 2일 때 1+1, 2
		// 3일 때 1+1+1, 1+2, 2+1, 3
		
		// 4는 1+3/2+2/3+1로 나타낼 수 있음
		// 1+(1+1+1)/2+(1+1)/3+(1)
		// 1+(1+2)/2+(2)
		// 1+(2+1)
		// 1+(3)
		// 따라서 f(3)+f(2)+f(1)로 나타낼 수 있는 것이다.
		
		dp[1] = 1;
		dp[2] = 2;
		dp[3] = 4;
		
		for (int i = 4; i <= 100; i++) {
			dp[i] = dp[i-1] + dp[i-2] + dp[i-3];
		}
		
		System.out.println(dp[n]);
	}
}

백준 DP 9095번 1, 2, 3 더하기

'Java > 백준' 카테고리의 다른 글

[Java] 백준 [7570] 줄 세우기  (0) 2022.12.17
[Java] 백준 [2631] 줄 세우기  (0) 2022.12.17
[Java] 백준 [1697] 숨바꼭질  (0) 2022.12.12
[Java] 백준 [1303] 전쟁 - 전투  (0) 2022.12.10
[Java] 백준 [11048] 이동하기  (0) 2022.12.10

안드로이드 기기

1. 설정 > 휴대전화 정보 > 소프트웨어 정보 > 빌드번호 여러 번 터치

 

2. 설정 > 개발자 옵션

 

3. USB 디버깅 ON

 

안드로이드 기기 USB 연결

4. 확인 창 나타나면 허용

 

안드로이드 스튜디오

5. 기기 연결 확인

 

6. 실행 버튼 클릭 후 안드로이드 기기 확인

+ Recent posts