2세대 블록체인의 대세는 이더리움이고 가장 저변도 넓다.

하지만 단점을 꼽는다면, 다소 늦은 점과 사용시에 수수료가 든다는 점이다.


이를 극복하기 위해서 리눅스재단과 IBM을 중심으로 하이퍼레저가 만들어졌으며

컨소시엄을 구성해서 운영하기에 좋은 형태이다.



개인적으로 생각하는 하이퍼레저의 단점을 나열해 보면


-하이퍼레저: 컨소시엄을 구성해서 운영해야 하는 부담이 있고

    그렇게 하지 않을경우, 보안성이 떨어진다. 

   물론 하나의 회사에서 4개이상의 노드를 구성해서 운영할 수도 있지만,

   이럴 경우 서버장애로 인한 안정성도 떨어지고, 

   소스를 자체수정해서 로직의 조작등의 가능성도 있기 때문에 보안성이 떨어지는 것이다.


그래서, 개인적으로는 수수료라는 큰 단점이 있긴 하지만

이것은 보통 ICO를 통해 극복이 되는 이더리움이 더 대세가 될 것이라고 판단된다.

(물론 이더리움이 이미 대세라고 보고 있다)



<이더리움과 하이퍼레저의 차이점>

 구분

 이더리움

 하이퍼레저

 오픈시기

 2015.7

 2017.7

 가상화폐

 ETH

 없음

 합의

 POW

 PBFT(자체 알고리듬- 타3개의 노드중 1개이상의 노드의 승인 필요)

 네트워크

 Public, (private에서도 가능)

 private

 스마트계약

 주로 solidity로 구현

 chaincode로 구현

 블록체인 구분

 Public

 Private

 기술기반

 EVM(자체구현) 

 Docker




참고사이트: REF

Posted by yongary
,

react설치:   npm install -g create-react-app

프로젝트 생성:  create-react-app hello-world    REF



============= Form 예제 =================== 


class Game extends React.Component {

  constructor(props) {

super(props);


this.onSubmit = this.onSubmit.bind(this);   //onSubmit등 이벤트를 쓸때는 생성자에서, 이 window로 onSubmit을 bind

  }


  onSubmit(event) {

event.preventDefault();

console.log(this.input.value)    //   this.input으로 바로 언급가능


//const data = new FormData(event.target);

let data={};

data.name = event.target[0].value;

data.value = event.target[1].value;


fetch('/api/form-submit-url', {

method: 'POST',

body: data,

});

  }


  onClick() {                                                      //각종 이벤트 정의 가능

     console.log('test);

  }


  render() {

            const list = [ 'test1', 'test2'];   //여기서 변수 선언 가능. const나 let을 많이 쓴다. ES6문법.


    return (

      <div className="game">        //html에선 class를 쓰지만, JSX에서는 className을 쓴다.

        <div className="game-board">

          <Board />

        </div>

        <div className="game-info" onClick = {this.onClick}> //이벤트를 이런식으로 호출 가능

          <div>{/* status */}</div>

          <ol>{/* TODO */}</ol>

        </div>


         <form onSubmit={this.onSubmit}>

                 <input onChange={this.onChange}  ref={input => this.input=input} />

         </form>         

      </div>

    );

  }

}




============= setState 예제 ===================


class
 App extends React.Component {

  constructor(props) {

super(props);


this.state= {                 //JSON포맷으로 state 지정

title: 'My Title'

};

this.onClick = this.onClick.bind(this);

  }


  onClick() {

      this.setState(               //state 수정시에는 꼭, setState() 함수로 수정

            {title: 'New Title'}

      );

  }


  render() {


    return (

      <div className="App">        

<h1> {this.state.title} </h1>    //state 사용

               <div onClick = {this.onClick}> Click here </div>

               <MyComponent />    //다른  Component 그리는 방법. 혹은

               

                //혹은 아래처럼 변경하면서 사용가능 : 

                // 이경우 MyComponent render() 첫줄에는  const {title, name, onClick } = this.props;  

               <MyComponent                        

                    title =' __'

                    name = 'My Name'

                    onClick = {this.onClick}

               />

      </div>

    );

  }

}



출처유투브

Posted by yongary
,

참고)  이더리움 용어:  transaction - writing하는 호출,   call-읽는 호출.

공부하기 좋은 소스: petShop




<Truffle> : 단어 의미는 송로버섯


이더리움 solidify 개발시에 간단한 웹환경인 remix가 공부하기 좋지만,

본격적으로 빌드환경 구성해서 개발하기에는 truffle이 좋다.   


설치: $npm install -g truffle

$truffle init    만 하면 개발폴더구조와 설정파일인 truffle.js가 생성된다.

$truffle compile - sol컴파일.

 


참고: 테스트 서버환경 (테스트용도임- 배포환경으로 적당치 않음)

truffle에 직접 lite-server를 사용하여 localhost:3000으로 test를 할 수도 있는데

이 경우엔 package.json을 만들어 "dev"란 이름으로 lite-server를 추가하고

$npm run dev 를 하면 된다.     => petShop truffle예제 참고   


$truffle console - crowd세일등을 test할 때, javascript console처럼 온라인 test가능. REF


좋은 crowd세일 예제:  REF



<Ganache> : 단어 의미는 초코+크림 반반 섞은 거시기


remix에서는 이더리움 지갑으로 metaMask를 쓰듯이

Truffle에서는 이더리움 client로 ganache를 사용하는게 좋다. (물론 다른 것들도 있다)


GANACHE  :  app을 실행하면

http://127.0.0.1:7545  에서 클라이언트 실행

                                 참고 8545 = TestRPC일경우.(주로 MetaMask랑 같이 씀) - REF

                                     truffle init # Initialize a default truffle project in that folder

truffle build # Compile the dapp truffle migrate # Publish the dapp on the blockchain truffle serve # Host your web interface on port 8080


Truffle + Ganache환경에서

truffle develop하면  http://127.0.0.1:9545 에서 클라이언트 실행해줌. 



<ROPSTEN-TestNet사용법>


 $npm install truffle-hdwallet-provider -save하고 나서


 truffle.js를 편집해서 ROPSTEN설정하고

           (ethpm.js도 점검하고)

$truffle publish  하면 ROPSTEN에 publish됨.




<Zeppelin>

Zeppelin기반으로 Token을 만들고 싶다면.. npm방식으로 zeppelin을 설치하는 방법과

ethpm방식으로 zeppelin을 설치하는 방법이 있는데..   


npm방식으로 하면 다른 소스들과 헤깔리기도 하고, 직접 zeppelin과 상관도 없는 많은 파일들을 받아야 하므로

딱 필요한 것만 받는 ethpm방식으로 설치하기를 추천한다.


ethpm.json파일만 만든 후에  REF

$truffle install zeppelin하면 intalled_contracts밑에 패키지가 설치가 되고..    REF

토큰관련 코딩후에는 그냥 

$truffle compile -> $truffle migrate로 다른 일반 contracts와 함께 개발이 가능한 것으로 보인다.

($truffle publish는 아직은 필요없는거 같은데.. 이건 ROPSTEN용도이려나? .... 아직 미 test중)



출처:Truffle공식사이트

Posted by yongary
,


비트코인 블록의 헤더가 6가지 간단한 정보로 관리되는데 비해,


이더리움 블록의 헤더는 무려 15가지 정보가 관리된다.   

   바디에는 Trasaction List와  Uncle List: (유효한 블록이지만 선택이 안된  List)가 관리된다.


이더리움 블록헤더

 부모Hash

 Uncle Hash

 보상: 채굴성공에 대한 보상금

 stateRoot :  상태 trie의 rootHash값

 transactionsRoot: transaction List에서 파생된 trie의 rootHash값

 수신자Root

 Bloom필터

 난이도 

 조상 블록의 개수

 gasLimit

 gasUsed

 시간(timestamp)

 extraData

 mixHash : 

그리고, 그 유명한 NONCE


REF



이더리움은 기본적으로 블록에  (비트코인처럼)완성된 데이타가 저장   되는게 아니고,  

최종상태와 transaaction List를 관리하고 있어서,  계산을 해야 최종상태를 알수 있다. 



헤더도 마찬가지 개념으로서, 바디의 2가지 정보를 위주로 

   parentHash와 nonce를 제외한 모든 헤더정보를 만들어 낸다고 볼 수 있는데,

자세한 사항은 (공부해서 보충예정)

Posted by yongary
,

REF


이더리움에서 계산량이 많을 경우를 대비해, 계산량이 많은 부분은 별도로 sidechain에서 계산을 해서

비용을 줄이도록 만든 블록체인으로  Loom Network가 대표적이다.



Posted by yongary
,

solidity는 이더리움에서 smartContract를 정의할때 사용하는 언어로서 javascript에다가 몇가지 기능을 추가한 언어이다.


헬로월드 수준은: http://www.chaintalk.io/archive/lecture/86 

             간단한 dApp예제는 : http://www.chaintalk.io/archive/lecture/501


공부하기 가장좋은 사이트는 크립토좀비.



거기서 공부한 예제를 보면 다음과 같다.

pragma solidity ^0.4.19;

contract ZombieFactory {

// 여기에 이벤트 선언 - 이벤트는 나중에 별도로

uint dnaDigits = 16;
uint dnaModulus = 10 ** dnaDigits;

//struct: 생성자 자동, myZombie.name 으로 접근.

//struct내에서는 uint(256) 보다는 uint8을 쓰는게 가스소모량을 줄인다.

struct Zombie {
string name;
uint dna;
}

Zombie[] public zombies; //변수나 함수 되에 public/private 선언이 가능하다.

//private함수 및 param의 이름은 _로 시작하는게 관례

// internal: 자식class에서도 호출가능-private은 안됨 external: 외부에서만 호출가능

function _createZombie(string _name, uint _dna) private {
zombies.push(Zombie(_name, _dna));
// 여기서 이벤트 실행
}

//view:읽기만 하는 함수외부서호출시gas불소모, pure:다른변수 전혀 안쓰는 함수, return은 여러개도 가능

function _generateRandomDna(string _str) private view returns (uint) {
uint rand = uint(keccak256(_str)); //이더리움에서 지원하는 SHA함수로 16진수 return. uint로 변환필요
return rand % dnaModulus;
}

function createRandomZombie(string _name) public {
uint randDna = _generateRandomDna(_name);
_createZombie(_name, randDna);
}
}


<Event>

  

//선언
event NewZombieAdded(uint zombieId, string name, uint dna);

//이벤트 실행: dApp으로 신호보내기 임.
NewZombieAdded(id, _name, _dna); //id= zombies.push(..)-1 로 가능. push는 length리턴.


  이벤트 받는 예제는 : REF


<Mapping> 매핑은 말이 Mapping이지 사용법을 array와 동일하게 만들어 놨음.
      msg.sender 이용(해보자) : 컨트랙트내의 함수를 외부에서 호출한 사람주소


mapping (address => uint) favoriteZombieMap; function setMyNumber(uint _myNumber) public { // `msg.sender`에 대해 `_myNumber`가 저장되도록 `favoriteNumber` 매핑을 업데이트한다 ` favoriteZombieMap[msg.sender] = _myNumber; // ^ 데이터를 저장하는 구문은 배열로 데이터를 저장할 떄와 동일하다 }


<Require> Require는 if 함수와 비슷하지만,  조건이 안 맞으면 에러를 낸다.  

  solidity에는 string비교함수가 없으므로 SHA해시로 비교한다. 

require(keccak256(_name) == keccak256("Vitalik"));



<상속> 

contract ZombieFeeding is ZombieFactory {
}

  


<storage 및 메모리>
storage: HDD 또는 heap느낌.  블록체인에 영구저장됨.  contract의 멤버변수들도 여기 해당됨.
memory: RAM 또는 stack느낌.

대부분 storage/memory구분없이 사용해도 자동으로 되긴 하지만, function내에서 struct/array처리시 구분해서 사용해야할 경우가 있다.


<Interface>  

contract와 포맷이 동일한데, 내부함수에 body없음.

=> 다른 contract내의 함수를 호출할때 사용한다.

contract KittyInterface {
function getKitty(uint256 _id) external view returns (uint a);
}



<OpenZeppelin의 Ownable.sol>  => 이걸 상속받으면  onlyOwner modifier로 간단히  owner제약.  

owner 만 실행가능함. 

//1. import ownable.sol, 2. 상속 (is Ownable) 3.아래처럼 사용

function setKittyContractAddress(address _address) external onlyOwner {
kittyContract = KittyInterface(_address);
}


onlyOwner와 같은 modifier에 인자도 추가 가능.

modifier aboveLevel(uint _level, uint _zombieId) {
require(zombies[_zombieId].level > _level);
_; //실행코드가 한줄은 필요..
}



<각종 시간>

1 minutes :  60  임 (초단위까지 네요)

5 minutes: 300 

 secondsminuteshoursdaysweeksyears 같은 시간 단위 또한 포함하고 있다네. 이들은 그에 해당하는 길이 만큼의 초 단위 uint 숫자로 변환되네. 즉 1 minutes는 601 hours는 3600(60초 x 60 분), 1 days는 86400(24시간 x 60분 x 60초) 같이 변환

// 마지막으로 `updateTimestamp`가 호출된 뒤 5분이 지났으면 `true`를, 5분이 아직 지나지 않았으면 `false`를 반환 function fiveMinutesHavePassed() public view returns (bool) { return (now >= (lastUpdated + 5 minutes)); }



<Payable>

function levelUp(uint _zombieId) external payable {
require(msg.value == levelUpFee);
zombies[_zombieId].level++;
}


//인출 코드 예제.
uint itemFee = 0.001 ether; msg.sender.transfer(msg.value - itemFee);



Posted by yongary
,


build.gradle에서 npm run build 수행방법:


plugins {
id "com.moowork.node" version "1.2.0"
}
apply plugin: 'com.moowork.node'
task npmBuild(type: NpmTask) {
args = ['run-script','build']
}
build.dependsOn npmBuild



그리고, jar하면서 react.js의 결과파일을 static으로 넣는 방법은

 web-frontend 프로젝트를 별도로 만들고, (위의 build.gradle작업은 여기서 하고)


메인 spring-boot-webapp 프로젝트의 build.gradle에서   아래와 같이  의도적으로 build밑에껄 복사해준다.

jar {
//blabla
from {
configurations.compile.collect {it.isDirectory()? it: zipTree(it)}
}
into('static') {
from('../web-frontend/build')
}
}


Posted by yongary
,

Ajax axios, Redux

React.js 2018. 2. 25. 23:26


React에서 ajax기능을 사용할때는 axios HttpClient를 많이 사용한다.   REF



  axios.get('/user?id=velopert')

    .then( response => { console.log(response); } ) // SUCCESS
    .catch( response => { console.log(response); } ); // ERROR

axios.post('/msg', { user: 'velopert', message: 'hi' }) .then( response => { console.log(response) } ) .catch( response => { console.log(response) } ); //catch는 생략가능

//IE 호환문제 ? babe-polyfill로 해결? -> test해보자.

class 활용 예제. 

https://laracasts.com/discuss/channels/servers/get-data-out-from-axios-javascript



Redux 는 study중:    dispatcher방식으로 state관리  https://velopert.com/1225   




=================물론 jquery $.ajax도 사용할 수 있다 =================


 (POST앞에 있는것은 커서임)


출처:유투브



Posted by yongary
,

키보관 방법

블록체인 2018. 2. 18. 00:03

키나 IOTA seed를 암호화해서 보관하고 싶으면


파일을 알집으로 암호넣어서 zip을 한다음에


axcrypt.net에서 프로그램을 다운받아서 아주 긴 비번으로 로그인을 해서, 암호화를 하도록 한다.

256bit 알고리듬으라 안전하다.  



Posted by yongary
,

kubernetes

SDN,cloud,Puppet 2018. 2. 12. 19:19

Docker를 여러개의 host에서 쓴다던지 하는 경우로 인해,

서로 다른 Host내의 docker끼리 통신을 해야한다면(inter-host comm.)


Kubernetes를 사용하면 된다. 

Kubernetes에는 그 외에도 몇가지 기능이 있는데.. 


Posted by yongary
,

비트코인 지갑

블록체인 2018. 2. 1. 23:07

 REF

 비트코인 지갑 : 처음들으면 Bitcoin이 들어있는 것으로 착각들을 하지만, 실제로는 private키만 보관한다.

   종류는 인터넷에 연결된 Hot Wallet과  그렇지 않은 Cold Wallet이 있고 ,   HD(계층 결정적)Wallet도 참고삼아 보자.


  Hot Wallet - full node에는 full wallet,  SPV Node에는 SPV(Simple Payment Verification) wallet. 

                     전체 blockchain을 저장하지 않으면서 full node들의 메모리를 이용하는 가벼운 장점으로 인해, 모바일을 비롯해 많은 SPV wallet들이 발전중이다.


  Cold Wallet - 종이나 USB 혹은 특별히 제작된 Hardware와 같이 offline으로 private key를 저장하는 Wallet.




  HD Wallet - 24개 이하의 단어를 쓰면 private key를 생성해줘서 약간 외울수 있는 수준의 private key를 만들어 주는 지갑.

             brain Wallet도 비슷한 개념인거 같네요.   암튼 이것도 단어는 추측이 쉬워서 보안에 취약하다는 거...  

        정리하면) 단어를 이용해 pk를 만들거나 단어를 통해 pk를 암기하는 방식으로 pk를 안외워도 되는 방식이지만 보안에 썩 좋진 않음

        ==> 그래도  왠지 이게 끌리네요. 가성비가 좋을듯. 



 -------------  private key를 보관하지 않는 wallet --------  비트코인 지갑이라고 부를수 없을것 같구요

  Web Wallet- pk를 3자에게 맡긴 것으로, 거래소 등에 Wallet을 맡겼다고 보면 된다.  당근 위험!  

Posted by yongary
,

jQuery의 팝업 기능으로 간단히 이쁜 layer팝업을 만들수 있다.

 - 이걸 모를때는 bootstrap을 사용했었는데, jQuery가 더 편하다.

  (이쁘기는 bootstrap이 더 이쁠 것 같아요)



- 사용법도 간단하다.  REF


1. jquery관련 인클루드

  <script type="text/javascript" src="blabla/js/jquery.popup.min.js"></script>


2. html 팝업코딩

  <div id="popup" class="pop_style">

     blabla

  

3. jquery로 호출.

  뛰우기:  $('#popup').bPopup();


  close:   $('#popup').bPopup().close();

Posted by yongary
,

Excel upload

springBoot gradle 2018. 1. 23. 11:46

 poi 이용 : 한글 REF 

    영문: REF



1. maven dependency 추가.

<dependency>

<groupId>org.apache.poi</groupId>

<artifactId>poi</artifactId>

<version>3.15</version>

</dependency>

         <dependency>

            <groupId>org.apache.poi</groupId>

            <artifactId>poi-ooxml</artifactId>

            <version>3.15</version>

        </dependency>

<dependency>

            <groupId>org.apache.poi</groupId>

            <artifactId>poi-ooxml-schemas</artifactId>

            <version>3.15</version>

        </dependency>

        <dependency>

            <groupId>org.apache.poi</groupId>

            <artifactId>poi-contrib</artifactId>

            <version>3.6</version>

        </dependency>


2. JSP

function fnCheckUpload() {

var file = $("#excel").val();

if(file == "" || file == null){

alert("먼저 파일을 선택하세요.");

return false;

}

var fileFormat = file.split(".");

var fileType = fileFormat[1];

if(confirm("업로드 하시겠습니까?")){

$('#excelUpForm').attr('action','/uploadMoveinExcel.do');

var options = {

fail:function(data) {

        alert('저장 오류가 발행하였습니다.');

        $('#popup').bPopup().close();

        },

success:function(data){

alert(data + "건 업로드 완료");

$('#popup').bPopup().close();

},

type: "POST",

data : {"excelType" : fileType}

};

$('#excelUpForm').ajaxSubmit(options);

}

}

-----HTML--------

<form id="excelUpForm" method="post" action="" role="form" enctype="multipart/form-data">

                                    <input  id="excel" name="excel" class="file" type="file"  >


</form>



3. controller

  @ResponseBody

@RequestMapping(value="/uploadMoveinExcel.do")

public String uploadExcel( MultipartHttpServletRequest request, HttpSession session) {

List<ExcelVo> list = new ArrayList<>();

String excelType = request.getParameter("excelType");

log.info("uploadExcel.do + excelType:" + excelType);

if(excelType.equals("xls")){

list = moveinService.xlsExcelReader(request);

}else if(excelType.equals("xlsx")){

//IN_STUDY:  list = adminAccountsMngService.xlsxExcelReader(req);

}

int cnt = service.uploadList(list);

return String.valueOf(cnt);//success cnt : media처리의 경우, JSON포맷으로 잘 안변함(config필요), 따라서 간단히 숫자만 리턴.

}


4. service

  public List<MoveinExcelVo> xlsExcelReader(MultipartHttpServletRequest request) {

// 반환할 객체를 생성

List<MoveinExcelVo> list = new ArrayList<>();


MultipartFile file = request.getFile("excel");

HSSFWorkbook workbook = null;


try {

// HSSFWorkbook은 엑셀파일 전체 내용을 담고 있는 객체

workbook = new HSSFWorkbook(file.getInputStream());


// 0번째 sheet 반환

HSSFSheet curSheet = workbook.getSheetAt(0);  //workbook.getNumberOfSheets()

// row 탐색 for문

boolean isInTable = false;

for (int rowIndex = 0; rowIndex < curSheet.getPhysicalNumberOfRows(); rowIndex++) {

//헤더 Cell 찾기.

String firstCellValue = curSheet.getRow(rowIndex).getCell(0).getStringCellValue();

if ("구분".equals(firstCellValue.trim())) { //table헤더 발견.

isInTable = true;

continue; //헤더는 pass.  (다움줊부터 paring시작.)

}

if (isInTable) { //in Table 파싱 시작. ///////////////////////////////////////////

HSSFRow curRow = curSheet.getRow(rowIndex);

//필수 Cell들.

String cellStr = curRow.getCell(2).getStringCellValue(); //String 읽기

String cellDate =  StringUtil.toYYMMDD(curRow.getCell(5).getDateCellValue()); //날짜 읽기

String cellNum = curRow.getCell(7).getNumericCellValue() + ""; //산차.

  String cellLongNUm = StringUtil.toIntString(curRow.getCell(12).getNumericCellValue() ;   //엄청 긴 숫자 읽기

. . . . 

} catch (IOException e) {

e.printStackTrace();

}


// vo로 만들면서 db에 삽입코드는 생략.

return list;

}


public class StringUtil {


    private static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

    public static String datePattern = "^\\d{4}[\\-](0[1-9]|1[012])[\\-](0[1-9]|[12][0-9]|3[01])$";

    public static boolean isDate(String str) {

    return Pattern.matches(datePattern, str);

    }

    //return YYYY-MM-DD String

    public static String toYYMMDD(Date date) {

    return formatter.format(date);

    }

    public static boolean isNumericOrFloat(String str) {

        if (str == null) {

            return false;

        }

        int sz = str.length();

        for (int i = 0; i < sz; i++) {

            if (Character.isDigit(str.charAt(i)) == false) {

            if (str.charAt(i) != '.')  //Added KY. '.'도 numeric으로 간주. float때문에.

            return false;

            }

        }

        return true;

    }

    

    //For Excel processing.

    // 엑셀에선 숫자를 항상 double로 읽기 때문에 int형태의 String으로 변환하면 유용.

    public static String toIntString(double doubleVal) {

    try {

    BigInteger k = new BigDecimal(doubleVal).toBigInteger();

    

    return String.valueOf(k);

   

    } catch (Exception e) {

    return null;

    }

    }

Posted by yongary
,

특수기능

ElasticSearch 2018. 1. 22. 21:38

template: 여러개의 template을 지정해 놓을 수 있음.

     -> 잘못 사용하면 여기에 계속 걸려서, insert가 안되는 경우도 있으니 조심필요.



join: 부모-child관계 지정.   (예:질문-답변)  REF

       RDB의 relation과 어느정도는 유사하게 사용이 가능하지만,

       one-to-many 관계에서만 사용하는 게 좋다. 

       (그리고, 한 index안에서만 사용한다 )


 -Relation: 부모와 자식관계 설정

 -Child 여러 개 설정 가능

- (손자)Child 밑에 Child를 둘 수 있음





_segment: segment내의 data까지 조회가 가능하다.





Posted by yongary
,

js 모듈화 코딩기법

jquery 2018. 1. 2. 09:14

http://www.nextree.co.kr/p4150/  

Posted by yongary
,

기본 Query예제

ElasticSearch 2017. 12. 31. 08:22


kibana필터 기본 문법:   REF - 루씬 문법임. . 

     title:(+return +"pink panther") : Field grouping - REF

  

timeliion 문법: REF



== 그 외 아래는 elastic 기본 Query예제이다. ====================================

 



  Index데이타넣기 + 자동생성 : REF


PUT /twitter
/doc/1 (1은 생략시 자동생성) { "user" : "kimchy", "post_date" : "2009-11-15T14:12:12", "message" : "trying out Elasticsearch" }



Index 생성 및 Mapping 조정: REF

PUT twitter :생성 {} PUT twitter/_mapping/_doc { "properties": { "name": { "type": "text" } } } //type:keyword가 중요

데이타 타입: REF



문서하나 Delete:

    DELETE /twitter/_doc/1

   


 Delete Index:

 DELETE /twitter






  Match:  REF


GET entry/_search

{

  "query": {

    "term": {"play_name":"Hamlet"}

  }

}


GET entry


GET /_search { "query": { "match" : { "message" : "this is a test" } } }



Posted by yongary
,

랜섬웨어 감염시

IT 2017. 12. 30. 10:22

랜섬웨어에 감염되어 파일들이 확장자가 변경되면서 실행이 안된다면..


1. windows/system32/tasks  밑에 가서, 날짜를 보고 최근 것들을 지운다.

  => 랜섬웨어 동작을 멈추게 한다.

  (그 후 고클린 등으로 각종 clear작업을 해주면 더 좋다)


2. 이미 감염된 파일들은 복구가 불가능 한데, 

   https://www.nomoreransom.org/ko/index.html   여기에 가면 일부 복구가 되는 랜섬들이 나열되어 있으므로

   따라서 복구를 한다.

Posted by yongary
,

spring boot로 Web Project생성하기.


1. https://start.spring.io/  에 접속해서  maven/gradle을 선택하고 이름만 넣으면  springboot프로젝트를 생성할 수 있다.  

   => 일반 application이 생성된다.


  1.1  IDEA나 eclipse에서 import project를 해서 열어서 Run만 시키면 돌아간다. (아래과 같이 spring을 볼수 있다)

    .   ____          _            __ _ _

 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \

( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \

 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )

  '  |____| .__|_| |_|_| |_\__, | / / / /

 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::        (v1.5.9.RELEASE)



2. Build.gradle을 열어서  아래 한줄을 추가한다.   (JDK1.8기준)


compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '1.4.7.RELEASE'
(version: '1.4.7.RELEASE')

 

   ==> 자동으로 Web Application이 된다. 실행도 되고 localhost:8080 접속도 된다.


3.  jsp처리기능이 아직없으므로 이를 위해 2개 더 추가한다. (REF1, ) 

    

compile group: 'javax.servlet', name: 'jstl', version: '1.2'
compile group: 'org.apache.tomcat.embed', name: 'tomcat-embed-core', version: '8.5.24'
compile group: 'org.apache.tomcat.embed', name: 'tomcat-embed-jasper', version: '8.5.24'

   

     (그리고, resources밑에 있는 application.property에  아래 4번 경로와 suffix를 추가한다)

     


spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp



4.  src/main  밑에  /webapp/views  밑에    jsp생성  (REF2-jsp) 

     
  jsp첫줄에는 아래 한줄이 필요하고..

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

 그 후 <html> tag야 있으면 좋고..





별첨: 간단한 Junit4 Test코드.... + RestTemplate는 여기 참조:   REF

         Lombok사용시 - 설정에서 컴파일러 옵션 중 Annotation Process 체크필요.

Posted by yongary
,

MVC개념

springBoot gradle 2017. 12. 29. 21:56

      USER가 url을 요청한다던지 하는 action을 하면, controller가 받아서 

     Model을 조회/변경하고 그걸 다시
     View에서 그려준다.  


    3가지가 분리되어서 업무분리 개발분리가 가능해진다. 

Posted by yongary
,

1. 해시캐시 (HashCache)

   - 해시함수를 fn(X) = Y 로 표현한다면, X는 입력값 Y는 출력값이다.
     이 중에서 이쁜 Y를 만들기 위해 X를 바꿔가며 입력할 수 있는데, 
     이쁜 Y를 만든 X를 HashCache라고 부를 수 있다.
    

     그런데 X에는 자동으로 고정되는 값이 몇개 포함되어 있어야 하고, 
     사용자가 임의로 설정할 수 있는 값도 있어야 한다.

     즉, 수신자의 메일주소와 같이 바꿀 수 없는 값 + 사용자가 임의설정 가능한 카운터 = X로 했을때
     이쁜 Y를 만들 수 있는 X를  HashCache라고 부를 수 있다.


     (해시캐시의 개념은 스팸메일 필터링에서 나온 개념이므로 수신자의 메일주소를 주로 포함한다.

     90년대 국제표준에서는 Y의 앞자리20자리가 0이 되는 X값을 해쉬캐시로 정했었다.)



2. Nonce
   - 위 예제에서 사용자가 설정한 임의의 카운터를 Nonce라고 부를수 있다.  나머지 고정된 값들을 제외한 사용자가 

      고생을 해서 산출해야 하는 값이다.

   - 이쁜 Y라고 부르는 이유는, Y값의 범위를 정하거나 모양등을 정하므로서, 알고리듬의 복잡도가 탄생한다. 

      즉, Y값을 000000000xxxxxxx 이런식으로 고정한다면, 이를 위해서 사용자는 nonce를 여러번 생성해봐야지 적당한 nonce를 구할 수 있다.

   - 비트코인에서는 총32Byte(256bit) 중,  앞자리 40 bit가 0이어야 한다.



이러한 해시캐시(Nonce포함)개념으로 하나의 블록을 생성한다. 


3. 블록체인

  - 앞에서 설명한 하나의 블록을 여러개 연결한게 블록체인이다.

  - 연결방식은 뉴블록 = 직전블록의 Hash값 +  뉴데이타 + 뉴Nonce 이다.   

   - 뉴뉴블록 = 뉴블록 Hash값 + 뉴뉴data + 뉴뉴nonce로  항상 직전 Hash값만 포함한다.

     이것만으로도 이전의 모든 블록들을 마치 다 포함하는 것처럼, 앞 선 모든 블록들을 아무도 고치지 못하는 효과가 생긴다. 


 

  




Posted by yongary
,

이더리움

블록체인 2017. 12. 26. 11:57

비트코인 다음으로 인기가 많은 이더리움에선 다음과 같은 용어들이 사용된다.


Wei:   1ETH = 1000 0000 00 GWei. (1Gwei:0.001원 정도,  만개쓰면 10원.  1ETH가 100만원일 때)

          1 Ether = 1000000000000000000 Wei 


GasPrice: cost of computation - 계산비용으로서 모든 operation에 대한 계산비용이 trasaction originator에게 지불이 된다.

           :  Gas is a unit of measurement for computational steps. Every transaction is required to 

            include a gas limit and a fee  that it is willing to pay per gas (that is, pay per computation) 


GHOST (Greedy Heaviest Observed Subtree) - 기존 longest chain대비 heaviest chain개념을 도입하여

                   이를 기준으로 가장 계산이 많이 사용된 chain을 결정한다. 




SmartContract:  code is law라는 슬로건아래 코드에 적히면 모두 계약이 된다.


Solidity:  smartContract를 가능하게 하는 튜링완전성을 지닌 script언어 - REF



Bootstrap node:

mainnet vs testnet:  mainnet이 주 network이고 testnet은 개발용.

Whisper & Swarm : 분산 프로토콜 & 분산 디스크.



Geth (Go-Ethereum) :  brew tap ethereum/ethereum ->  brew install ethereum

JSON-RPC : https://github.com/ethereum/g o-ethereum/wiki/JavaScript-Console


 


Mist: 이더리움 client


casper: POS(proof-of-stake) 의 단점을 보완하는 프로토콜. 
            POS는 컴퓨팅파워가 아니라 지분에 비례한 확률로 next block이 선정된다.

           이더리움이 현재는 POW방식이지만 2018년 중에 POS로 바뀔 예정.


dApp: 

         개발환경을 SPA로 해서 웹기반으로 하는 경우가 많은데
        Meteor.js를  사용하기 좋다고 한다.  Meteor REF

        필자는 react.js + springBoot로 해볼 예정.

        


faucet:


truffle contract: 




parity + Aura protocol:  POA(Authority)를 지원하므로 private형태나 은행협의체 형태의 blockchain을 개발하고자 할때 유용하다.


Posted by yongary
,


kibana에서 


search 구문 예제: 

text:java AND NOT(text:hiring) AND users.some_count[500 to *] 

timelion 구문: ref

.es(q=(text:java)).divide(.es(q=(text:kotlin)).multiply(100)





========================만들기 =============================

REF- 웹강의 와 sample소스가 있음.   REF-개요페이지


      강의내용중 URL :  plugin 개발-UI Exports 



js로 

1. visController  class 를 만든다. (ES6 js일듯)

  - constructor

  - render

  - destory 함수가 있는데..   예제에선 text만 뿌리는 수준이다.


2. visualization class를 만든다.

  


To follow along during the webinar:

  • Set up your Kibana development environment (preferably the master branch)
  • Use sample code from the webinar to create your own visualizations
  • Reference Contributing to Kibana Github repo for any issues

Related Resources: 



멋진 그림을 그릴 수 있으려나...  스터디 중.



Posted by yongary
,

 elastic 을 설치한 후,  curl로 test를 하는게 약간 귀찮게 느껴 진다면


Sense 에디터를 이용해서 test하는 게 편하다.  (PUT data.json을 바로 이용하는 느낌으로 사용)

Sense는 Kibana의 일부(plugin) 이기 때문에 kibana설치 후 사용이 가능하다. REF


  ==> 요즘은 (5.x부터)  Kibana만 설치하면  Dev Tools메뉴에서 바로 사용 가능.

  

 query명령어는 여기를 참조해서 공부한다.  REF(elastic 영문사이트)





그리고 참,  혹시 elasticsearch에 data가 없다면  이 sample data를 이용한다. REF





Posted by yongary
,

Java Rest Client

ElasticSearch 2017. 12. 15. 17:40

ElasticSearch용 java client를 구현하는 방법은 여러가지가 있다.


app으로 REST를 구현해도 되고

jest를 이용하거나

spring-data-elasticsearch  를 이용해도 된다.



spring 이용해서 간단하게 해보고 싶으면 여기추천:  REF





하지만, 일단은 공식 java client를 먼저 검토추천 한다고 하는데..(개인적으론 아직 익숙치 않아서인지 불편해 보인다) 

(node간 통신시 binary포맷으로 바꾸어야할 필요성도 있다고 하는데? 그래서 공식 client가 좋은건가? 싶은데 검토필요)


공신 client 사이트는 : REF  javadoc


사용법은 

Map<String, String> params = Collections.emptyMap();
String jsonString = "{" +
            "\"user\":\"kimchy\"," +
            "\"postDate\":\"2013-01-30\"," +
            "\"message\":\"trying out Elasticsearch\"" +
        "}";
HttpEntity entity = new NStringEntity(jsonString, ContentType.APPLICATION_JSON);
Response response = restClient.performRequest("PUT", "/posts/doc/1", params, entity); 



이 예제   elastic core 를 이용하고 있군요.. javadoc

Posted by yongary
,

Aggregation

ElasticSearch 2017. 12. 15. 17:11



REF (한글개념)   REF(영문 aggregation)   


Elastic에서 복잡한 검색은 mongoDB에서처럼 aggregation이란 용어를 사용해서 수행한다.



- Metric Aggregation: 산술식 

    : script Aggregation:   map & reduce방식으로 script를 이용해 동작할 수 있다. ref

    : Cardinality Aggregation:   distinct count 느낌.  ref (cardinal=기수, 즉 1234에서 10진수 기수는 4개)



- Bucket Aggregation: 그루핑
   : filter Aggregation:  group by느낌이고  where절을 filter에서 거는 느낌으로 사용한다. ref

    


- Matrix  :  멀티Field.    단, scripting은 미지원.


- Pipeline   : aggregation + aggregation





Posted by yongary
,

블록체인

블록체인 2017. 12. 13. 21:27

블록체인 개념을 잡기 좋은 2가지 글.



1. Proof of Work개념도 : REF

  - 비트코인에서 처음으로 쓰인 용어로서, 거래의 시작(비트코인에서는 mine 채굴완성)을

    검증하기 위해 여러개의 core 클라이언트 노드에서 인증을 하는 프로세스를 의미.

   


2. Java소스로 설명: REF





비트코인 Node: P2P 네트워크를 이용하는데, 노드들은 2가지 종류가 있다.

  1. Full Node : Wallet, network라우팅 외에, mining기능, full blockChain저장 기능. 

  2. SPV node: Wallet기능과 network라우팅 기능만 수행.


코어node 스타트시: 
               ( 비트코인 core 클라이언트에 하드코딩되고, 비트코인 community멤버에 의해유지되는 DNS seeds를)
                  DNS 쿼리를 통해,  모든 core peer들을 찾는다.  




3. Conflict 해결 방법:

    80번 block이 최신버전인 상태에서,  동시에 약 3개의 81번 block이 peer들에서 생성이 된 경우, 어떤 로직으로 진짜 81을 선택하는가?


    비트코인에서는 Longest Chain Rule을 적용한다.

      - 81a, 81b, 81c 3개가 비슷한 시점에 들어왔다면 
      - 그 다음 82가 먼저 들어오는 block 즉 내가 81a+82a를 만들기전에  81b+82b를 본다면 82b를 채택해서
        83b를 만들면 된다.

      - 즉, 81a가 없어지고 83b가 되는 것이다. 이렇게 해서 Logest Chain을 구현한다.


    

4. Double Spend로직: (해킹이 어렵도록 하는 로직 중 하나)

   - payment 기록을 2개를 만든다. (하나는 online판매자용, 하나는 나를 위한 전용)

   - 판매자용 기록만 전송한다.

   - 기록이 honest block에 기록되면 일단 판매자는 상품을 전송하고, 나는 상품을 받는다.

   - 조용히(비밀리에) Longer Chain of block을 만드는데 이때는 판매자용 기록은 제외하고,
     나를 위한 기록을 추가한다.

   - Longer Chain을 publish한다.  Longest chain rule에 의해 기존 판매자용 기록은 없어지고,
     새로만들어진 chain으로 대체된다.

   

Posted by yongary
,

REF (ref에는 일반 javascript방식도 포함되어 있어요)

REF - window센터맞추기(dual포함)



팝업 뛰우기:


var witdh = 600;

var height = 400;

var left = (screen.width/2)-(witdh/2);

var top = (screen.height/2)-(height/2);

window.open('url','myTitle',

'top=' + top +',left='+ left +',width=' + width + ',height=' + height +  ',toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes');


크롬에서 size조절이 잘 안될 경우에는 아래 css 추가

<style>

html,body {overflow: hidden;}

</style>



그리고, 듀얼 스크린을 고려한 w/h는 

var w = 600;

var h = 550;

//dual

var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;

    var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;


    var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;

    var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;


    var left = ((width / 2) - (w / 2)) + dualScreenLeft;

    var top = ((height / 2) - (h / 2)) + dualScreenTop;





팝업에서 부모창에 값 전달하기

$("#parentId", opener.document).val(부모창으로 전달할 값);



부모창에서 값 가져오기

$("#parentId", opener.document).val();


사용빈도는 낮지만, 부모창에 존재하는 함수호출

$(opener.location).attr("href", "javascript:부모스크립트 함수명();");



부모창 Submit:

var form =  $('#searchForm', opener.document);

form.submit();



//팝업창 닫기

window.self.close();


//부모창 refresh

window.opener.document.location.reload();


Posted by yongary
,

화면에 존재하는 id가 item_table인 테이블의 자식들을 모두 지우고

순서를 변경해서 모두 다시 add 하는 예제. (가상의 data라는 정보를 이용해서 추가함)

(예쁘게 add하기 위해 colspan을 항상 조정 함.)


이 때, tr은 매번 만들어서 추가하는 방식 임.

테이블은 한 row당 4개의 항목 (th+td가 한항목)까지 max로 들어가므로 총 12개의 colspan을 이용해 추가함.



               var table = $('#item_table');

    var itemsTh = $('#item_table th');

var itemsTd = $('#item_table td');


//remove all

table.children().remove();

var items = []; //sorted MenuItem data

//sort

        for (var i = 1; i <= data.length; i++) { //itemOrd는 1부터 시작.

        for (var j = 0; j < data.length; j++)

        if(data[j].itemOrd == i && data[j].useYn == 'Y') //useYn도 여기서 check필요.

        items.push(data[j]);

        }

        var newTr = $('<tr> </tr>');

        var sumColspan = 0;

        var colspan;

        var tdIdx;

    //items 다시add to tr -> table

        for (var i = 0; i < items.length; i++) {

        //find th/td

        tdIdx = findTdNum(items[i].itemCd, itemsTd);

       

        //add to tr, td는 colspan setting max 12개 td기준. 

        itemsTh.eq(tdIdx).text(items[i].itemNm);

        sumColspan += 1;

        newTr.append(itemsTh[tdIdx]);

       

        colspan = getColspan(items[i].itemStep);

       

        //colspan 조정.(여분 tr을 꽉 채우기) max=12

        var nextColspan = getNextColspan(items.length, i+1, items );

        colspan = adjustColspan(colspan, sumColspan, nextColspan );

       

        sumColspan += colspan;

        itemsTd.eq(tdIdx).attr('colspan', colspan);

        newTr.append(itemsTd[tdIdx]);

       

        //tr이 꽉차면 add tr 2 table

        if (sumColspan >= 12) {

        table.append(newTr); //test

        newTr = $('<tr> </tr>');

        sumColspan = 0;

        }

        } //items LOOPS

       

        if (sumColspan != 0) {

        //마지막 colSpan정리

        var finalColspan = adjustColspan(colspan, sumColspan-colspan, 99);

        itemsTd.eq(tdIdx).attr('colspan', finalColspan); //마지막 colspan재설정.

        table.append(newTr); //마지막 남은 tr add

        }

Posted by yongary
,

.attr 호출시 dom.eq(idx)

jquery 2017. 12. 7. 15:26


상식적으로는 itemsTd[0].attr('id') 가 될 것 같은데, 안되고 attr is not a function 오류가 발생한다.


itemsTd는 DOM이라 동작하지 않고,  jquery Object를 가져와야 함.

==> .eq(idx) 이용.




var itemsTd = $('#item_table td');

console.log( itemsTd.eq(0).attr('id') );

Posted by yongary
,

ajax 예제 (jquery)

jquery 2017. 12. 6. 17:27

jquery를 이용한 ajax 예제입니다.


post 예제: ==> 이 경우 spring에서는 @RequestBody로 바로 받을 수 있음.


    $.ajax({

        url:'./misetStore.do',

        type: 'POST',

        contentType: 'application/json',

        data: JSON.stringify(itemList),    //JSON data를 string으로 넘기기. 

        success:function(data) { 

        alert('저장되었습니다');

        },

        fail:function(data) {

        alert('저장 오류');

        }

        

});//ajax



  get 메서드 일 경우에는, url만 기입하면 됨.

       url:'./getSubMenu.json?' + 'noMenuUp=' + noMenu,

Posted by yongary
,