June 10, 2020

What is REST(Representational State Transfer)


❑ REST(Representational State Transfer)
❍ Communication way of client↔server.
클라이언트↔서버의 통신 방식.
❍ An architecture style (type) for the purpose of communication using URI and HTTP.
URI와 HTTP를 이용한 통신 목적의 아키텍처 스타일(유형).
* URI(Uniform Resource Identifier): Name for identifying resources such as pictures, documents and videos.
그림, 영상 등의 자원 식별용 이름.
* Architecture style(아키텍처 스타일): Type of architecture(structure). 아키텍처(구조)의 종류(유형, 스타일, 타입).
e.g.
Client-Server(클라이언트/서버)
Repository(저장소)
Pipe/Filter(파이프/필터)
REST.

❑ RESTful: REST applied system.
REST가 적용된 시스템.

❑ REST API: REST applied API.
REST가 적용된 API.

❑ The system that provides REST API is RESTful.
REST API를 제공하는 시스템은 RESTful이다.




To be precise, REST should satisfy the following conditions.
정확하게는, REST는 아래 조건을 만족해야 한다.

1. Uniform interface: It conforms to the interface specified by URI use, HTTP method use, RPC not called, etc.

1. 일관된 인터페이스(Uniform interface): URI 사용, HTTP 메소드 사용, RPC 미호출 등으로 지정된 인터페이스를 준수한다.



2. Client-Server: The client sends a request message to the server, and the server sends a response message about the request.

2. 클라이언트/서버(Client-Server): 클라이언트는 서버에 요청(request) 메시지를 전송하고 서버는 요청에 대한 응답(response) 메시지를 전송한다.



3. Statelessness: Communication is possible without a previous situation(context) such as a session.

3. 비연결성(Statelessness): 세션 등 이전 상황(문맥) 없이도 통신할 수 있다.



4. Cacheable: The server's response message can be cached (stored and reused).

4. 캐시 가능(Cacheable): 서버의 응답 메시지는 캐싱(저장 후 재사용)될 수 있다.



5. Layered system: Roles are separated by hierarchy. Therefore, even if roles (load balancing, authentication, etc.) are added/removed in the middle, communication is not affected.

5. 계층화된 시스템(Layered system): 계층별로 기능이 분리된다. 그러므로 중간에 기능(로드 밸런싱, 인증 등)이 추가/제거되어도 통신에 영향을 주지 않는다.



6. Code on demand(option): For easy data processing, the server can send a script to be executed on the client.

6. 주문형 코드(Code on demand)(선택): 손쉬운 데이터 처리를 위해 서버는 클라이언트에서 실행될 스크립트를 전송할 수 있다.

May 02, 2020

CORS and JavaScript.

This summary is not available. Please click here to view the post.

September 02, 2019

How to check each memory address

Let's check the address of the text, data, BSS, heap, libc, and stack memory addresses with C code.

C 코드를 통해 Text, data, BSS, heap, libc, stack 메모리 영역의 주소를 확인한다.

// < check.c >

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h>

void aFunc() {
    printf("Function called");
}

char *global1 = "glob1";
char global2;

int main(){
    char *heap = malloc(128);
    void *tmp;
    long libcAddr;
    tmp = dlopen("/lib/libc.so.6", RTLD_LAZY);
    libcAddr = (long)dlsym(tmp, "scanf");

    printf("[Text]  %p\n", aFunc);
    printf("[Data]  %p\n",global1);
    printf("[BSS]   %p\n",&global2);
    printf("[Heap]  %p\n", heap);
    printf("[Libc]  %p\n", libcAddr);
    printf("[Stack] %p\n", &libcAddr);

    return 0;
}

How to compile.
컴파일 방법.

gcc -o check check.c -lc -ldl

- lc: Load the library "libc.so" before loading "libdl.so".
"libdl.so"를 로드하기 전 "libc.so"를 로드.

- ldl: Load the library "libdl.so".
"libdl.so" 라이브러리 로드.

root@ubuntu:~# ./check
[Text]  0x400736
[Data]  0x4008d4
[BSS]   0x601061
[Heap]  0x602010
[Libc]  0x7ffff7a777e0
[Stack] 0x7fffffffe580

July 01, 2019

How to create HTTP request message(crawling) using Python



#-*- coding: utf-8 -*-

import sys
import os
import ssl
from socket import *

def main(argv):

    rstCrawl = crawl("news.naver.com", 443, "/main/main.nhn", "?mode=LSD&mid=shm&sid1=102") 
    # os.system("Pause") 
 
 
def crawl(dHost, target_port="80", path="/", paramGET=""):
     
    # 소켓 준비.
    print("  (Notice) Prepare the socket.")
    client = socket(AF_INET, SOCK_STREAM)
    if (target_port == 80):
        s_sock = client
    elif (target_port == 443):
        context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
        s_sock = context.wrap_socket(client, server_hostname=dHost)
    s_sock.connect((dHost, target_port))
   
    # 송신용 요청 메시지 준비.
    print("  (Notice) Prepare the request message.")
    request = "GET "+ path + paramGET +" HTTP/1.1\r\n"
    request += "Host:" + dHost + "\r\n"
    request += "\r\n"
 
    # 반복: 디코딩 성공 시 탈출.
    flagBreakDecode = False
    while(flagBreakDecode == False):
 
        s_sock.send(request.encode())
     
        # 반복: 데이터 수신 완료 시 탈출.
        httpResponse = b""
        flagBreakRecv = False
        while(flagBreakRecv == False):
            tmpHttpResponse = s_sock.recv(4096)
            if ("0\\r\\n\\r\\n" in str(tmpHttpResponse)) == True:
                flagBreakRecv = True
            httpResponse += tmpHttpResponse
     
        httpResponseLen = len(httpResponse)
        print("  (Notice) Recieved data(Byte):", httpResponseLen)
 
        try:
            dHttpResponse = httpResponse.decode("euc-kr")
            # dHttpResponse = httpResponse.decode()
            flagBreakDecode = True
            print("  (Notice) Complete decoding.")
        except UnicodeDecodeError:
            print("  (Error) UnicodeDecodeError. → Modify the way of decoding.")
            continue
         
    # charset 제거: 한글 식별 목적. 
    dHttpResponse = dHttpResponse.replace("<meta charset=\"utf-8\">", "")
    dHttpResponse = dHttpResponse.replace("<meta charset=\"euc-kr\">", "")

    # 결과 출력
    with open("./" + dHost + "_crawl.html", "w", encoding="utf-8") as f:
        f.write(dHttpResponse)

    print("  (Notice) Complete crawl.")
    return dHttpResponse
 
 
if __name__ == '__main__':
    main(sys.argv)

When the above Python program is executed, the file "xxx_crawl.html" is created in the same location.

위 파이썬 프로그램을 실행하면, 동일 위치에 "xxx_crawl.html" 파일이 생성된다.

June 21, 2019

How to use python pdb



❑ pdb: The Python debugger. 파이썬 디버거.

❑ How to debug.
01. Command line style.    커맨드 라인 방식.
python -m pdb [program.py]

02. Python code style.    파이썬 코드 방식.
import pdb

pdb.set_trace()  
# Place this code in the position you want to stop. But it is not recognized as a breakpoint.
# 중단하고 싶은 위치에 이코드를 넣는다. 하지만 브레이크포인트로 인정되지는 않는다.

❑ Usage.    사용법.
CommandDescription
?
h(help)
Print help.
도움말 출력.
n(next)Step over.
스탭 오버.
s(step)Step into.
스탭 인투.
c(continue)Execute continuously until a breakpoint is encountered.
다음 중단점까지 실행.
r(return)Execute continuously until the current function returns.
현재 함수가 값을 반환할 때까지 실행.
l(list) [line], [line]Print the 11 lines around the current line, If no line is specified.
라인을 지정하지 않으면 현재 위치 주위의 11개 라인 출력.

* list 15, 19
Print 15~19 lines.
15~19라인 출력.
b(break) [line | function], [condition]Set a breakpoint.
브레이크포인트 설정.

* b
Print all breakpoints set up to now.
현재까지 설정된 브레이크포인트 출력.

* b 9
Set a breakpoint at the line 9.
9라인에 breakpoint 설정.

* b main
Set a breakpoint at the main() function.
main() 함수에 브레이크포인트 설정.

* b 9, var1>0
Set a breakpoint that stops if the value of var1 is greater than zero.
var1의 값이 0보다 크면 정지하는 브레이크포인트 설정.
enable [number]Enable a breakpoint.
브레이크포인트를 활성화.

* enable 1
Enable the breakpoint #1.
1번 브레이크포인트를 활성화.
disable [number]Disable a breakpoint.
브레이크포인트를 비활성화.

* disable 1
Disable the breakpoint #1.
1번 브레이크포인트를 비활성화.
cl(clear) [number]Delete a breakpoint.
브레이크포인트 제거

* cl 1
Delete the breakpoint #1.
1번 브레이크포인트 제거.
bt
w(where)
Print a stack trace(function call).
스택 추적 결과 출력(함수 호출).
u(up)Based on stack trace results, move to the higher(older) stack frame.
스택 추적 결과를 기준으로, 상위(오래된) 스택 프레임으로 이동.
d(down)Based on stack trace results, move to lower(newer) stack frame.
스택 추적 결과를 기준으로, 하위(최신의) 스택 프레임으로 이동.
a(args)Print the arguments of the current function.
현재 위치의 함수에 입력된 아규먼트 값들을 출력.
[Python code]Execute Python code.
파이썬 코드 실행.


January 12, 2019

Dark web, deep web, surface web

❑ Dark web: The cyberspace accessible only through specific software or authentication.
다크 웹: 특정 소프트웨어나 인증을 통해서만 접근할 수 있는 사이버 공간.

❑ Deep web: The cyberspace that search engines such as Google can not access. It is a superordinate concept including Dart web.
딥 웹: 구글 등 검색 엔진이 접근할 수 없는 사이버 공간. 다크 웹을 포함하는 상위개념.

❑ Surface web: The cyberspace that search engines such as Google can access.
서피스 웹: 구글 등 검색 엔진이 접근할 수 있는 사이버 공간.

December 30, 2018

RDBMS meta-data

❑ Meta-data: The data to describe the data in the DB.
메타데이터: DB의 데이터를 설명하기 위한 데이터.


❑ MySQL, PostgreSQL: INFORMATION_SCHEMA(DB format. DB 형태.)
INFORMATION_SCHEMA.COLUMNS
PropertyData typeDescription
COLUMN_NAMEvarchar(64)The column's name.
칼럼의 이름.
TABLE_NAMEvarchar(64)The table's name to which the column belongs.
칼럼이 속해있는 테이블의 이름.
TABLE_SCHEMAvarchar(64)The database's name that contains the table to which the column belongs.
칼럼이 속해있는 테이블이 저장된 데이터베이스의 이름.




❑ SQLite: SQLITE_MASTER(table format. 테이블 형태.)
SQLITE_MASTER
PropertyData typeDescription
TYPEtextThe object type. 객체의 종류(table, view, trigger, index).
NAMEtextThe object's name
오브젝트의 이름.
TBL_NAMEtextThe name of a view or a table.
뷰 혹은 테이블의 이름.
SQLtextThe definition of the table. The SQL commands used when creating the table.
테이블의 정의문. 테이블 생성 시 사용된 SQL 명령어들.

October 24, 2018

Solidity grammar

❑ The deployed Ethereum smart contract(DApp) is immutable.
❑ Solidity file extension.: *.sol
❑ Version pragma: It is the starting source code of a DApp, and tells you the version of Solidity.

pragma solidity ^0.4.24;


❑ Contract: The basic components of the Ethereum DApp. All variables and functions are in the Contract.

Contract HelloWorld {
}


❑ State variables are permanently stored in Contract storage.
❑ exponential operator(x^2) : x ** 2
❑ Data type : int, uint(Unsigned integer) == uint256, uint8, uint16, uint32, struct, string, array, mapping, address.
❍ uint
- Generally, uint8 uses the same storage space as uint256.
- But, uint8 in a struct uses less space than uint256.

❍ Struct struct Person { uint age; string name; }
// The continuous uint32 is packed when it stored. : struct abc2 { uint32 a; uint32 b; }
// The spaced uint32 is packed when it stored : struct abc2 { uint32 a; uint c; uint32 b; }

❍ Array uint[2] arr1; // A fixed array of uints.
string[5] arr2; // A fixed array of strings. 
Person[] people // A dynamic array of Person structs. 
uint[] arr3; // A dynamic array of uints. 
uint[] memory values = new uint[](3); // Allocate memory. 
values.push(1); // The push function returns the current length of the array. 
values.push(2); 
values.length // Length of the array.

❍ mapping : The data type of the "key => value" format.
// account => data.
mapping (address => uint) public favoriteNumber;

// The update of a mapping value.
favoriteNumber[msg.sender] = _Anumber;

// The call of a mapping value.
favoriteNumber[msg.sender]


❍ address: The datatype that stores the Ethernet address (0x~~~~~~~~~).
* The address refers to a specific user(Wallet) or smart contract.

❑ Function modifier: It is the syntax to control the function of a function.
* Generally, It is used to verify that the requirements are fulfilled before the function is executed.
* There are "Visibility modifier", "State modifier", "Custom modifier" etc.
* Several modifiers can be used together.
❑ Visibility modifier: It is the syntax that specifies where variables/functions can be called.
❍ Private [Variable | Function] : It is the Variables/functions that only functions in the Contract can call.
❍ Public [Variable | Function] : It is the Variables/functions that other Contract can call.
* If you do not specify a "visibility modifier", the Solidity function is declared public.
* When a public variable is declared, a public "getter()" function with the same name is created internally.
❍ Internal [Variable | Function] : It is "private modifier" but, It is also accessible from contracts that inherit the defined Contract.
❍ External [Variable | Function] : It is "public modifier" but, It is only accessible from outside the Contract.

// The dynamic array of Zombie structs. Other Contracts can use this array.
Zombie[] public zombies;


// The method of making a private function.
// The underbar character is used to mean a local variable/function. "_name" and "_dna" are local variables. "_createZombie" is a private function.
function _createZombie(string _name, uint _dna) private {}


❑ State modifier: It is the syntax that specifies how the Solidity source code interacts with the blockchain.
* "external [View | Pure]" function does not consume gas because it does not access the block.
❍ View: The read-only function. It just read stored data.
* Query occurred. No transaction occurred.
❍ Pure: The function that calculates and returns a value using a parameter. The side-effect(Changing variable's value)does not occur.

// This function returns a uint value.
// This function is a view function.
function _generateRandomDna(string _str) private view returns (uint) {}


❑ Custom modifier: It is the user-defined syntax.

// When the "setLevelUpFee()" function is called, the "onlyOwner()" modifier is executed first.
// The "onlyOwner()" modifier allows only the contract owner for use the function.
modifier onlyOwner() {
    require(msg.sender == owner);
    _; // Return to the function that called modifier.
}
function setLevelUpFee(uint _fee) external onlyOwner {
    levelUpFee = _fee;
}

// Modifier can use parameters.
modifier aboveLevel(uint _level, uint _zombieId) {
    require(zombies[_zombieId].level >= _level);
    _;
}

function changeName(uint _zombieId, string _newName) external aboveLevel(2, _zombieId) {
}


❑ Payable modifier: It is the syntax that is used in ETH coin transfer.
* The ETH that is transferred to a Contract is kept in the Contract.

[Contract]
contract OnlineStore {
    function buySomething() external payable {
        // Checking that 0.001 ETH is transmitted from the client when executing the function.
        // The data type of 0.001 ether is uint.
        require(msg.value == 0.001 ether);
    }

    // The source code for ETH withdrawals stored in the contract.
    function withdraw() external onlyOwner {
         // this.balance : The total ETH balance stored in the contract.
        owner.transfer(this.balance);
    }
}

[Client]
// The client source code written in web3.js.
// You can only send "value" to the function for which the payable modifier is set.
OnlineStore.buySomething({from: web3.eth.defaultAccount, value: web3.utils.toWei(0.001)});


❑ keccak256(): It is the SHA3-based hash function that returns a hexadecimal value of 256 bits.

// Generating a SHA-3 value.
// 6e91ec6b618bb462a4a6ee5aa2cb0e9cf30f7a052bb467b0ba58b8748c00d2e5
keccak256("aaaab");
// b1f078126895a1424524de5321b339ab00408010b7cf0e6ed451514981e58aa9
keccak256("aaaac");

// How to generate random numbers using hash values(0 to 99).
// Timestamp of current time(now), a msg.sender and the temporary value(nonce) are needed.
// Because a malicious node may try to write to a block only when the desired value comes out, this code is vulnerable.
uint randNonce = 0;
uint random = uint(keccak256(now, msg.sender, randNonce)) % 100;
randNonce++;
uint random2 = uint(keccak256(now, msg.sender, randNonce)) % 100;


❑ Typecasting

uint8 a1 = 5;
uint a2 = 6;

// uint256 → uint8
uint8 a3 = uint8(a2);


❑ Fallback function : No-name function. It is the function that is called when calling a function that does not exist in the contract. The fallback function prevents the error caused by not executing.

function () {
}


❑ event: It is the syntax that occurs logs.

// The declaring the log to be generated.
event NewZombie(uint zombieId, string name, uint dna);

// Each time the "_createZombie()" function is called, logs of "id", "_name", "_dna" values are generated.
function _createZombie(string _name, uint _dna) private {
    NewZombie(id, _name, _dna);
}


❑ msg.value: The amount of ETH sent.
❑ msg.sender: The person or the smart contract that called the current function.
❑ require: It is the syntax to raise an error message and stop execution when the condition is not true.

// Checking that "_name"'s value is the same as "abc".
// Solidity has no default string comparing function.
require(keccak256(_name) == keccak256("abc"));

// If the above condition is true, the following source code will be executed:
return "Hi!";


❑ Inheritance

contract Doge {
    function catchphrase() public returns (string) {
        return "So Wow CryptoDoge";
    }
}

// "BabyDoge" contract inherits "Doge" and "ERC721" contract.
contract BabyDoge is Doge, ERC721 {
    function anotherCatchphrase() public returns (string) {
        return "Such Moon BabyDoge";
    }
}


❑ import : The syntax to load solidity files(*.sol).

import "./someothercontract.sol";


❑ Storage: The variable that is used to store a value permanently in the blockchain.
* High cost syntax.
* [Array].push() changes the size of the array.
❑ Memory: The variable that is used to store a value temporarily.
* Low cost syntax compared to storage.
* [Array].push() doesn't change the size of the array.
❑ Without storage/memory syntax, If the storage/memory syntax doesn't exist, state variables(the Variables declared outside functions) are stored in storage, and variables in functions are stored in memory.

contract SandwichFactory {
    struct Sandwich {
        string name;
        string status;
    }

    Sandwich[] sandwiches;

    function eatSandwich(uint _index) public {

        // "mySandwich" is a pointer pointing "sandwiches [_index]".
        Sandwich storage mySandwich = sandwiches[_index];

        // This changes the storage's "status" value permanently.
        mySandwich.status = "Eaten!";

        // "anotherSandwich" copies the value of "sandwiches [_index]".
        Sandwich memory anotherSandwich = sandwiches[_index + 1];

        // This changes the "status" value of memory.
        anotherSandwich.status = "Eaten!";
    }
}


❑ Interface: The syntax to use a contract that you do not own.

// The interface declaration has the same format as a contract.
contract KittyInterface {

    // Copy the function from the name until the returns syntax and put a semicolon at the end.
    function getKitty(uint256 _id) external view returns (
        bool isGestating,
        bool isReady,
        uint256 cooldownIndex,
        uint256 nextActionAt,
        uint256 siringWithId,
        uint256 birthTime,
        uint256 matronId,
        uint256 sireId,
        uint256 generation,
        uint256 genes
    );
}


contract test {
    // The address of the smart contract to use.
    address ckAddress = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d;

    // This initializes the interface.
    KittyInterface kittyContract = KittyInterface(ckAddress);

    // Now you can use the smart contract.
    // This stores the last of the 10 returned values in "kittyDna".
    uint kittyDna;
    (,,,,,,,,,kittyDna) = kittyContract.getKitty(_kittyId);
}


❑ Constructor: The function with the same name as the contract. It is executed once when the contract is created.

contract Ownable {
    function Ownable() public {
        owner = msg.sender;
    }
}


❑ Time(The value related in the time.)

/*
now // Returns UNIX timestamp(32 Bits uint).
seconds
minutes // Minute of the current time converted in seconds.
5 minutes // 300(60*5)
hours
1 hours // 3600(60*60)
days
weaks
years
*/

uint lastUpdated;
function updateTimestamp() public {
    lastUpdated = now;
}

// It returns "true" if it has been 5 minutes since the "updateTimestamp" function was called.
function fiveMinutesHavePassed() public view returns (bool) {
    return (now >= (lastUpdated + 5 minutes));
}


❑ For

for(uint i=0; i<10; i++) {
}


❑ If

if (var1 == var2) {
} else {
}


❑ ERC721 token
❍ function balanceOf(): It returns the number of tokens held by "_owner".

function balanceOf(address _owner) public view returns (uint256 _balance) {
    return ownerZombieCount[_owner];
}


❍ function ownerOf(): It returns the address that owns "_tokenId".

function ownerOf(uint256 _tokenId) public view returns (address _owner) {
    return zombieToOwner[_tokenId];
}


❍ function transfer(): It transfers the token from "_from" address to "_to" address.

function _transfer(address _from, address _to, uint256 _tokenId) private {
    ownerZombieCount[_to]++;
    ownerZombieCount[_from]--;
    zombieToOwner[_tokenId] = _to;

    Transfer(_from, _to, _tokenId); // The event defined by ERC721.
}

// The modifier that checks access permission to a token.
modifier onlyOwnerOf(uint _zombieId) {
    require(msg.sender == zombieToOwner[_zombieId]);
_;
}

function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
    _transfer(msg.sender, _to, _tokenId);
}


❍ function approve(): It approves tokens that is transferred.

function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
    zombieApprovals[_tokenId] = _to;
    Approval(msg.sender, _to, _tokenId); // The event defined by ERC721.
}


❍ function takeOwnership(): It calls "_transfer()" after ensuring that the "msg.sender" is approved to have a token.

function takeOwnership(uint256 _tokenId) public {
    require(zombieApprovals[_tokenId] == msg.sender);
    address owner = ownerOf(_tokenId);

    // Since msg.sender calls this function, it becomes a recipient.
    _transfer(owner, msg.sender, _tokenId);
}


❑ The Library is a special kind of contract In Solidity.
❑ Library SafeMath

library SafeMath {

    // Be careful not to input any values other than uint256(e.g. uint16, uint32 etc.).
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;

        // Check overflow..
        // "require()" and "assert()" are equivalent in that they return an error when the condition is not satisfied.
        // "require()" returns the remaining gas when the condition is not satisfied, but "assert()" doesn't return the remaining gas.
        assert(c >= a);
        return c;
    }
}

contract abc {
    // This applies the SafeMath library to the data type.
    using SafeMath for uint;

    uint a = 5;
    // The variable "a" is entered as the first argument of "add()".
    uint b = a.add(3); // 5 + 3 = 8
    uint c = a.mul(2); // 5 * 2 = 10
}


❑ Comment: Natspec comment is the standard comment format in Solidity.
❍ // @title: The title of a comment.
❍ // @autor: The author of a comment.
❍ // @notice: The description of a source code.
❍ // @dev: The description for developers.
❍ // @param: The parameter used by the function..
❍ // @return: The value returned by the function.

August 15, 2018

What is Block chain

[Block chain]

❑ Blockchain : The computer using P2P based distributed DB. Or the technology to make up this computer.
* P2P based distributed data storage creates data(blocks) and interconnects them using a consensus algorithm.
* Four major functions : Cryptocurrency, Smart Contract, Smart Asset, DAO.
❑ Side chain : A technology that allows trading of assets that exist in different block chains.
❑ On chain : Using Blockchain.
❑ Off chain : Not using Blockchain.
❑ Lightning Network(LN) : The technology allows sending and receiving cryptocurrencies immediately without mining.
* If a payment channel is written to a block, a transaction is not required to be written to the block because the off-chain verification method is used.
❑ Raiden network : It means Etherium's lightning network.
❑ A block is a storage. The gathered blocks are called distributed DB..
❑ The cryptocurrency issuance is made by recording in a block according to a specific format created by a dedicated program.
❑ Crypt wallet is a dedicated program.
❑ the data types of the bitcoin blockchain and the Ethereum blockchain are different. So each network's data is not compatible.
❑ The condition for data integrity in a blockchain.
❍ The format of the recorded data is correct.
❍ It is equal if comparing my data to data of other blocks.
❑ The member of the blockchain network.
❍ Node(miner) : A server in the blockchain network. Run DAPP. Create blocks(Transaction approval, distributed consensus, Storing transaction history.).
* Master node : The node that performs additional functions(anonymization, governance participation, etc.).
❍ Client(user) : Server users(Transaction creation, transaction history verification.).
❑ If a client creates a transaction, nodes share and execute the transaction through a distributed consensus.
❑ The blockchain node has two DBs.
❍ Transaction DB.
❍ Application(Smart contract) DB : It stores the latest state (variables) of the smart contract.
❑ Smart contract : Software. Application. DApp.
❑ The state of a smart contract : A variable used in a smart contract.
❑ Interface for using smart contracts.
❍ Transaction : Write, Modify. Delete. It is recorded in transaction DB. It changes the state of a smart contract.
❍ Query : Read.  It is not recorded in transaction DB. It reads the state of a smart contract.
At present, Transaction is slower than regular DB, but Query can be faster than regular DB.
❑ If the miner succeeds in mining, the miner receives transaction fee and compensation for the block issuance and.
❑ The miner creates a block first by processing a transaction that has a higher fee to increase mining compensation.
❑ A simple calculation has small fee, and a complex calculation has high fee.
❑ Transaction is a signed data package.
❑ Fork : Version update of a blockchain software.
* Miners update mining software and users update user software(wallet etc.).
❑ Hard fork : Creating a new main net.
❍ At a specific time, it copies blocks applied the old rule and connects the blocks to which the new rule is applied for constructing a new blockchain network.
❍ All miners/users should update their software.
❍ Service is not available during the update.
❑ Soft fork
❍ At a specific time, it connects the blocks applied the new rule to blocks which the old rule is applied.
❍ miners should update their software, but users don't need that.
❍ Service is available during the update.
❑ Test net : A blockchain network for testing before launching the main net..
❑ Main net : A block-chain network with an independent environment that is platform/transaction/wallet etc.
❑ Private blockchain : A closed blockchain network(Intranet).
❑ Public blockchain : A opened blockchain network(Internet).
❑ Token : A cryptocurrency application implemented in an existing main net.
* The tokens on Ethereum network are implemented in Solidity language.
❑ Coin : A cryptocurrency application implemented in its independent main net.
* Ethereum coin was implemented in languages other than Solidity(C++, GO).
❑ ICO(Initial Coin Offering) : Supporting the fund by appealing the blockchain technology. It is similar to IPO in that it distributes tokens to sponsors.
❑ ICO is usually implemented using Ethereum smart contract.
In "etherscan.io", you can find the corresponding ICO DApp by searching with the address.
* Investments and token distributions are made transparent and real time.
❑ Typical blockchain network building process.
1. Issue tokens in existing blockchain network.
* e.g. Issue ERC-20 tokens in Ethereum network.
2. Raise the fund through ICO and distributes tokens to participants.
3. Launch the test net for preparing the main net.
* In general, development status is disclosed to GitHub.
4. Launch the main net and issue coins.
5. Exchange the issued tokens and the coins.
❑ PoW(Proof Of Work) : Being the node by solving the hash problem.
❑ PoS(Proof Of Stake) : Being the node by having coins(stake).
❑ DPoS(Delegated Proof Of Stake) : It is the same as PoS but nodes are selected by electing.
The nodes of the DPoS are called delegated node or witness etc.




[Bitcoin]

❑ nBits : Filling the left side of the hash value with zeros. It affects mining difficulty because, If the miner's hash value is smaller than the hash value adjusted by nBits, mining will be achieved.
❑ Bitcoin script
❍ The first smart contract.
❍ Loop cannot be used(If a loop is allowed, the infinite loop occurs.).
❑ In the bitcoin network, the decentralized application called bitcoin is the main application.




[Ethereum]

❑ A block chain platform specialized in smart contract.
* Ethereum smart contract is written in Solidity language and becomes EVM Bytecode after being compiled.
❑ Solidity : The object-oriented programming language capable of developing Ethereum DAPP..
❑ Web3.js : The JavaScript library that interacts with an Ethereum smart contract.
❑ All cryptocurrency(token) issued on the Ethereum network are smart contracts.
* EOS token and crypto kitty are all just DApp.
❑ Ethereum combines transaction DB and smart contract DB for high compression ratio.
❑ Examples of Etherium's most famous smart contract is DAO(Decentralized Autonomous Organization)
* DAO tokens enable the company to make decisions.
* DAO smart contracts were attacked by hackers because of vulnerabilities.
❑ EVM(Ethereum Virtual Machine) : The node drives EVM and can run EVM Bytecode.
❑ GAS : The fee incurred when EVM Bytecode is executed.
* Unlike Ethereum coin, it maintains a constant price.
* Ethereum coin is used for GAS payments.
* The miner can determine the gas quantity to reject the transaction of the lower fee.
* Max fee : GAS limit * GAS price.
❍ GAS Limit : The max gas quantity that transaction generates.
* As a result of transactions, it is possible to use less gas than GAS Limit("GAS Used By Txn" displays this.).
❍ GAS Price(unit : wei).
* 1 Wei = 1/10^18 ETH
* 1 Kwei = 1/10^15 ETH
* 1 Mwei = 1/10^12 ETH
* 1 Gwei = 1/10^9 ETH
❑ Ethereum uses a node search protocol based on the Kadelima protocol.
❑ DApp distribution.
❍ TestRPC(Ganache) : Virtual environment. ETH can be issued without mining. The smart contract distributed can be deleted.
❍ TestNet : Ethereum network for testing. The difficulty of mining is low.
❍ MainNet : The actual Ethereum network that consumes gas when a transaction occurs.
❑ Ethereum's smart contract/wallet address length is 20 Bytes.
❑ ERC(Ethereum Request for Comment) : The standard recommended for cryptocurrency DApp of Etereum network.
❍ ERC-20(https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md)
❍ ERC-721(https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md)
- Each token cannot be split into decimal points.
- Each token has an ID.

July 02, 2018

Javascript grammar

[Example 1]
<div id="box" style="border: 1px solid #000;">
    <p>
        pageX : <span id="x"></span>
    </p>
    <p>
        pageY : <span id="y"></span>
    </p>
</div>

<script>
window.onload = function (){
    var box = document.getElementById("box");
    var pageX = document.getElementById("x");
    var pageY = document.getElementById("y");

    box.addEventListener("mousemove", function(){
        pageX.innerText = event.pageX;
        pageY.innerText = event.pageY;
    });
}
</script>



[Example 1 : Result]
pageX :
pageY :

window.onload = function() {} : The code for executing after all loading has finished. If it is used more than once, an error can occur without an error message.
❑ document.getElementById("[ID]") : Select an element using the [ID].
❑ [Element].addEventListener("mousemove", function() {}) : Register an [Element]'s event to event listener.
❑ event.pageX : The x-coordinate of the mouse.
event.pageY : The y-coordinate of the mouse.
[Element].innerText = [Plain text] : Insert a [Plain text] to the [Element].
[Element].innerHTML = [HTML text] : Insert a [HTML text] to the [Element].




[Example 2]
<p class="pClass">
    <b><span class="ft">Test1</span></b>
</p>
<p class="pClass">
    <b><span class="ft">Test2</span></b>
</p>

<input id="btn1" type="button" value="one"/>
<input id="btn2" type="button" value="two"/>
<input id="btn3" type="button" value="clear"/>

<br/><br/>
[Result]
<div id="rst"></div>


<script>
    document.querySelector("#btn1").addEventListener("click", function(){
        var spanFirst = document.querySelector("b span.ft");

        spanFirst.style.color="#FF0000";
        document.querySelector("#rst").innerHTML += spanFirst.style.color + "<br/>";
        spanFirst.setAttribute("onclick", "javascript:alert('One clicked!!')");
        var tmpStr = spanFirst.getAttribute("onclick");
        document.querySelector("#rst").innerHTML += tmpStr + "(Type : "+ typeof(tmpStr) + ")" + "<br/>";
    });

    document.querySelector("#btn2").addEventListener("click", function(){
        var pAll = document.querySelectorAll(".pClass");

        pAll[1].style.color="#00FF00";
        document.querySelector("#rst").innerHTML += pAll[1].style.color + "<br/>";
        pAll[1].setAttribute("onclick", "javascript:alert('Two clicked!!')");
        var tmpStr = pAll[1].getAttribute("onclick");
        document.querySelector("#rst").innerHTML += tmpStr + "(Type : "+ typeof(tmpStr) + ")" + "<br/>";
    });

    document.querySelector("#btn3").addEventListener("click", function(){
        var spanFirst = document.querySelector("b span.ft");
        spanFirst.style.color="";
        spanFirst.setAttribute("onclick", "");

        var pAll = document.querySelectorAll(".pClass");
        pAll[1].style.color="";
        pAll[1].setAttribute("onclick", "");
        document.querySelector("#rst").innerHTML = "";
    });
</script>


[Example 2 : Result]
Test1
Test2


[Result]

❑ document.querySelector("b span.ft") : Select one of the children of the "b" element that is a "span" element and has the attribute class "ft".
document.querySelector("#rst") : Select the element that has the attribute id is "rst".
❑ document.querySelectorAll(".pClass") : Select all elements that have the attribute class is "pClass"(Type : NodeList).
❑ [Element].style.color="#FF0000" : Set the [Element] to a red color style.
[Element].innerHTML += "[HTML code]"Append the [HTML code] to [Element].
❑ [Element].setAttribute("onclick", "javascript:alert('One clicked!!')") : Set the [Element]'s "onclick" attribute to the javascript code.
❑ [Element].getAttribute("onclick") : Return the value of the [Element]'s "onclick" attribute.
❑ typeof([Variable]) : Return [Variable]'s data format such as string, integer etc.
await [Promise] : Return the value of the disaggregated [Promise] object.




❑ setInterval(function() {}, 2000): Execute the anonymous function every 2 seconds.
window.setTimeout(function() {}, 2000) : Execute the anonymous function after 2 seconds.
Math.random() : Return the value of 0<=x<1.
Math.floor(Math.random()*3+1) : Return the value of 1<=x<=3.
❑ let css1 = document.createElement('link');
css1.href = "[URL]";
css1.rel = "stylesheet";
css1.onload = [Function name to execute after the load is completed];
document.querySelector('head').appendChild(css1);
: Import an external css file.

Example to use Inline-assembly in C language

The method using assembly code in C language is called Inline-assembly.


[Example 1]
#include<stdio.h>

int main() {

    int a = 0;
    int b = 0;
    int c = 0;

    printf("Hello world\n");

    __asm__ __volatile__(
        "mov $2, %%eax;"
        "mov %%eax, %0;"
        "mov $10, %%ebx;"
        "mov %%ebx, %1"
        : "=m" (a), "=m" (c)
    );


    __asm__ __volatile__(
        "mov $5, %%ebx;"
        "mov %%ebx, %0"
        : "=m" (b)
    );

    printf("Result(a) : %d\n", a);
    printf("Result(c) : %d\n", c);
    printf("Result(b) : %d\n", b);


    int src = 3;
    int dst = 5;
    __asm__ volatile (
        "mov %1, %%eax;"
        "add $1, %%eax;"
        "mov %%eax, %0;"
        : "=m" (dst)
        : "m" (src)
    );

    printf("Result(add) : %d\n", dst);

    system("pause");
    return 0;
}

[Example 1 : result]
Hello world
Result(a) : 2
Result(c) : 10
Result(b) : 5
Result(add) : 4

❑ : "=m" (dst) → The result is output to the dst using memory.
❑ : "=r" (dst) → The result is output to the dst using a register. 
❑ : "m" (src) → The src value is input using memory.
❑ : "=m" (dst) : "m" (src)  %0 points to the dst and %1 points to the src.
❑ __volatile__ → The assembly code is executed where it is located and doesn't move for reasons such as optimization.


June 19, 2018

Python class examples

<Code1.py>
class Car(object):
    __w = 4
    __d= 2

    def __init__(self, v1, v2):
        print "__init__() is called"
        self.v1 = v1
        self.v2 = v2

    def func1(self):
        print "w_ => {}".format(self.__w)
        print "d_ => {}".format(self.__d)
   
    def __del__(self):
        print "__del__() is called"


# Instance object
car_object = Car(2, 3)
car_object2 = Car(2, 3)

print "address(Car) => {0:#x}".format(id(Car))
print "address(Car_object) => {0:#x}".format(id(car_object))


print id(car_object.v1), id(car_object2.v1)


car_object.func1()


if (isinstance(car_object, Car) == True):
    print "yes"
else:
    print "no"

class_of_car_object = car_object.__class__
class_of_car_ojbect2 = car_object2.__class__

print class_of_car_object, class_of_car_ojbect2

print car_object2.__w


<Code1.py result>
__init__() is called
__init__() is called
address(Car) => 0x60014f4f0
address(Car_object) => 0x6ffffe60d90
25770367776 25770367776
w_ => 4
d_ => 2
yes
<class '__main__.Car'> <class '__main__.Car'>
Traceback (most recent call last):
  File "C:\Users\user\Desktop\tmp\test.py", line 43, in <module>
    print car_object2.__w
AttributeError: 'Car' object has no attribute '__w'
__del__() is called
__del__() is called

❑ [Object].__class__ : Returns the class to which the [Object] belongs.
❑ Error occurs because __w is a variable that is set to private by the underscore(__).
* [Information hiding]
__name == private
_name == protected
name == public
❑ The constructor and The Destructor are called automatically at the beginning and end.




<Code2.py>
class P:
  v=100

class C(P): #Inheritance
  pass

class Np:
vv=15
__w = "This is __w"
_wp = "This is _wp"

def __f(self):
print "This is private method"

def wFunc(self):
print self.__w


objectC = C()
print objectC.v

print issubclass(C, P)
print issubclass(C, C)
print issubclass(C, Np)
print issubclass(C, object) #True in Python 3.x

print C.__bases__
print P.__bases__
print Np.__bases__ # An Object is displayed in Python 3.x



class CC(P, Np): # Multiple inheritance
pass

objectCC = CC()

print objectCC.vv
# print CC.__w
# print CC.__f() # The private member variables/functions are not inherited.
print objectCC._wp
objectCC.wFunc()

<Code2.py result>
100
True
True
False
False
(<class __main__.P at 0x6ffffe56598>,)
()
()
15
This is _wp
This is __w

❑ A class's subclass includes itself.
❑ In Python 3.x, the object class is the parent class of all classes.
❑ [Class].__bases__ : Check the parent class of the [Class].
❑ Private member variables/functions are not inherited, but protected member variables/functions are inherited.
❑ The protected member variable/function can only be called in inheritance.




<Code3.py>
class Pp:
    v = 0x12
 
class C2(Pp):
    pass
 
objectC2= C2()
objectC2_2= C2()
objectC2.w = 10 
#The new member variable "w" is created in the objectC2.
print objectC2.w

print hex(id(objectC2.v))
print hex(id(objectC2_2.v))
print hex(id(C2.v))

objectC2.v = 55
print hex(id(objectC2.v))
print hex(id(objectC2_2.v))
print hex(id(C2.v))

C2.kVal = 150
print objectC2.kVal
print objectC2_2.kVal



class P10(object):
    def f(self):
        print "Parent f()"
     
class P11(P10):
    def f(self):    #Redefine
        print "Child f()"
    pass
 
objectP11 = P11()
objectP11.f()

<Code3.py result>
10
0x6000899a0
0x6000899a0
0x6000899a0
0x600089df0
0x6000899a0
0x6000899a0
150
150
Child f()

❑ If a member variable/function is redefined, the variable/function of the child object is used.

June 18, 2018

XML special characters

❑ &#nn : Decimal format.
❑ &#xhh : Hexadecimal format.


Character Numeric
character
Name

&#09;Horizontal tab

&#10;Line feed

&#13;Carriage Return

&#32;Space
!&#33;Exclamation mark
"&#34;Quotation mark
#&#35;Number sign
$&#36;Dollar sign
%&#37;Percent sign
&&#38;Ampersand
'&#39;Apostrophe
(&#40;Left parenthesis
)&#41;Right parenthesis
*&#42;Asterisk
+&#43;Plus sign
,&#44;Comma
-&#45;Hyphen
.&#46;Period
/&#47;Slash
:&#58;Colon
;&#59;Semi-colon
<&#60;Less than
=&#61;Equals sign
>&#62;Greater than
?&#63;Question mark
@&#64;At
[&#91;Left square bracket
\&#92;Bbackslash
]&#93;Right square bracket
^&#94;Caret
_&#95;Underscore
`&#96;Acute accent
{&#123;Left curly brace
|&#124;Vertical bar
}&#125;Right curly brace
~&#126;Tilde

June 12, 2018

Exit status

exit status test example

❑ Exit status : The returned value when a program exits. This can only be used if the program supports exit status.

❑ "$?" has the exit status.
* 0 : Successfully executed.
* 1~255(Non-zero) : An error occurred.



In above image, the "vi" program doesn't support the exit status. It always has the 0 exit status.

On the other hand, the "ls" program support the exit status. the below image is the manual of the "ls" program. the exit status can be checked.

checking the ls exit status


June 10, 2018

How to use awk

❑ AWK(alfred Aho, peter Wenberger, brian Kemighan) : The script language for text pattern scanning and processing.
* It is mainly used to extract specific columns of text data.
* /bin/awk
* /usr/bin/awk

❑ awk program grammar : awk [Option] '/[Pattern]/ {[Action]}' [File]
* After [Pattern] scanning in [File], [Action] is performed.



❑ awk Example

< Data file >
RegExr v3 was created by gskinner.com, and is proudly hosted by Media Temple.

Edit the Expression & Text to see matches. Roll over matches or the expression for details. PCRE & Javascript flavors of RegEx are supported.

The side bar includes a Cheatsheet, full Reference, and Help. You can also Save & Share with the Community, and view patterns you create or favorite in My Patterns.

Explore results with the Tools below. Replace & List output custom results. Details lists capture groups. Explain describes your expression in plain English.


CommandResult
$ awk '{print $1, $2}' ./file1
→ Print the first and second fields.
RegExr v3

Edit the

The side

Explore results
$ awk '/RegExr/' ./file1
→ Print records(paragragh) including "RegExr"(Case-sensitive).
RegExr v3 was created by gskinner.com, and is proudly hosted by Media Temple.
$ awk '/the/ {print "First column: ",$1,"\nnext column : ",$2}' ./file1First column:  Edit
next column :  the
First column:  The
next column :  side
First column:  Explore
next column :  results
$ awk '{print $NF}' ./file1
* NF : The Number of Fields in the current input record.
* '{print NF}' :  Print number of fields in each record.
* '{print $NF}' :  Print the last filed in each record.
Temple.

supported.

Patterns.

English.
$ awk '{print NR}' ./file1
→ Print the index of each records (paragraph).
* NR : The total number of records(paragraph) seen so far.
1
2
3
4
5
6
7
$ awk 'BEGIN {FS="Edit"} {print $1}' ./file1
→ Output the first field after separating the records based on "Edit".
RegExr v3 was created by gskinner.com, and is proudly hosted by Media Temple.

The side bar includes a Cheatsheet, full Reference, and Help. You can also Save & Share with the Community, and view patterns you create or favorite in My Patterns.

Explore results with the Tools below. Replace & List output custom results. Details lists capture groups. Explain describes your expression in plain English.
$ awk '$1 ~ /RegExr/ {print}' ./file1
→ If the first field is "RegExr", print the record.
* !~ : Not same.
RegExr v3 was created by gskinner.com, and is proudly hosted by Media Temple.
$ awk 'NR > 3 {print}' ./file1
→ Print the records existing after the third record.
The side bar includes a Cheatsheet, full Reference, and Help. You can also Save & Share with the Community, and view patterns you create or favorite in My Patterns.

Explore results with the Tools below. Replace & List output custom results. Details lists capture groups. Explain describes your expression in plain English.
$ awk 'NR==1, NR==3 {print}' ./file1
→ Print the records that are indexed 1~3.
RegExr v3 was created by gskinner.com, and is proudly hosted by Media Temple.

Edit the Expression & Text to see matches. Roll over matches or the expression for details. PCRE & Javascript flavors of RegEx are supported.
$ awk 'NR<5 && $1=="RegExr" {print}' ./file1
→ If the index is less than 5 and the first field is "RegExr", print the record.
RegExr v3 was created by gskinner.com, and is proudly hosted by Media Temple.
$ awk 'NR<4 || $1=="RegExr" {print $0}' ./file1
→ If the index is less than 4 or the first field is "RegExr", print the record.
RegExr v3 was created by gskinner.com, and is proudly hosted by Media Temple.

Edit the Expression & Text to see matches. Roll over matches or the expression for details. PCRE & Javascript flavors of RegEx are supported.
$ awk 'BEGIN {IGNORECASE = 1} /RegExp/' file.txt(Case-insensitive result)

※ This is tested all in [Vidio 1] and [Video 2]