블록체인

블록체인 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
,

Web Service-SOAP

IT 2017. 11. 28. 09:40

요즘은 REST가 대세이긴 하지만,

SOAP도 나름대로의 장점이 있다. 이 기종간 명확한 spec기반의 통신이 가능하다.


SOAP을 위해서, WSDL을 먼저 생성하는 게 좋은데

eclipse나 IDEA에서도 생성이 가능하지만


oXygen XML 에디터가 좋아보인다.



생성된 WSDL기반으로 테스트 하기에는 SOAP UI라는 툴이 좋아 보인다.  REF

다운로드는 https://www.soapui.org/  에서 Download로 들어가면 SoapUI OpenSource가 있다. 

Posted by yongary
,

login 관리

Spring 2017. 11. 20. 21:59

Login구현시에는 cookie + session을 섞어서 쓰는게 일반적이다. REF


쿠키는  날짜를 지정가능

세션은  id/비번등 주요정보 저장 가능.  단 브라우저 종료시 사라짐. 


즉,

세션이 브라우저 종료시 사라지는 문제가 있으므로, 

쿠키를 이용해 이를 보완해야 한다.  쿠키에 날짜/시간이 지정 가능하므로 이를 이용해서 세션ID등을 저장해 보완하면된다.




Posted by yongary
,

Column

Hadoop 2017. 11. 18. 20:42

 String은 ENCODING STRING으로

 숫자는   ENCODING BINARY로 하는 게 속도가 빠름.


REF

CREATE HBASE TABLE enc_str (
   ti TINYINT, si SMALLINT, i INT,
   bi BIGINT, b BOOLEAN, f FLOAT,
   d  DOUBLE, s1 STRING, s2 STRING,
   s3 STRING, s4 STRING, s5 STRING
) 
COLUMN MAPPING ( 
   KEY MAPPED BY (s1,ti,bi,i) ENCODING STRING,
   f1:a MAPPED BY (si,s2,f) ENCODING STRING, 
   f1:b MAPPED BY (d,b,s3) ENCODING STRING,
   f1:c MAPPED BY (s4,s5) ENCODING STRING
);


Posted by yongary
,

가벼운(lightweight) 확장가능한 data shippers.  data를 수집하고 shipping.

  (logstash가 무겁기 때문에 가볍게 만든 agent?)



Libbeat - 기본 라이브러리 

   Config

   Setup

   Run  - 데이타를 elasticSearch나  logstash로 전송. 

   CleanUp

   Stop  

   의 함수들을 구현(override)하면 새로운 beat을 만들 수 있음.



Packetbeat - 클라이언트에서 서버로 보내지는 데이타를 수집 

Topbeat - 시스템정보 수집

 -> 5.0부터 MetricBeat로 바뀜.


그외에도 각종 beat들이 만들어지고 있음.



  나만의 beats만들기 REF REFY



Posted by yongary
,

Pheonix

Hadoop 2017. 11. 16. 10:18

Hive가 batch오리엔티드인데 반해

Phoeix는 real-time Query도 수행하도록 만든 빠른 레이어이다.

  -query를 HBase scan으로 만들어 빠르게 수행한다. 

  -HBase API를 바로 사용도 가능. 

 ==> 그냥 jdbc 드라이버+SQL지원 정도의 용도로 많이 사용한다.



----------------------------------- 

Phoenix : RDB 레이어 over hBase.

 - Query engine + Metadata 저장소.

 - JDBC driver 제공.


 - Hive와 같이 join등 제공. 


 <Secondary index 방식 3가지>

 - write only / + append 방식 

 - global for read-heavy mutable data

 - local for write-heavy mutable or immutable


각종 join모두 지원.


 

Phoenix Calcite ? 


----View생성 from HBase 테이블:  이름  transactions, ColumnFamily:transactions일때

 CREATE VIEW "TransactionHistory" (k VARCHAR primary key, "Transactions"."transactionId" VARCHAR);. 

 =>  Select "transactionId" from "Transactions" 

      그리고 ALTER VIEW명령어로 column추가 가능.   

  

  REF


======Sqlline 사용한 shell 이용 방법====

   $cd /usr/hdp/current/phoenix-client/bin/

   $./sqlline.py  

  pnix> !tables

  pnix> select * from MY.MY_TABLE


0: jdbc:phoenix:> help

!all                Execute the specified SQL against all the current connections

!autocommit         Set autocommit mode on or off

!batch              Start or execute a batch of statements

!brief              Set verbose mode off

!call               Execute a callable statement

!close              Close the current connection to the database

!closeall           Close all current open connections

!columns            List all the columns for the specified table

!commit             Commit the current transaction (if autocommit is off)

!connect            Open a new connection to the database.

!dbinfo             Give metadata information about the database

!describe           Describe a table

!dropall            Drop all tables in the current database

!exportedkeys       List all the exported keys for the specified table

!go                 Select the current connection

!help               Print a summary of command usage

!history            Display the command history

!importedkeys       List all the imported keys for the specified table

!indexes            List all the indexes for the specified table

!isolation          Set the transaction isolation for this connection

!list               List the current connections

!manual             Display the SQLLine manual

!metadata           Obtain metadata information

!nativesql          Show the native SQL for the specified statement

!outputformat       Set the output format for displaying results

                    (table,vertical,csv,tsv,xmlattrs,xmlelements)

!primarykeys        List all the primary keys for the specified table

!procedures         List all the procedures

!properties         Connect to the database specified in the properties file(s)

!quit               Exits the program

!reconnect          Reconnect to the database

!record             Record all output to the specified file

!rehash             Fetch table and column names for command completion

!rollback           Roll back the current transaction (if autocommit is off)

!run                Run a script from the specified file

!save               Save the current variabes and aliases

!scan               Scan for installed JDBC drivers

!script             Start saving a script to a file

!set                Set a sqlline variable

  => !set maxWitdh 200    :  Terminal 가로 출력 길이 세팅.


!sql                Execute a SQL command
!tables             List all the tables in the database
!typeinfo           Display the type map for the current connection
!verbose            Set verbose mode on


Posted by yongary
,