출처 : https://gist.github.com/aunyks/8f2c2fd51cc17f342737917e1c2582e2

 

ex1.js 돌아는 간다.


const date = require('date-utils');
var dt = new Date();

 


var Block = new function(){
                this.index = 0;
                this.timestamp = dt.clone();
                this.data = "data :  Genesis Block"
                this.previous_hash = "0";
                this.hash = crypto.createHash("sha256").update(this.index + this.timestamp + this.data + this.previous_hash).digest("hex");
};


console.log("index : ", Block.index, "timestamp : ", Block.timestamp, "data : ", Block.data, "previous_hash : ", Block.previous_hash, "hash", Block.hash);

const next_block = async () => {
        try{
        Block.index = Block.index+1;
        Block.timestamp = dt.clone();
        Block.data = "Hey! I'm block " + Block.index;
        Block.previous_hash = Block.hash;
        Block.hash = crypto.createHash("sha256").update(Block.index + Block.timestamp + Block.data + Block.previous_hash).digest("hex");
        }catch (error) { console.log('Task Failure',error);}
}


var num_of_blocks_to_add = 20;

for(var i=0; i<num_of_blocks_to_add; i++){
        next_block();
        console.log("index : ", Block.index, "timestamp : ", Block.timestamp, "data : ", Block.data, "previous_hash : ", Block.previous_hash, "hash", Block.hash);
}
 

 

 

 

실행결과

root@tkpark-VirtualBox:~/project/myapp/routes# nodejs ex1.js
index :  0 timestamp :  2019-01-17T06:14:00.735Z data :  data :  Genesis Block previous_hash :  0 hash 435f39b1283eaaad92378228feb0ff217904cba051828ddbf87eb9049fc269fc
index :  1 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 1 previous_hash :  435f39b1283eaaad92378228feb0ff217904cba051828ddbf87eb9049fc269fc hash ea0b1c93cff5ad20bd1b300f339e557747cf92f9cccf18839069b9b34df40241
index :  2 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 2 previous_hash :  ea0b1c93cff5ad20bd1b300f339e557747cf92f9cccf18839069b9b34df40241 hash 27cd8f270c2d09ad2e7409f50ce9dd29d5141cfc1c62dcc2c189f7f7ad394ed1
index :  3 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 3 previous_hash :  27cd8f270c2d09ad2e7409f50ce9dd29d5141cfc1c62dcc2c189f7f7ad394ed1 hash dd12e07c03dd274850ed7071fe6e3009758c56361fcc6d64ca3befed4f683ab7
index :  4 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 4 previous_hash :  dd12e07c03dd274850ed7071fe6e3009758c56361fcc6d64ca3befed4f683ab7 hash efc128e74d5e32f761d11e63851431c84564b315f1ad2cf96e9b610f43a35a74
index :  5 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 5 previous_hash :  efc128e74d5e32f761d11e63851431c84564b315f1ad2cf96e9b610f43a35a74 hash 3bfb7ea0d0ae3183240976de82c100d7f83ce11a91faa6a2b5c79d4a889b525b
index :  6 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 6 previous_hash :  3bfb7ea0d0ae3183240976de82c100d7f83ce11a91faa6a2b5c79d4a889b525b hash 93e60df16e258ba4e40407f68a13763db2e741129ef15fa25b5d4c5f98d13f29
index :  7 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 7 previous_hash :  93e60df16e258ba4e40407f68a13763db2e741129ef15fa25b5d4c5f98d13f29 hash dc3bd4fb62dfb15ad82e44b3768e4bc03a2085efc66a20f3542d901bf0da535c
index :  8 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 8 previous_hash :  dc3bd4fb62dfb15ad82e44b3768e4bc03a2085efc66a20f3542d901bf0da535c hash 5ac36c5edca409f8d3fe1d7c6323cb6488542d0dfb80390b8211992af9e278dc
index :  9 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 9 previous_hash :  5ac36c5edca409f8d3fe1d7c6323cb6488542d0dfb80390b8211992af9e278dc hash df60da5103bb153495e36d26c5fe101ecc7f445a001ca0ec5010ac1e0ca70bf5
index :  10 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 10 previous_hash :  df60da5103bb153495e36d26c5fe101ecc7f445a001ca0ec5010ac1e0ca70bf5 hash 079808737914421f6fbeaaf20764a23fd984eb1b5384c0d64b127bf9b36b69d8
index :  11 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 11 previous_hash :  079808737914421f6fbeaaf20764a23fd984eb1b5384c0d64b127bf9b36b69d8 hash 38e6a98821aa193e9b24d009fdddadab4565388ef93b4bfbf25d3ddbb6e32623
index :  12 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 12 previous_hash :  38e6a98821aa193e9b24d009fdddadab4565388ef93b4bfbf25d3ddbb6e32623 hash f668b9c2521bfb9f4562557501914c6dcbf7dad2fa84c27437be72536c763023
index :  13 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 13 previous_hash :  f668b9c2521bfb9f4562557501914c6dcbf7dad2fa84c27437be72536c763023 hash 48dc2d11c14ad8dbcdc11908185e435162da6f0f653d52bbec3c92b8471d1660
index :  14 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 14 previous_hash :  48dc2d11c14ad8dbcdc11908185e435162da6f0f653d52bbec3c92b8471d1660 hash e1745d4dd8344bc8bd01aefbf59e2a347b0bd9a743bd5e2331c4707763111862
index :  15 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 15 previous_hash :  e1745d4dd8344bc8bd01aefbf59e2a347b0bd9a743bd5e2331c4707763111862 hash fcd3d0e8fd8eb2b90ec2a913085a32de9978cc4c8eb9365dd6fc98f7b6105967
index :  16 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 16 previous_hash :  fcd3d0e8fd8eb2b90ec2a913085a32de9978cc4c8eb9365dd6fc98f7b6105967 hash c545d471f6fc9fd388868b6d0cfdac607df6348f497a907874e71139d91126e9
index :  17 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 17 previous_hash :  c545d471f6fc9fd388868b6d0cfdac607df6348f497a907874e71139d91126e9 hash 4cae02f8716133366633d2ddb3a9bc87b13cee2898eb650f2a0c21f7e550ddb5
index :  18 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 18 previous_hash :  4cae02f8716133366633d2ddb3a9bc87b13cee2898eb650f2a0c21f7e550ddb5 hash e4aa549a98cf6412a4eea651849ef76165dd2bd5d9fee44ac394a58088d6a066
index :  19 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 19 previous_hash :  e4aa549a98cf6412a4eea651849ef76165dd2bd5d9fee44ac394a58088d6a066 hash 1f21c685f6aec8e4e3c5d985873fd00c57241612c7b12f9283b5324113c8b20b
index :  20 timestamp :  2019-01-17T06:14:00.735Z data :  Hey! I'm block 20 previous_hash :  1f21c685f6aec8e4e3c5d985873fd00c57241612c7b12f9283b5324113c8b20b hash a780596a78f9bf8570903f65c86bc88fc11dfc9c717379f5694953ce1209d637
root@tkpark-VirtualBox:~/project/myapp/routes#
 

 

 

 

 

 

 

 

 

 

 

 

 

블로그 이미지

iesay

,

nodejs + mariadb 연동

시스템 2019. 1. 14. 15:10

출처 : http://kamang-it.tistory.com/entry/NodeJSNodeJS%EC%99%80-MysqlMariaDB%EC%97%B0%EB%8F%99%ED%95%98%EA%B8%B0-expressJS-%EC%83%81%EC%97%90%EC%84%9C-%EA%B0%84%EB%8B%A8%ED%95%9C-%ED%9A%8C%EC%9B%90%EA%B0%80%EC%9E%85%EB%A1%9C%EA%B7%B8%EC%9D%B8%ED%9A%8C%EC%9B%90%ED%83%88%ED%87%B4-%EA%B5%AC%ED%98%84

 

우분투 18

mariadb 환경

root@tkpark-VirtualBox:~/project/myapp/routes# mysql -u tkpark -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 78
Server version: 10.1.34-MariaDB-0ubuntu0.18.04.1 Ubuntu 18.04

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>
 

 

 

 

index.js

module.exports = router;
var router = express.Router();

var mysql = require('mysql');

router.get('/', function (req, res, next) {
    var connection = mysql.createConnection({
        host: 'localhost',
        post: 3306,
        user: 'tkpark',
        password: '패스워드',
        database: 'tkpark'
    });
    connection.connect();
    connection.query('select * from transactionscan', function (err, rows, fields) {
        connection.end();
        if (!err) {
            console.log(rows);
            console.log(fields);
            var result = 'rows : ' + JSON.stringify(rows) + '<br><br>' +
                'fields : ' + JSON.stringify(fields);
            res.send(result);
        } else {
            console.log('query error : ' + err);
            res.send(err);
        }
    });
});


module.exports = router; 

 

실행결과

# yarn start
yarn run v1.12.3
$ node ./bin/www
[ RowDataPacket {
    idx: 1,
    from_address: 'TVcaZYGf94J5K6WkPsfSDVUu5cWreZz1h9',
    to_address: 'TY2HycNQV4qMRZF7TrmTqrAENG59tpsGix',
    amount: 1000000000000000000,
    txid: 'fc3e6e97d5619e186cb4c14ea6326965aa43df85619a6ccd74ee819767104e48' },
  RowDataPacket {
    idx: 2,
    from_address: 'TVcaZYGf94J5K6WkPsfSDVUu5cWreZz1h9',
    to_address: 'TY2HycNQV4qMRZF7TrmTqrAENG59tpsGix',
    amount: 10000000000,
    txid: 'fc3e6e97d5619e186cb4c14ea6326965aa43df85619a6ccd74ee819767104e48' },
  RowDataPacket {
    idx: 3,
    from_address: 'TVcaZYGf94J5K6WkPsfSDVUu5cWreZz1h9',
    to_address: 'TY2HycNQV4qMRZF7TrmTqrAENG59tpsGix',
    amount: 10000000000,
    txid: 'fc3e6e97d5619e186cb4c14ea6326965aa43df85619a6ccd74ee819767104e48' } ]
[ FieldPacket {
    catalog: 'def',
    db: 'tkpark',
    table: 'transactionscan',
    orgTable: 'transactionscan',
    name: 'idx',
    orgName: 'idx',
    charsetNr: 63,
    length: 11,
    type: 3,
    flags: 16899,
    decimals: 0,
    default: undefined,
    zeroFill: false,
    protocol41: true },
  FieldPacket {
    catalog: 'def',
    db: 'tkpark',
    table: 'transactionscan',
    orgTable: 'transactionscan',
    name: 'from_address',
    orgName: 'from_address',
    charsetNr: 33,
    length: 300,
    type: 253,
    flags: 4097,
    decimals: 0,
    default: undefined,
    zeroFill: false,
    protocol41: true },
  FieldPacket {
    catalog: 'def',
    db: 'tkpark',
    table: 'transactionscan',
    orgTable: 'transactionscan',
    name: 'to_address',
    orgName: 'to_address',
    charsetNr: 33,
    length: 300,
    type: 253,
    flags: 4097,
    decimals: 0,
    default: undefined,
    zeroFill: false,
    protocol41: true },
  FieldPacket {
    catalog: 'def',
    db: 'tkpark',
    table: 'transactionscan',
    orgTable: 'transactionscan',
    name: 'amount',
    orgName: 'amount',
    charsetNr: 63,
    length: 20,
    type: 8,
    flags: 4097,
    decimals: 0,
    default: undefined,
    zeroFill: false,
    protocol41: true },
  FieldPacket {
    catalog: 'def',
    db: 'tkpark',
    table: 'transactionscan',
    orgTable: 'transactionscan',
    name: 'txid',
    orgName: 'txid',
    charsetNr: 33,
    length: 450,
    type: 253,
    flags: 4097,
    decimals: 0,
    default: undefined,
    zeroFill: false,
    protocol41: true } ]
GET / 200 69.467 ms - 1770
 

 

 

mariadb모듈로 접근해보았는데 npm 설치하고

생각보다 잘 안붙는다

놀라지말고 위소스대로 잘 붙여 보길 바란다.

 

 

 

 

 

'시스템' 카테고리의 다른 글

pm2  (0) 2019.03.28
nodejs - form submit  (0) 2019.01.22
nodejs json파일 MongDB에 입력  (0) 2018.12.04
nodejs json파일 컨트롤  (0) 2018.12.04
Mongdb 설치 ubuntu 18  (0) 2018.11.30
블로그 이미지

iesay

,

TronScan(제작 완료)

트론 2019. 1. 10. 10:29

참고 : https://github.com/tronscan/tronscan-api

 

이더스캔은 이더스캔 API로 잠깐 깔짝 때보고 회사 업무상 트론을 계속 보게

 

되었는데  트랜젝션 조회 트론스캔을 어떻게 접근해야 될지 고민중이다.

 

지금 현재 트론 상황은  token발행 심볼때문에  몇몇 함수가 막혀 있다.

 

그중에 하나인 tronWeb.trx.getTransactionsRelated  도 지금 사용이 불가능다.

1. full node를 동기화시켜서 DB에 넣을지?

2. 특정 Token에 대한 것만 DB에  넣을지?

 

input /output에 대한 결과를 어떻게 사용자에게 보여주는게 좋을지 판단이 안선다.

 

그래서 우선  트론스캔에 있는 tx를 웹에서 파싱해서 한번 넣어보자...

API가 제공안하니 웹파싱해서 넣는다 해도 큰 무리는 없을것이다.

 

https://tronscan.org/#/transaction/51d1994d5d36693299bba3ed3002ca46849922fd80df0446acbd28609948d09d

index.js

var express = require('express');
var router = express.Router();
const TronWeb = require('tronweb');
const fullNode = 'https://api.shasta.trongrid.io';
const solidityNode = 'https://api.shasta.trongrid.io';
const eventServer = 'https://api.shasta.trongrid.io/';
var privateKey = '123';

var mysql = require('mysql');
var connection = mysql.createConnection({
        host: 'localhost',
        post: 3306,
        user: 'tkpark',
        password: '1234',
        database: 'tkpark'
    });
const tronWeb = new TronWeb(
fullNode,
solidityNode,
eventServer,
privateKey
  );
tronWeb.setDefaultBlock('latest');
const nodes = tronWeb.isConnected();
const connected = !Object.entries(nodes).map(([ name,   connected]) => {
        if (!connected)
                  console.error(`Error: $ {name}is not connected`);
        return connected;
}).includes(false);
if (!connected)
      res.json( {'result':'connect fail'})
router.get('/createAccount/',function(req,res,next) {
        const account = tronWeb.createAccount();
        account.then(function (account) { const isValid = tronWeb.isAddress(account.address['hex']);
                console.log('- Private Key:',   account.privateKey);
                console.log('- Base58:',        account.address.base58);
                console.log('- Valid: ',        isValid,        '\n');
                account.isValid = isValid;
                res.json( {'result':account.privateKey, '- Base58': account.address.base58});
        });
});
router.get('/getBalance/:Address',function(req,res,next) {
        const app = async () => {
                try {
                        const Add = req.params.Address;
                        const gBalance = await tronWeb.trx.getBalance(Add);
                        const gBandwidth = await tronWeb.trx.getBandwidth(Add);
                        console.log("getBalance : ", gBalance);
                        console.log("getBandwidth : ", gBandwidth);
                        console.log("   ", Add);
                        res.json( { "getBalance  ": gBalance, "getBandwidth": gBandwidth, "123": Add})
                }catch (error) { console.log('Task Failure',error);
                }
        };
        app();
});


router.get('/transactionview',function(req,res,next) {
                try{
                        var Address = req.query.Address;
                        var select_sql = "select *, \"send\" from transactionscan where from_address=? union all select *, \"receive\" from transactionscan where to_address=? order by idx desc;";
                        connection.query(select_sql, [Address, Address], function (err, rows, fields) {
                        if (!err) {
                                var resultdown = JSON.stringify(rows);
                                var TRList = JSON.parse(resultdown);
                                var Result_data = [];
                                for(var i=0; i<TRList.length; i++){
                                        var TR=TRList[i];
                                        var info = {
                                                send: TR.send,
                                                idx: TR.idx,
                                                from_address: TR.from_address,
                                                to_address: TR.to_address,
                                                amount: TR.amount,
                                                txid: "https://shasta.tronscan.org/#/transaction/"+ TR.txid
                                        };
                                        Result_data.push(info);
                                }
                                var result_end={
                                        count: Result_data.length, // count
                                        Result_data: Result_data
                                };
                                console.log(result_end);
                                res.send(result_end);
                                } else {
                                console.log('query error : ' + err);
                                }
                        });
                }catch (error) { console.log('Task Failure',error);
                }

});
router.get('/sendToken',function(req,res,next) {
        const app = async () => {
                try {
                        const gPK = req.query.PK;
                        privateKey = tronWeb.setPrivateKey(gPK);
                        const gvalue = req.query.value;
                        const gsendAddress = await tronWeb.address.fromPrivateKey(gPK);
                        const gtoAddress = req.query.toAddress;
                        var txid = "";
                        var result = "";
                        var insert_sql = "insert into transactionscan (from_address, to_address, amount, txid) values (?, ?, ?, ?)";
                        var select_sql = "select * from transactionscan where txid=?";
                        /*
                        console.log("gPK : ", gPK);
                        console.log("gvalue : ", gvalue);
                        console.log("gsendAddres :", gsendAddress);
                        console.log("gtoAddress : ", gtoAddress);
                        */
                       sendTransaction = await tronWeb.transactionBuilder.sendToken(gtoAddress, gvalue, "1002003", gsendAddress);

                        const signedTransaction = await tronWeb.trx.sign(sendTransaction);
                        const sendRaw = await tronWeb.trx.sendRawTransaction(signedTransaction);
                        result = JSON.stringify(sendRaw, null, 2);
                        var TRList = JSON.parse(result);
                        var txid = TRList.transaction.txID;
                        /*
                        console.log('- Transaction:\n' + TRList.transaction.txID);
                        res.json( { "gPK  ": gPK, "gvalue  ": gvalue, "gsendAddres ": gsendAddress, "gtoAddress": gtoAddress,'- Transaction:n': TRList.transaction.txID, "Transaction\n": JSON.stringify(sendRaw, null, 2)});
                        */

 var params = [gsendAddress, gtoAddress, gvalue, txid];
                        connection.query(insert_sql, params, function (err, rows, fields) {
                        if (!err) {
                                console.log('query error : ' + err);
                                //res.send(err);
                         }
                        });
                        connection.query(select_sql, txid, function (err, rows, fields) {
                        if (!err) {
                                console.log(rows);
                                var resultdown = 'rows : ' + JSON.stringify(rows);

                                res.send(resultdown);
                                } else {
                                console.log('query error : ' + err);
                                }
                        });
                        }catch (error) { console.log('Task Failure',error);
                }
        };
        app();
});

 

module.exports = router;

 

실행결과

 

계좌신청
http://192.168.0.118:3000/createAccount/

 

잔액조회 지갑주소
http://192.168.0.118:3000/getBalance/TS4AYYxrF38EA3fDw92mMWbWdFWRJ4VKih
http://192.168.0.118:3000/getBalance/TMDBC4DoS1yQCjBgnPBJWnfTZN9rAKBUHc

 

송금
http://192.168.0.118:3000/sendToken?PK=@@@@@&value=@@@@&toAddress=@@@@@@@@@@

송금시 API가 변경되어서 꼭 tronWeb.setPrivateKey로 다시 세팅하고

받는 사람 주소를 인자에 넣어야 된다.

 tronWeb.transactionBuilder.sendTrx(gtoAddress, gvalue, gsendAddress);

 

 

트렌젝선 조회
http://192.168.0.118:3000/transactionjson?Address=TS4AYYxrF38EA3fDw92mMWbWdFWRJ4VKih

 

 

Mysql DB스키마

CREATE TABLE `transactionscan` (
  `idx` int(11) NOT NULL AUTO_INCREMENT,
  `from_address` varchar(100) NOT NULL COMMENT '보내는 사람 주소',
  `to_address` varchar(100) NOT NULL COMMENT '받는 사람  주소',
  `amount` bigint(20) NOT NULL COMMENT '양',
  `txid` varchar(150) NOT NULL COMMENT '트랜젝션 id',
  `regdate` datetime default current_timestamp,
  PRIMARY KEY (`idx`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='트랜젝션 조회 테이블';

 

MariaDB [tkpark]> desc transactionscan;
+--------------+--------------+------+-----+-------------------+----------------+
| Field        | Type         | Null | Key | Default           | Extra          |
+--------------+--------------+------+-----+-------------------+----------------+
| idx          | int(11)      | NO   | PRI | NULL              | auto_increment |
| from_address | varchar(100) | NO   |     | NULL              |                |
| to_address   | varchar(100) | NO   |     | NULL              |                |
| amount       | bigint(20)   | NO   |     | NULL              |                |
| txid         | varchar(150) | NO   |     | NULL              |                |
| regdate      | datetime     | YES  |     | CURRENT_TIMESTAMP |                |
+--------------+--------------+------+-----+-------------------+----------------+

 

 

 

select *, \"send\" from transactionscan where from_address=? union all select *, \"receive\" from transactionscan where to_address=? order by idx desc

해당 쿼리에 대한 결과다.

 

쿼리구문은 당연히 ?가 들어가는 prepared statement

sql 인젝션 방지까지 된다.

 

마지막 부분 조회할때는 지갑 A, B주소로  서로 송금 해보고

A주소로 조회시 send,

파란색 주소를  트랜젝션 조회하면  send한부분 recieve한 부분 보여진다.

빨간색 주소를 트랜잭션 조회해도  send한부분 recieve한 부분 보여진다.

 

트랜젝션 조회시 tronscan 원본에도 조회 되도록

https://shasta.tronscan.org/#/transaction/
4533bb973d7cd4dccc1805b0e43e2a7b341f0e02d23ab8febbe58b994fb8ee73

링크를 함께 뿌려주고 있다.

 

코드 좀 정리 해서 github 라는놈도 한번 써봐야곘다.

회사에서 필요하는 만큼 빨리 잘 만들었다.

 

Dapp 개발하면서 느끼지만 메인넷은 이더리움과 비트코인과 같이

글로벌한 천재들이 있던지

아니면 트론처럼 직원이 많아야 된다.

web3.js나 tronweb이나 API를 유지보수해야될 인력도 어마 어마하게

필요하기 때문이다.

 

 

 

 

 

블로그 이미지

iesay

,