将已签名的交易发送给Ropsten或Truffle与Trezor(硬件钱包)开发网络

时间:2018-05-30 04:09:06

标签: ethereum web3js truffle trezor

我尝试将 web3js Trezor 集成到 truffle 开发网络或使用 ropsten测试网络

我们的想法是使用硬件钱包签署交易,然后使用web3js发送原始交易

我得知我们没有平衡来进行交易,可能是因为web3js没有使用10个松露帐户中的一个并使用不在我本地网络中的trezor地址 ..

在ropsten上我有一些醚,我得到了#34;无效的地址"

有没有办法使用web3js将已签名的交易(使用trezor)发送到松露开发网络?我的意思是,有没有办法将trezor地址包含在松露网络中?

松露的情况在这里详细解释,但问题可以推广到" 有没有办法将硬件钱包纳入松露开发网络?" :https://github.com/trufflesuite/truffle/issues/973

使用ropsten我已经设法发送一个事务并在回调中接收一个事务哈希,但是如果我们查询该事务,我们得到该事务不存在..那么......这怎么可能?

我也试过将合同部署到Ropsten,现在我得到了#34;无效的地址"在调用智能合约功能时。也许签名功能错了?有人可以将Trezor交易登录与web3js集成吗?

你们看到我们所遵循的签名和发送过程中有什么问题吗? R,V和S参数处理可能有问题  ..

另一个重要的事情是我使用https://github.com/ethereumjs/ethereumjs-tx来创建原始交易

在web3js,truffle和trezzor中发布的问题可以提供更多信息:

亲切的问候

 trezorLogin = async()=> {
        let trezor=  await this.getTrezor();

        // site icon, optional. at least 48x48px
        let hosticon = 'https://doc.satoshilabs.com/trezor-apps/_images/copay_logo.png';
        // server-side generated and randomized challenges
        let challenge_hidden = '';
        let challenge_visual = '';
        //use anonimous functions on callback otherwise returns cross origin errors
        trezor.requestLogin(hosticon, challenge_hidden, challenge_visual, function (result){
            if (result.success) {
                console.log('Public key:', result.public_key); // pubkey in hex
                console.log('Signature:', result.signature); // signature in hex
                console.log('Version 2:', result.version === 2); // version field
                console.log(result);
            }else {
                console.error('Error:', result.error);
            }
        });}


    trezorSignTx= async(transaction)=> {
        let trezor=  await this.getTrezor();
        // spend one change output
        let address_n = "m/44'/60'/0'/0/0"
        // let address_n = [44 | 0x80000000,
        //                  60 | 0x80000000,
        //                  0  | 0x80000000 ,
        //                  0 ]; // same, in raw form
        let nonce = transaction.nonce.substring(2); // note - it is hex, not number!!!
        let gas_price = transaction.gasPrice.substring(2);
        let gas_limit = transaction.gasLimit.substring(2);
        let to = transaction.to.substring(2);
        // let value = '01'; // in hexadecimal, in wei - this is 1 wei
        let value = transaction.value.substring(2); // in hexadecimal, in wei - this is about 18 ETC
        let data = transaction.data.substring(2); // some contract data
        // let data = null  // for no data
        let chain_id = 5777; // 1 for ETH, 61 for ETC
        return new Promise (function (resolve,reject) {
            trezor.ethereumSignTx(
                address_n,
                nonce,
                gas_price,
                gas_limit,
                to,
                value,
                data,
                chain_id,
                function (response) {
                    if (response.success) {

                        console.log('Signature V (recovery parameter):', response.v); // number
                        console.log('Signature R component:', response.r); // bytes
                        console.log('Signature S component:', response.s); // bytes
                        resolve(response);

                    } else {
                        console.error('Error:', response.error); // error message
                        resolve(null);
                    }

                });
        })
    }

    getTrezorAddress = async() => {
        let trezor=  await this.getTrezor();
        // spend one change output
        let address_n = "m/44'/60'/0'/0/0";
        trezor.ethereumGetAddress(address_n, function (result) {
            if (result.success) { // success
                console.log('Address: ', result.address);
            } else {
                console.error('Error:', result.error); // error message
            }
        });
    }


    getTrezor = async() => {
        let trezorC;
        await getTrezorConnect
            .then(trezorConnect => {
                trezorC= trezorConnect;
            })
            .catch((error) => {
                console.log(error)
            })
        return trezorC;

    }

 sendTransaction= async(address, amount, id)=>{
        let tokenInstance = this.props.smartContractInstance;

        let getData = tokenInstance.mint.getData(address, amount);

        let tx = {
            nonce: '0x00',
            gasPrice: '0x09184e72a000',
            gasLimit: '0x2710',
            to: CONTRACT_ADDRESS,
            value: '0x00',
            from:CONTRACT_OWNER_ADDRESS,
            data: getData
        };
        let response = await this.trezorSignTx(tx);

        let web3;
        let _this = this;
        if (response!=null){
            getWeb3
                .then(results => {
                    web3= results.web3;
                    let v = response.v.toString();
                    if (v.length % 2 != 0){
                        v="0"+v;
                    }
                    tx.r=Buffer.from(response.r,'hex');
                    tx.v=Buffer.from(v,'hex');
                    tx.s=Buffer.from(response.s,'hex');
                    let ethtx = new ethereumjs(tx);
                    console.dir(ethtx.getSenderAddress().toString('hex'), );
                    const serializedTx = ethtx.serialize();
                    const rawTx = '0x' + serializedTx.toString('hex');
                    console.log(rawTx);
                    //finally pass this data parameter to send Transaction
                    web3.eth.sendRawTransaction(rawTx, function (error, result) {
                        if(!error){
                            _this.props.addTokens(id)
                                .then(()=>{
                                        _this.setState({modalOpen: true});
                                        _this.props.getAllTransactions();
                                    }
                                );
                        }else{
                            alert(error)
                        }
                    });
                })
                .catch((error) => {
                    console.log(error)
                })
        }else{
            alert("There was an error signing with trezor hardware wallet")
        }


    }

getTrezorConnect函数只是异步获取window.trezorConnect,因为该对象是作为脚本注入的

<script src="https://connect.trezor.io/4/connect.js"></script>


let getTrezorConnect = new Promise(function(resolve, reject) {
    // Wait for loading completion
    window.addEventListener('load', function() {

        let trezorConnect = window.TrezorConnect

            return resolve(trezorConnect)


})});

export default getTrezorConnect

2 个答案:

答案 0 :(得分:2)

好吧,经过大量的尝试,我们设法将与Trezor签署的原始交易发送到 Ropsten 松露(请参阅答案底部的编辑)还有一个本地的私人 Geth 网络,因此代码没问题,Trezor在这些环境中的集成没有问题

https://ropsten.etherscan.io/address/0x89e2c46b22881f747797cf67310aad1a831d50b7

为了能够将已签名的事务发送到Ropsten testnet,我已经更改了这些内容。

这假设您已将合同部署到Ropsten并且您拥有合同地址。

1)获取Trezor帐户的地址

  getTrezorAddress = async() => {
        let trezor=  await this.getTrezor();
        // spend one change output
        let address_n = "m/44'/1'/0'/0/0";
        trezor.ethereumGetAddress(address_n, function (result) {
            if (result.success) { // success
                console.log('Address: ', result.address);
            } else {
                console.error('Error:', result.error); // error message
            }
        });
    }

2)将trezor地址放入原始事务的from字段中,通过获取该地址的事务计数来获取事务的nonce。重要提示:使用getTransactionCount上的“pending”可选参数来获取帐户的所有交易,否则您将重写未决交易。

getNonce = async(address) => {

        let web3 = await this.getWeb3();
        return new Promise (function (resolve,reject) {
            web3.eth.getTransactionCount(address, "pending", function (error,result){
                console.log("Nonce "+result);
                resolve(result);


            });
        });

    }

let count = null;
        await this.getNonce("0xedff546ac229317df81ef9e6cb3b67c0e6425fa7").then(result => {
            if(result.length % 2 !==0){
                result = "0"+result;
            }
            count = "0x"+result;

       });

let tx = {
            nonce: count ,
            gasPrice: web3.toHex(gasPriceGwei*1e9),
            gasLimit: web3.toHex(gasLimit),
            to: CONTRACT_ADDRESS,
            value: '0x00',
            data: getData,
            chainId:chainId,
            from:"yourTrezzorAddress"
        };

3)r,s,v参数不正确,处理它们的正确方法是获取trezor响应的值并将其转换为hexa:

// response is the Trezor sign response
tx.v= response.v;
tx.r="0x"+response.r;
tx.s="0x"+response.s;
let ethtx = new ethereumjs(tx);.
const serializedTx = ethtx.serialize();
const rawTx = '0x' + serializedTx.toString('hex');
 //finally pass this data parameter to send Transaction
web3.eth.sendRawTransaction(rawTx, someCallbackFunction);

重要提示:ropsten中的挖掘时间将介于15到30秒之间,因此如果在someCallbackFunction中使用散列检查事务接收,则结果将为null,因为事务处于挂起状态。 / p>

4)要在ropsten进行测试,我们使用Infura,因此我们更改了web3提供商:

import Web3 from 'web3'
import HDWalletProvider from "truffle-hdwallet-provider";

let getWeb3 = new Promise(function(resolve, reject) {
    // Wait for loading completion to avoid race conditions with web3 injection timing.
    window.addEventListener('load', function() {
        let results
        let web3 = window.web3

        // Checking if Web3 has been injected by the browser (Mist/MetaMask)
        if (typeof web3 !== 'undefined') {
            // Use Mist/MetaMask's provider.
            web3 = new Web3(web3.currentProvider)

            results = {
                web3: web3
            }

            console.log('Injected web3 detected.');

            return resolve(results)
        } else {
            // Fallback to localhost if no web3 injection. We've configured this to
            // use the development console's port by default.
            // let provider = new Web3.providers.HttpProvider("https://ropsten.infura.io/your_infura_api_key")

            let mnemonic = "infura mnemonic"
            let provider = new HDWalletProvider(mnemonic, "https://ropsten.infura.io/your_infura_api_key")
            web3 = new Web3(provider)

            results = {
                web3: web3
            }

            console.log('No web3 instance injected, using Local web3.');

            return resolve(results)
        }
    })
})

export default getWeb3

修改

这也适用于松露!查看此问题的最新评论https://github.com/trufflesuite/truffle/issues/973

答案 1 :(得分:0)

我们开发了一个小型库来将 Truffle 与 Trezor 硬件钱包结合使用:https://github.com/rariblecom/trezor-provider

可以这样使用:

const { createProvider } = require('@rarible/trezor-provider')

module.exports = {
    networks: {
        ropsten: {
            provider: function() {
                //websocket and http urls are supported
                return createProvider({ url: "{infura or other}", path: "m/44'/60'/0'/0/0", chainId: 3 }) 
            },
            network_id: 3
        }
    }
};