ethereum

// JavaScript source code
'use strict';
const Web3 = require('web3');
const web3 = new Web3();
const con = require('./mysqlConnection');
const ethereumUri = 'http://127.0.0.1:8545';
web3.setProvider(new web3.providers.HttpProvider(ethereumUri));
//livenet
//var contract = web3.eth.contract([{"constant":true,"inputs":[{"name":"","type":"bytes32"}],"name":"map","outputs":[{"name":"volume","type":"uint256"},{"name":"depositm","type":"uint256"},{"name":"amount","type":"uint256"},{"name":"providerfee","type":"uint256"},{"name":"intermediaryfee","type":"uint256"},{"name":"provider","type":"address"},{"name":"intermediary","type":"address"},{"name":"user","type":"address"},{"name":"contractId","type":"bytes32"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_contractId","type":"bytes32"}],"name":"refund","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_volume","type":"uint256"},{"name":"_contractId","type":"bytes32"},{"name":"_provider","type":"address"},{"name":"_intermediary","type":"address"},{"name":"_user","type":"address"}],"name":"set","outputs":[],"payable":true,"type":"function"},{"constant":false,"inputs":[],"name":"deposit","outputs":[],"payable":true,"type":"function"},{"constant":false,"inputs":[],"name":"refundowner","outputs":[],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"}]).at("0x792C040f5182B67e16eB204A0b0afE48d64C462b")
//private
var contract = web3.eth.contract([{"constant":true,"inputs":[{"name":"","type":"bytes32"}],"name":"map","outputs":[{"name":"volume","type":"uint256"},{"name":"depositm","type":"uint256"},{"name":"amount","type":"uint256"},{"name":"providerfee","type":"uint256"},{"name":"intermediaryfee","type":"uint256"},{"name":"provider","type":"address"},{"name":"intermediary","type":"address"},{"name":"user","type":"address"},{"name":"contractId","type":"bytes32"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_contractId","type":"bytes32"}],"name":"refund","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"deposit","outputs":[],"payable":true,"type":"function"},{"constant":false,"inputs":[{"name":"_volume","type":"uint256"},{"name":"_provider","type":"address"},{"name":"_intermediary","type":"address"},{"name":"_user","type":"address"},{"name":"_contractId","type":"bytes32"}],"name":"set","outputs":[],"payable":true,"type":"function"},{"constant":false,"inputs":[],"name":"refundowner","outputs":[],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"}]).at("0xbc1952044aa2446d8d0dae6855e380bfe05e4a75")
const tableName = "GlobalContractTable";
var state;
var pw="cisco123";
var apply_id;
var contract_period;
isConnected();
infoInput();
var contract_id_sendTransaction2 =[];
var sendTransaction;
var refund;
function isConnected() {
    if ( !web3.isConnected() ){
        console.log('unable to connect to ethereum node at ' + ethereumUri);
    } else {
        //console.log('connected to ehterum node at ' + ethereumUri);
    }
}

function infoInput() {

var contract_id_expiration2 =[];
var contract_id_sendTransaction1 =[];
var sendTransaction1 = [];
var interval = setInterval(function() {

var expiration2 = "SELECT * FROM GlobalContractTable where state = 'expiration2'";
    
con.query(expiration2, function (err, result, fields) {
//console.log("check...");
if (result == "") {
    console.log("no data available!");
    contract_id_expiration2 = [];
    contract_id_sendTransaction1 =[];
    sendTransaction1 = [];
    return;
} else {

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

        var contract_id = JSON.stringify(result[i].contract_id).replace(/"/g, "");
        var up_volume = JSON.stringify(result[i].up_volume);
        var down_volume = JSON.stringify(result[i].down_volume);
        var volume = Number(up_volume) + Number(down_volume);

        if (sendTransaction1.indexOf(contract_id) >= 0) {
            
            if (contract_id_sendTransaction1.indexOf(contract_id) >= 0) {

                if (contract_id_sendTransaction2.indexOf(contract_id) >= 0) {
                    continue;
                } else {
                let getTransaction = web3.eth.getTransaction(refund);
                let blockNum = getTransaction.blockNumber;
                    
                    if ( blockNum != null ) {
                        contractFromBc(result,i);
                    }
                }
                
            } else {

                let getTransaction = web3.eth.getTransaction(sendTransaction);
                let blockNum = getTransaction.blockNumber;
                
                if ( blockNum != null ) {;
                    console.log("expired");
                    console.log("contract_id:" + contract_id);
                    var map = contract.map(contract_id);
                    console.log("map:" + map);
                    
                    if ( web3.personal.unlockAccount(web3.eth.accounts[0], pw) ) {
                        var estimateGas = contract.refund.estimateGas(contract_id,{from :web3.eth.accounts[0]});
                        console.log("estimateGas:" + estimateGas);
                        refund = contract.refund(contract_id,{from :web3.eth.accounts[0], gas:estimateGas ,gasLimit:estimateGas});
                        console.log("refund:" + refund);
                        contract_id_sendTransaction1.push(contract_id);
                    } else {
                        console.log('unlock failed');
                    }
                }
            }
        } 
        if (contract_id_expiration2.indexOf(contract_id) >= 0) {
            continue;
        } else {
        if (err) throw err;
            contract_id = JSON.stringify(result[i].contract_id).replace(/"/g, "");
            contract_id_expiration2.push(contract_id);
            //console.log("contract_id_expiration2:"+contract_id_expiration2);
            
                var sql2 = "select own.eth_public as owner_address, usr.eth_public as user_address, usr.password as user_pw, off.contract_margin as amount,off.up_line_price as up,off.down_line_price as down from GlobalContractTable as con ";
                sql2 += "inner join GlobalApplyTable as app ON con.apply_id = app.apply_id ";
                sql2 += "inner join GlobalOfferTable as off ON app.offer_id = off.offer_id ";
                sql2 += "inner join LocalOwnerTable as own ON off.owner_id = own.owner_id ";
                sql2 += "inner join LocalUserTable as usr ON app.user_id = usr.user_id ";
                sql2 += "where con.contract_id = '" + contract_id + "' ";
                
                    con.query(sql2, function (err, res, fields) {
                    if (err) throw err;
                    if (res == "") {
                        console.log("no user or owner!");
                        return;
                    }
                    console.log("get eth_public:\n"+sql2);
                    var provider = JSON.stringify("0x"+res[0].owner_address).replace(/"/g, "");
                    console.log("provider:"+provider);
                    var user = JSON.stringify("0x"+res[0].user_address).replace(/"/g, "");
                    console.log("user:"+user);
                    var user_pw = JSON.stringify(res[0].user_pw).replace(/"/g, "");
                    console.log("user_pw:"+user_pw);
                    var amount = JSON.stringify(res[0].amount).replace(/"/g, "");
                    console.log("amount:"+amount);
                    //livenet
                    //var intermediary = "0x7d80846c65e37a09eef7bd9c4abfe94ff9611e39".replace(/"/g, "");
                    var intermediary = "0x4fd8fbfa869f7a7d39cea684b92323d217fedf65".replace(/"/g, "");
                    console.log("intermediary:"+intermediary);

                    if ( web3.personal.unlockAccount(user, user_pw) ) {
                        var estimateGas = contract.set.estimateGas(volume, provider, intermediary, user, contract_id, {from :user, value: web3.toWei(amount, "ether")});
                        console.log("estimateGas:" + estimateGas);
                        sendTransaction = contract.set(volume, provider, intermediary, user, contract_id, {from :user, value: web3.toWei(amount, "ether"), gas:210000});
                        console.log("sendTransaction:" + sendTransaction);
                        sendTransaction1 = contract_id;
                    } else {
                        console.log('unlock failed');
                    }
                });

                }
            }

        }
});
}, 10000);

}

function contractFromBc(result,i) {

        var contract_id = JSON.stringify(result[i].contract_id).replace(/"/g, "");
        console.log("contract_id:"+contract_id);
        contract_id_sendTransaction2.push(contract_id);
        let sequence_no = JSON.stringify(result[i].sequence_no);
        console.log("sequence_no:"+sequence_no);
        
        var apply_id = JSON.stringify(result[i].apply_id).replace(/"/g, "");
        console.log("apply_id:"+apply_id);
        
        let nonce = JSON.stringify(result[i].nonce);//.replace(/"/g, "");
        console.log("nonce:"+nonce);
        
        let user_sign = JSON.stringify(result[i].user_sign).replace(/"/g, "");
        console.log("user_sign:"+user_sign);
        
        let owner_sign = JSON.stringify(result[i].owner_sign).replace(/"/g, "");
        console.log("owner_sign:"+owner_sign);
        
        let state = "expired";
        console.log("state:"+state);
        
        let contract_sign = JSON.stringify(result[i].contract_sign).replace(/"/g, "");
        console.log("contract_sign:"+contract_sign);
        
        let contract_start_time = formatTime(); 
        console.log("contract_start_time:"+contract_start_time);
        
        let contract_end_time = formatTime();
        //let contract_end_time = contract_start_time + ( 60 );
        console.log("contract_end_time:"+contract_end_time);
        
        let up_volume = JSON.stringify(result[i].up_volume).replace(/"/g, "");
        console.log("up_volume:"+up_volume);
        
        let down_volume = JSON.stringify(result[i].down_volume).replace(/"/g, "");
        console.log("down_volume:"+down_volume);
        
        let owner_review = JSON.stringify(result[i].owner_review).replace(/"/g, "");
        console.log("owner_review:"+owner_review);
        
        let user_review = JSON.stringify(result[i].user_review).replace(/"/g, "");
        console.log("user_review:"+user_review);
        
        let identify = "shinkawasaki3F";
        let tbl_name = tableName;

        let setData = web3.fromAscii(identify + '@' + tbl_name + '@' + contract_id + '@' + sequence_no + '@' + apply_id + '@' + nonce + '@' + user_sign+ '@' + owner_sign + '@' + state + '@' + contract_sign + '@' + contract_start_time + '@' + contract_end_time + '@' + up_volume + '@' + down_volume + '@' + owner_review + '@' + user_review);

    if ( web3.personal.unlockAccount(web3.eth.accounts[0], pw) ) {
        var sendTransaction = web3.eth.sendTransaction({from :web3.eth.accounts[0], to :web3.eth.accounts[0], data:setData, gas:"0x11CF8", gasLimit:"0x11CF8"});
        console.log('sendTransaction3:'+sendTransaction);
    } else {
        console.log('unlock failed');
    }

}


function formatTimestamp(ts) {

    let d = new Date( ts * 1000 );
    let year  = d.getFullYear();
    let month = d.getMonth() + 1;
    let day  = d.getDate();
    let hour = ( d.getHours()   < 10 ) ? '0' + d.getHours()   : d.getHours();
    let min  = ( d.getMinutes() < 10 ) ? '0' + d.getMinutes() : d.getMinutes();
    let sec   = ( d.getSeconds() < 10 ) ? '0' + d.getSeconds() : d.getSeconds();
    let str = year + '/' + month + '/' + day + ' ' + hour + ':' + min + ':' + sec;
    return str;
}


function formatTime(dt) {

    var date = new Date(dt) ;
    var a = date.getTime() ;
    console.log("a:"+a);
    var b = Math.floor( a / 1000 ) ;
    
    return b;
}

//timestamp�ɕϊ�
function formatTime() {

    var date = new Date() ;
    var a = date.getTime() ;
    var b = Math.floor( a / 1000 ) ;
    
    return b;
}