Namad TS - 5.Typescript Blockchain
#5 Typescript Blockchain
5.0 Introduction
5.1 Targets
mkdir typechain
code typechain (vscode에서 폴더 열기 - 따로 설정해놔야 터미널에서 명령어 사용 가능)
npm init -y
npm install -D typescript
src폴더 생성, 그 아래 index.ts 파일 생성
tsconfig.json 파일 생성
touch tsconfig.json (명령어 아니어도, 파일 이름 동일하게 만들어도 됨)
include : 자바스크립트로 컴파일하고 싶은 모든 디렉터리 넣기.
: 타입스크립트가 src의 모든 파일을 확인한다는 의미
//tsconfig.json
{
"include": [
"src"
]
}
// tsconfig.json
"compilerOptions": {
"outDir": “build”
}
: outDir는 자바스크립트 파일이 생성될 디렉터리를 지정.
=> build 폴더에 js 파일 생성됨
package.json에서
"scripts": {
"build": "tsc"
},
설정 후, 터미널에서
npm run build
index.ts
const hello = () => "hi";
index.js 컴파일 결과
var hello = function () { return "hi"; };
낮은 버전의 자바스크립트 코드로 바꿔줌.
=>tsconfig.json “compilerOptions”에서 target 지정하면 원하는 버전의 자바스크립트로 컴파일 할 수 있다.
//tsconfig.json
"compilerOptions": {
"outDir": "build",
"target": "ES6"
}
다시 컴파일 하면,
index.js 결과
const hello = () => "hi";
5.2 Lib Configuration
타입스크립트에게 코드가 어디서 동작할 것인지를 알려줌.
만약 코드가 브라우저 위에서 동작한다면, 타입스크립트에게 "dom"이라고 설정해주면 window, document, localStorage 등을 사용할 수 있음.
//tsconfig.json
{
"compilerOptions": {
(...)
"lib": ["es6", "DOM"]
}
}
5.3 DeclarationFiles
5.4 JSDoc
"allowJs": true
=> 타입스크립트가 js파일 안에 들어와서 함수를 다 불러올 수 있게 할 수 있음
자바스크립트에 보호 장치를 더하는 방법
// @ts-check
타입스크립트 파일한테 자바스크립트 파일을 확인하라고 알리는 것.
/ 자바스크립트지만, 타입스크립트가 제공하는 보호 장치를 사용하고 싶을 때. => JSDoc 사용 (코멘트로 이루어진 문법)
5.5 Blocks
npm i -D ts-node
=> 빌드없이 타입스크립트 실행 가능(개발 환경에서만 사용)
npm i nodemon
=> 자동으로 커맨드 재실행, 일일이 커맨드 다시 실행할 필요 없어짐. 서버 재시작 필요 없어
package.json scripts에 추가
"scripts": {
"build": "tsc",
"dev": "nodemon --exec ts-node src/index.ts",
"start": "node build/index.js"
},
실행
npm run dev
5.6 Definitely Typed
https://github.com/DefinitelyTyped/DefinitelyTyped
GitHub - DefinitelyTyped/DefinitelyTyped: The repository for high quality TypeScript type definitions.
The repository for high quality TypeScript type definitions. - GitHub - DefinitelyTyped/DefinitelyTyped: The repository for high quality TypeScript type definitions.
github.com
5.7 Chain
import crypto from "crypto";
interface BlockShape{
hash: string;
prevHash: string;
height: number;
data: string;
}
class Block implements BlockShape {
public hash: string
constructor(
public prevHash: string,
public height: number,
public data: string
) {
this.hash = Block.calculateHash(prevHash, height, data);
}
static calculateHash(prevHash: string, height: number, data: string){
const toHash = `${prevHash}${height}${data}`
return crypto.createHash("sha256").update(toHash).digest("hex")
}
}
class Blockchain {
private blocks: Block[];
constructor() {
this.blocks = [];
}
private getPrevHash(){
if(this.blocks.length === 0) return "";
return this.blocks[this.blocks.length -1].hash;
}
public addBlock(data: string){
const newBlock = new Block(this.getPrevHash(), this.blocks.length + 1, data);
this.blocks.push(newBlock)
}
public getBlocks(){
return this.blocks;
}
}
const blockchain = new Blockchain();
blockchain.addBlock("First one");
blockchain.addBlock("Second one");
blockchain.addBlock("Third one");
console.log(blockchain.getBlocks())
[LOG]
[
Block {
prevHash: '',
height: 1,
data: 'First one',
hash: 'd90f2cc6ecdb63760af30f041a06e85e9a4d3376cccc09ff807e08c749e81ca9'
},
Block {
prevHash: 'd90f2cc6ecdb63760af30f041a06e85e9a4d3376cccc09ff807e08c749e81ca9',
height: 2,
data: 'Second one',
hash: '21625d153b9a2ba0996ac8a8ce85b78d5512a4c0bbf647548b0befab3e9b3cfe'
},
Block {
prevHash: '21625d153b9a2ba0996ac8a8ce85b78d5512a4c0bbf647548b0befab3e9b3cfe',
height: 3,
data: 'Third one',
hash: '33090390c5b209e1796881ef8aa55128e9beab0941cbc6f4989260d6f5bd961b'
}
]
이 상태로는 보안상 문제가 있다!!!
새 배열로 리턴해주면 해결~
public getBlocks(){
return [...this.blocks];
}
5.8 Conclusions