[nodejs] 스팀 노드 모니터링 라이브러리

in #kr6 years ago

사용방법

  • 단건 [ 'comment' ] 이렇게 하면 글, 댓글 모니터링
  • 배열로 [ 'comment', 'vote' ] 이렇게 하면 글, 댓글, 보팅 모니터링
  • 아래 참조만 하시면 됩니다.
  • 자세한 설명은 귀차니즘으로 생략 ㅜㅜ
  • Promise 가 역시 짱인거 같네요 후훗 chaing is great !

활용

  • 정말 무긍 무진하게 활용이 가능 합니다. 후후
  • 좀만 손질하면 web에서도 사용가능하죠

사용예시

const wmonitor = require('./wmonitor');

wmonitor.on(['comment'], (data)=>{
    console.log(data);
});

wmonitor.js

const steem = require('steem');

const DEF_SLEEP_SEC = 1000 * 3;

const fn = {};

/*
* 최신 블록 번호를 STEEM 노드에서 가져온다
* @param isHead 헤드블록인지 여부
* @return 블록번호
*/
fn.get_last_block_number = async (isHead=true) => {
    return steem.api.getDynamicGlobalPropertiesAsync()
    .then(x=>isHead?x.head_block_number:x.last_irreversible_block_num)
    .catch(err=>{error:err});
}

/*
* 범위 내의 블록 정보를 반환한다
* @param sblock 시작 블록번호
* @param eblock 종료 블록번호
* @return 블록정보
*/
fn.get_blocks = async (sblock, eblock) => {

    if(sblock && eblock){
        let list = [];
        for(let i=sblock;i<=eblock;i++){
            list.push(steem.api.getBlockAsync(i));
        }

        // 단건, 다건 구분
        let res = await Promise.all(list);
        if(!Array.isArray(res)){
            return Promise.resolve( [res] );
        }
        return res;

    }else if(sblock){
        // 단건
        return [await steem.api.getBlockAsync(sblock)];
    }else{
        // not matched
        return Promise.reject({error:`${sblock} is empty`});
    }
}

/*
* 블록 정보에서 거래 정보를 추출한다 
* @param blocks 블록정보 
* @return 거래정보 
*/
fn.get_trans_from_block = async (blocks) => {

    let items = [];

    if(!blocks || !Array.isArray(blocks) ){
        return Promise.reject({error:`block is empty or not iterable`});
    }

    for(let b of blocks){
        if(b && b.transactions){
            for(let t of b.transactions){
                if(t && t.operations){
                    for(let o of t.operations){
                        let item = {};
                        item.timestamp = b.timestamp;
                        item.block_num = t.block_num;
                        item.transaction_num = t.transaction_num;
                        item.transaction_id = t.transaction_id;
                        item.operation = o;
                        items.push(item);
                    }
                }
            }
        }
    }
    return Promise.resolve(items);
}

/*
* 커맨드 목록 기준으로 operations를 필터링 한다
* @param ops 오퍼레이션 목록
* @cmds 커맨드목록
* @return 필터링된 커맨드 목록
*/
fn.get_filtered_by_command = async (ops, cmds) => {

    if(!Array.isArray(cmds)){
        cmds = [cmds];
    }

    ops = ops.filter(x=>cmds.includes(x.operation[0]));

    let items = [];
    for(let o of ops){
        items.push({
            timestamp : o.timestamp,
            block_num : o.block_num,
            transaction_num : o.transaction_num,
            transaction_id : o.transaction_id,
            cmd : o.operation[0],
            operation : o.operation[1]
        });
    }
    return Promise.resolve(items);
}

/*
* 모니터링을 수행한다
* @param cmds 모니터링할 커맨드 목록
* @param cb 수신 결과를 모니터링할 콜백
* @param sblock 모니터링을 시작할 블록넘버
*/
fn.on = async (cmds, cb, sblock)=>{

    let eblock;
    try{
        eblock = await fn.get_last_block_number();
    }catch(e){
        // 일반적으로 네트워크 오류임 / 다시 시작
        return fn.on(cmds, cb, sblock);
    }

    // 이미 읽어들인 정보인 경우임
    if(sblock && sblock>=eblock){
        return fn.on(cmds, cb, sblock);
    }

    // 시작 블록 미설정한 경우, 마지막 블록으로 설정
    if(!sblock){
        sblock = eblock;
    }
    
    // 시작 => 마지막 블록 번호 얻기  => 거래정보 추출 => 커맨드 명 기준 필터링 => 결과 알려주기(콜백) , 다시 첨부터 ...
    fn.get_blocks(sblock, eblock)
    .then(res=>fn.get_trans_from_block(res))
    .then(res=>fn.get_filtered_by_command(res, cmds))
    .then(res=>{
        // 결과를 콜백으로 알려준다 
        cb(res);

        // 다음 결과를 모니터링 수행
        setTimeout(()=>{
            // 다음에 읽어들일 블록 정보 update
            sblock = eblock + 1;
            return fn.on(cmds, cb, sblock);
        }, DEF_SLEEP_SEC );
    });
}

module.exports = fn;

맺음말

  • 오후 10시인데 아직도 퇴근 못함 ㅜㅜ
Sort:  

얼른 퇴근 하셔야죠. ㅎㅎ

넹 ㅜㅜ

곰돌이가 @jisoooh0202님의 소중한 댓글에 $0.010을 보팅해서 $0.013을 살려드리고 가요. 곰돌이가 지금까지 총 1831번 $24.149을 보팅해서 $22.647을 구했습니다. @gomdory 곰도뤼~

또 감사감사 :)

맺음말이 슬픕니다..

곰돌이가 @glory7님의 소중한 댓글에 $0.011을 보팅해서 $0.012을 살려드리고 가요. 곰돌이가 지금까지 총 1848번 $24.356을 보팅해서 $22.831을 구했습니다. @gomdory 곰도뤼~

정말 피곤하시겠어요.

피곤하네요 ㅜㅜ 오늘도 늦잠자고 좀전에 출근

악순환즁...

곰돌이가 @dokebi님의 소중한 댓글에 $0.010을 보팅해서 $0.013을 살려드리고 가요. 곰돌이가 지금까지 총 1839번 $24.266을 보팅해서 $22.714을 구했습니다. @gomdory 곰도뤼~

화..화이팅!!
이거 한번 따라 해보고 싶은 예제네요!!
감사합니다

쓸만합니다 ㅋㅋ

곰돌이가 @ayogom님의 소중한 댓글에 $0.010을 보팅해서 $0.013을 살려드리고 가요. 곰돌이가 지금까지 총 1840번 $24.276을 보팅해서 $22.727을 구했습니다. @gomdory 곰도뤼~

원사마님은 천재맞습니다!!!

설마요 ? ㅋ

곰돌이가 @ioioioioi님의 소중한 댓글에 $0.010을 보팅해서 $0.013을 살려드리고 가요. 곰돌이가 지금까지 총 1842번 $24.294을 보팅해서 $22.755을 구했습니다. @gomdory 곰도뤼~

This post has been found valuable and upvoted by El surtidor


This post got an extra 5 power for following us

Follow @elsurtidor to get biggest votes in your next posts

Congratulations @wonsama! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You got more than 1500 replies. Your next target is to reach 1750 replies.

Click here to view your Board of Honor
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard:

Saint Nicholas challenge for good boys and girls

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @wonsama! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You received more than 15000 upvotes. Your next target is to reach 20000 upvotes.

Click here to view your Board of Honor
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard:

Saint Nicholas challenge for good boys and girls

Support SteemitBoard's project! Vote for its witness and get one more award!

Hi @wonsama!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your UA account score is currently 3.707 which ranks you at #5097 across all Steem accounts.
Your rank has not changed in the last three days.

In our last Algorithmic Curation Round, consisting of 275 contributions, your post is ranked at #130.

Evaluation of your UA score:
  • You're on the right track, try to gather more followers.
  • The readers like your work!
  • Good user engagement!

Feel free to join our @steem-ua Discord server

지금 하고 있는 작업 끝나면 node.js 도 제대로 공부해 보고 싶네요.

간간히 책 보고 있는데 완전 재미난 기술이더군요.

왜 진작에 몰랐을까..

원사마사마님 덕분에 도움 많이 될 것 같네요~

Coin Marketplace

STEEM 0.20
TRX 0.15
JST 0.029
BTC 63483.25
ETH 2601.63
USDT 1.00
SBD 2.81