以太坊web3.sendRawTransaction离线签名交易
2019-12-26 本文已影响0人
风吹而散
工作中需要复现短地址攻击和thedao重入攻击,重入攻击可以直接通过eth.sendTransaction和remix来发送交易,但是短地址攻击由于钱包和remix这些都对input做了长度检测,无法通过这些方式来复现,只能通过发离线签名交易来实现。
1.环境依赖:nodejs , keythereum , ethereumjs-common , ethereumjs-tx 。
npm install keythereum
npm install ethereumjs-common
npm insall ethereumjs-tx
2.进入Node控制台,获取相应账户私钥。
获得需要发送交易账户的私钥
var keyth=require('keythereum');
//这里的privateChain1是我的私链路径
var keyobj=keyth.importFromFile('0x53698724b12fa829619e0742933a886a415a7c61','/home/ch/gopath/src/github.com/ethereum/go-ethereum/build/bin/privateChain1');
var pkey=keyth.recover("1",keyobj)
console.log(pkey.toString('hex'))
![](https://img.haomeiwen.com/i11575032/9164635c6bdc0917.png)
3.签名交易,进入Node,这里注意nonce问题,需要Nonce是实际可执行的nonce,Nonce不对会发送交易失败,关于如何获取input data百度比较多就不详述了。
const privateKey = Buffer.from(
'975776452a74921c0fb79fb2febc340a7de9a665f04fe6d2adaaca33d838fdf0',
'hex',
)
const Common=require('ethereumjs-common').default
const customCommon = Common.forCustomChain(
'mainnet',
{
name: 'my-network',
networkId: 5,
chainId: 5,
},
'petersburg',
)
const txParams={
nonce:'0x3b',
gasPrice:'0x05',
gasLimit:'0x4ffff',
from: '0x53698724b12fa829619e0742933a886a415a7c61',
to:'0x16fe2bf1d3b1ccdbafe5233f281940ccab5448ba',
value:'0x00',
data:'0xa9059cbb000000000000000000000000b7990a950b1d0280107485651e7dd130a460365000000000000000000000000000000000000000000000000000000000000001',
chainId:'5'
}
const EthereumTx = require('ethereumjs-tx').Transaction
const tx = new EthereumTx(txParams, {common:customCommon})
tx.sign(privateKey)
const serializedTx = tx.serialize()
console.log('0x'+serializedTx.toString('hex'))
![](https://img.haomeiwen.com/i11575032/ec383d42f0758243.png)
4.遇到的坑,百度出来的步骤是有问题的或者过时了,当时是参考的这篇文章,https://www.freebuf.com/articles/blockchain-articles/199903.html
,在控制台通过eth.sendRawTransaction发送签名好的交易,我遇到了这个错误 ** sendRawTransaction invalid sender **
![](https://img.haomeiwen.com/i11575032/6ff346bd1e59cd82.png)
这个文章少了一个步骤。出现这个问题的最根本原因是没有设置chainId和networkId,这两个数值需要保证跟你的私链一致,还有Networkid不等于chainId,具体看你配置。百度这个问题根本找不到,通过谷歌Github上很多都说是chainId的问题,其实也包括Networkid,都需要保证一致,如果不设置的话默认是签名到公网交易,到私链上会报上面这个错误。通过参考 https://github.com/ethereumjs/ethereumjs-tx ,官方的定制方法,需要引入ethereumjs-common包来进行配置。按照上面的步骤来就可以成功.