采用web3.js将数据写入到区块链中

let Web3 = require("web3");
let fs = require("fs");
let web3 = new Web3();
web3.setProvider(new Web3.providers.HttpProvider("http://192.168.1.10:8545"));

let log = {
    time:(new Date).getTime(),
    type:"error",
    msg:"数据库连接失败"
};
let str = JSON.stringify(log);
let data = Buffer.from(str).toString('hex');
data = '0x'+data;
console.log(data);

//将数据写入到交易中
let coinbase = "0x8a1C505f1ff14045c03622E9ab82EB19c730cef3";
let user1 = "0xb4B6338977078f1c355ee394D67D6DFE5C24dad8";
web3.personal.unlockAccount(coinbase, "coinbase");
let address = web3.eth.sendTransaction({
    from:coinbase,
    to:user1,
    value:'0x00',
    data:data
});

//从交易地址获取数据
let transaction = web3.eth.getTransaction(address);
let inputData = transaction.input;
let res_str = Buffer.from(inputData.replace('0x',''),'hex').toString();
let res_json = JSON.parse(res_str);
console.log(transaction);
console.log(res_json);

console log:

0x7b2274696d65223a313531333135363433363137392c2274797065223a226572726f72222c226d7367223a22e695b0e68daee5ba93e8bf9ee68ea5e5a4b1e8b4a5227d
{ blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000',
  blockNumber: null,
  from: '0x8a1c505f1ff14045c03622e9ab82eb19c730cef3',
  gas: 90000,
  gasPrice: { [String: '18000000000'] s: 1, e: 10, c: [ 18000000000 ] },
  hash: '0x3149578fbb8cf75f264fc87426b7bfa2a89256763fe5194ccad8b724a0325470',
  input: '0x7b2274696d65223a313531333135363433363137392c2274797065223a226572726f72222c226d7367223a22e695b0e68daee5ba93e8bf9ee68ea5e5a4b1e8b4a5227d',
  nonce: 57,
  to: '0xb4b6338977078f1c355ee394d67d6dfe5c24dad8',
  transactionIndex: 0,
  value: { [String: '0'] s: 1, e: 0, c: [ 0 ] },
  v: '0x26',
  r: '0x742335f7b649c554a35baf624fe90c8e3fa3c9cfc116cfe858af420dc893359a',
  s: '0x20a63d760ab574736aaed4799f2a15bc727a988b4d41ee279e3b753b1c1f3913' }
{ time: 1513156436179, type: 'error', msg: '数据库连接失败' }

blockHash和blockNumber为空值是因为交易还没有被矿工打包生成区块,过一会再通过交易地址查询就能看到具体的区块信息。

发送交易:https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethsendtransaction

查询交易:https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethgettransaction

猜你喜欢

转载自blog.csdn.net/koastal/article/details/78794275
今日推荐