signTransaction: function(txParams, cb){ try { // console.log('signing tx:', txParams) var tx = new Transaction({ nonce: txParams.nonce, to: txParams.to, value: txParams.value, data: txParams.input, gasPrice: txParams.gasPrice, gasLimit: txParams.gas, }) tx.sign(privateKey) var serializedTx = '0x'+tx.serialize().toString('hex') // deserialize and dump values to confirm configuration var verifyTx = new Transaction(tx.serialize()) console.log('signed transaction:', { to: '0x'+verifyTx.to.toString('hex'), from: '0x'+verifyTx.from.toString('hex'), nonce: '0x'+verifyTx.nonce.toString('hex'), value: (ethUtil.bufferToInt(verifyTx.value)/1e18)+' ether', data: '0x'+verifyTx.data.toString('hex'), gasPrice: '0x'+verifyTx.gasPrice.toString('hex'), gasLimit: '0x'+verifyTx.gasLimit.toString('hex'), }) cb(null, serializedTx) } catch (err) { cb(err) } },
return newContract( contracts.Test, { from: client, gas: 3141592 }).then( deployed => { let code = web3.eth.getCode(deployed.address); let abi = deployed.abi; let privKey = util.stripHexPrefix(keys[0]); let privKeyNonClient = util.stripHexPrefix(keys[3]); let brokeKey = util.stripHexPrefix(keys[0]); let goodTxOptions = { gasPrice: 1, gasLimit: 3000000, data: util.stripHexPrefix(code)}; let badTxOptions = { gasPrice: 1, gasLimit: 0, data: util.stripHexPrefix(code)}; let callTxOptions = { data: util.stripHexPrefix(code)}; goodTxOptions.to = util.stripHexPrefix(deployed.address); badTxOptions.to = util.stripHexPrefix(deployed.address); callTxOptions.to = util.stripHexPrefix(deployed.address); let goodTxSet = wallet.txutils.functionTx(abi, 'setState', [2], goodTxOptions); let badTxSet = wallet.txutils.functionTx(abi, 'setState', [2], badTxOptions); let callTxSet = wallet.txutils.functionTx(abi, 'getVerified', [], callTxOptions); goodTxSet = util.stripHexPrefix(goodTxSet); badTxSet = util.stripHexPrefix(badTxSet); callTxSet = util.stripHexPrefix(callTxSet); let goodTx = new Transaction(new Buffer(goodTxSet, 'hex')); let goodTxNonClient = new Transaction(new Buffer(goodTxSet, 'hex')); let badTx = new Transaction(new Buffer(badTxSet, 'hex')); let brokeTx = new Transaction(new Buffer(goodTxSet, 'hex')); let callTx = new Transaction(new Buffer(callTxSet, 'hex')); goodTx.sign(new Buffer(privKey, 'hex')); goodTxNonClient.sign(new Buffer(privKeyNonClient, 'hex')); badTx.sign(new Buffer(privKey, 'hex')); brokeTx.sign(new Buffer(brokeKey, 'hex')); //callTx.sign(new Buffer(privKey, 'hex')); callTx = callTx.toJSON(); goodTx = goodTx.serialize().toString('hex'); goodTxNonClient = goodTxNonClient.serialize().toString('hex'); badTx = badTx.serialize().toString('hex'); brokeTx = brokeTx.serialize().toString('hex'); return { deployed: deployed, goodTx: goodTx, goodTxNonClient: goodTxNonClient, badTx: badTx, brokeTx: brokeTx, abi: abi, callGetVerified: [callTx[3],callTx[5]] } });
signTransaction: function (tx_params, callback) { //tx_params.nonce = '0x01'; tx_params.gasPrice = '0xba43b7400'; tx_params.gasLimit = '0x271000'; tx_params.value = '0x01'; console.log(tx_params); var tx = new ethereumjsTx(tx_params); console.log(tx); tx.sign(privateKey); var senderAddress = ethereumjsUtil.bufferToHex(tx.getSenderAddress()); console.log('senderAddress', senderAddress); var balance = web3.eth.getBalance(senderAddress); console.log('balance', balance.toString()); var buffer = new Buffer(tx.serialize()); var signedTx = ethereumjsUtil.bufferToHex(buffer); console.log('signedTx', signedTx); callback(null, ethereumjsUtil.stripHexPrefix(signedTx)); }
}, function(err, results) { if (err) return console.error(err); var func = new SolidityFunction(web3, abi[0], ''); var data = func.toPayload([$('#arg').val()]).data; var tx = new ethTx({ to: contract.address, nonce: results.nonce, gasLimit: '0x100000', gasPrice: '0x' + results.gasPrice.toString(16), data: data }); tx.sign(new Buffer('974f963ee4571e86e5f9bc3b493e453db9c15e5bd19829a4ef9a790de0da0015', 'hex')); web3.eth.sendRawTransaction('0x' + tx.serialize().toString('hex'), function(err, txHash) { if (err) return console.error(err); var blockFilter = web3.eth.filter('latest'); blockFilter.watch(function() { web3.eth.getTransactionReceipt(txHash, function(err, receipt) { if (err) return console.error(err); if (receipt) { blockFilter.stopWatching(); console.log(receipt); } }); }); }); });
KeyStore.prototype.signTx = function (rawTx, password, signingAddress) { rawTx = strip0x(rawTx); signingAddress = strip0x(signingAddress); if (this.addresses.length === 0) { throw new Error('KeyStore.signTx: No private keys in KeyStore.'); } var address = ''; if (signingAddress === undefined) { address = this.addresses[0]; } else { if (this.encPrivKeys[signingAddress] === undefined) { throw new Error('KeyStore.signTx: Address not found in KeyStore'); } address = signingAddress; } var encKey = this.generateEncKey(password); var txCopy = new Transaction(new Buffer(rawTx, 'hex')); var encPrivKey = this.encPrivKeys[address]; var privKey = KeyStore._decryptKey(encPrivKey, encKey); var addrFromPrivKey = KeyStore._computeAddressFromPrivKey(privKey); if (addrFromPrivKey !== address) { throw new Error('KeyStore.signTx: Decrypting private key failed!'); } txCopy.sign(new Buffer(privKey, 'hex')); privKey = ''; return txCopy.serialize().toString('hex'); };
}, function (err, results) { if (err) { return callback(err, null); } else // return callback(null, results); try { // console.log("---", results); if (web3.utils.toWei(results.balance, 'ether') < (results.gasEstimate * results.gasPrice)) { return callback('low balance', null); } else { var tx = new Tx({ to: contractObj.options.address, nonce: results.nonce, gasPrice: web3.utils.toHex(results.gasPrice), gasLimit: web3.utils.toHex(results.gasEstimate), data: functionData }); tx.sign(new Buffer(privateKey, 'hex')); web3.eth.sendSignedTransaction('0x' + tx.serialize().toString('hex'), function (err, response) { if (err) { return callback(err, null); } else return callback(null, response); }); } } catch (e) { return callback(e, null); } });
export function createSignedTx (netVersion, signature, unsignedTx) { const chainId = parseInt(netVersion, 10); const { data, gasPrice, gasLimit, nonce, to, value } = unsignedTx; const r = Buffer.from(signature.substr(2, 64), 'hex'); const s = Buffer.from(signature.substr(66, 64), 'hex'); const v = Buffer.from([parseInt(signature.substr(130, 2), 16) + (chainId * 2) + 35]); const tx = new Transaction({ chainId, data, gasPrice, gasLimit, nonce, to, value, r, s, v }); return { chainId, rlp: inHex(tx.serialize().toString('hex')), tx }; }
.then((_nonce) => { const chainId = parseInt(netVersion, 10); const nonce = (!transaction.nonce || transaction.nonce.isZero()) ? _nonce : transaction.nonce; const tx = new Transaction({ chainId, data: inHex(data), gasPrice: inHex(gasPrice), gasLimit: inHex(gas), nonce: inHex(nonce), to: to ? inHex(to) : undefined, value: inHex(value), r: 0, s: 0, v: chainId }); const rlp = inHex(tx.serialize().toString('hex')); const hash = sha3(rlp); return { chainId, hash, nonce, rlp, tx }; });
KeyStore.prototype.signTransaction = function (txParams, callback) { var ethjsTxParams = {}; ethjsTxParams.from = add0x(txParams.from); ethjsTxParams.to = add0x(txParams.to); ethjsTxParams.gasLimit = add0x(txParams.gas); ethjsTxParams.gasPrice = add0x(txParams.gasPrice); ethjsTxParams.nonce = add0x(txParams.nonce); ethjsTxParams.value = add0x(txParams.value); ethjsTxParams.data = add0x(txParams.data); var txObj = new Transaction(ethjsTxParams); var rawTx = txObj.serialize().toString('hex'); var signingAddress = strip0x(txParams.from); var self = this; this.passwordProvider( function (err, password) { if (err) return callback(err); KeyStore.deriveKeyFromPassword(password, function (err, pwDerivedKey) { if (err) return callback(err); var signedTx = signing.signTx(self, pwDerivedKey, rawTx, signingAddress, self.defaultHdPathString); callback(null, '0x' + signedTx); }) }) };
return new Bluebird((resolve, reject) => { const ethereumTransaction = new EthereumTransaction({ to: transaction.tx.to, from: transaction.tx.from, data: transaction.tx.data, value: transaction.tx.value, gasLimit: transaction.tx.gasLimit, gasPrice: transaction.tx.gasPrice, nonce: job.data.currentNonce, }) ethereumTransaction.sign(config.blockchain.signerPrivateKeyBuffer) const transactionData = `0x${ethereumTransaction.serialize().toString('hex')}` eth.sendSignedTransaction(transactionData) .once('transactionHash', (transactionHash) => { transaction.tx.hash = transactionHash transaction.status = 'pending' transaction.markModified('tx') transaction.save() // increase the nonce after we know this transaction was // submitted to the blockchain successfully job.data.currentNonce += 1 resolve() }) .on('error', (error) => { logger.error(`[${this.name}]`, `sendTransaction failed for ${transaction.id}:`, error) transaction.tx.error = error.toString() transaction.status = 'error' transaction.markModified('tx') transaction.save() // sometimes an error event is emitted when the nonce should // NOT increase (for example, bad TX params?), so we can't // reliably increment the nonce here - instead let's just // get the current TX count and set the nonce to that return eth.getTransactionCount(config.blockchain.signerPublicAddress) .then((currentNonce) => { job.data.currentNonce = currentNonce // @NOTE: don't reject when there's an error, since we // don't want to prevent any subsequent transactions in // this batch from running - just marking the // transaction as failed is good enough for now resolve() }) }) })
.then(function(privateKey) { var secret, tx, serializedTx; secret = new Buffer(privateKey, 'hex'); tx = new EthereumTx(rawTx); tx.sign(secret); serializedTx = '0x' + tx.serialize().toString('hex'); callback(null, serializedTx); })
.then((gasPrice) => { tx_params.gasPrice = gasPrice; tx_params.gasLimit = 22000; console.log(tx_params, 'tx_params'); var tx = new Transaction(tx_params); tx.sign(privkey); var rawTx = tx.serialize().toString('hex'); callback(null, '0x'+rawTx); });
async function signTransaction(txData) { const path = addressToPathMap[txData.from.toLowerCase()]; if (!path) throw new Error("address unknown '" + txData.from + "'"); const transport = await getTransport(); try { const eth = new AppEth(transport); const tx = new EthereumTx(txData); // Set the EIP155 bits tx.raw[6] = Buffer.from([networkId]); // v tx.raw[7] = Buffer.from([]); // r tx.raw[8] = Buffer.from([]); // s // Pass hex-rlp to ledger for signing const result = await eth.signTransaction( path, tx.serialize().toString("hex") ); // Store signature in transaction tx.v = Buffer.from(result.v, "hex"); tx.r = Buffer.from(result.r, "hex"); tx.s = Buffer.from(result.s, "hex"); // EIP155: v should be chain_id * 2 + {35, 36} const signedChainId = Math.floor((tx.v[0] - 35) / 2); const validChainId = networkId & 0xff; // FIXME this is to fixed a current workaround that app don't support > 0xff if (signedChainId !== validChainId) { throw makeError( "Invalid networkId signature returned. Expected: " + networkId + ", Got: " + signedChainId, "InvalidNetworkId" ); } return `0x${tx.serialize().toString("hex")}`; } finally { transport.close(); } }
signTransaction: function(rawTx, cb) { // dont include private key info anywhere around repo const privateKey = new Buffer(account.privateKey, 'hex'); // tx construction const tx = new Tx(rawTx); tx.sign(privateKey); // callback with buffered serilized signed tx cb(null, ethUtil.bufferToHex(tx.serialize())); },
self.getNonce(address, (newNonce) => { tx.nonce = newNonce; const key = ethUtil.stripHexPrefix(self.web3.eth.accounts.wallet[address].privateKey); const privKey = Buffer.from(key, 'hex'); tx.sign(privKey); payload.params[0] = '0x' + tx.serialize().toString('hex'); return realSend(payload, (error, result) => { self.web3.eth.getTransaction(result.result, () => { callback(error, result); }); }); });
web3.eth.getTransactionCount(senderAccount, function(error, number) { var transactionSequenceNumber = number; var paramBytes, rawTx, tx, serializedTx; // need to append bytecoded constructor params into tail of contract code paramBytes = _this.encodeConstructorParams(contract.abi, constructorParams); rawTx = { nonce: web3.toHex(transactionSequenceNumber), gasPrice: web3.toHex(gasPrice.toString()), gasLimit: web3.toHex(gasLimit), data: '0x' + contract.code + paramBytes, }; tx = new EthereumTx(rawTx); tx.sign(privateKey); serializedTx = tx.serialize(); web3.eth.sendRawTransaction(serializedTx.toString('hex'), function(error, transactionHash) { if (error) return reject(error); // console.log('...contract submitted - TX:', transactionHash); var count = 0; var filter = web3.eth.filter('latest', function() { // for each block write, look for transaction receipt // and give up after 50 blocks count++; web3.eth.getTransactionReceipt(transactionHash, function(error, receipt) { if (error) return reject(error); if (receipt || count > 50) { if (!receipt) return reject(new Error('...gave up waiting for contract to be mined')); filter.stopWatching(); // console.log('...contract mined'); // console.log('====transaction====='); // console.log(JSON.stringify({ // sender: senderAccount, // rawTx: rawTx, // }, null, 2)); // console.log(); // console.log('=======receipt======='); // console.log(JSON.stringify(receipt, null, 2)); // console.log(); // console.log('====== A B I ======='); // console.log(JSON.stringify(contract.abi)); // console.log(); receipt.sender = senderAccount; // just because resolve(receipt); } }); }); }); });
function valueTx (txObject) { // txObject contains gasPrice, gasLimit, value, nonce var txObjectCopy = {}; txObjectCopy.to = add0x(txObject.to); txObjectCopy.gasPrice = add0x(txObject.gasPrice); txObjectCopy.gasLimit = add0x(txObject.gasLimit); txObjectCopy.nonce = add0x(txObject.nonce); txObjectCopy.value = add0x(txObject.value); var tx = new Transaction(txObjectCopy); return tx.serialize().toString('hex'); }
mutex.lock(function () { for (var rawTxHash in augur.rpc.rawTxs) { if (!augur.rpc.rawTxs.hasOwnProperty(rawTxHash)) continue; if (augur.rpc.rawTxs[rawTxHash].nonce === packaged.nonce) { ++packaged.nonce; break; } } mutex.unlock(); var etx = new ethTx(packaged); // sign, validate, and send the transaction etx.sign(self.account.privateKey); // transaction validation if (!etx.validate()) return cb(errors.TRANSACTION_INVALID); // send the raw signed transaction to geth augur.rpc.sendRawTx(etx.serialize().toString("hex"), function (res) { var err; if (res) { if (res.error) { if (res.message.indexOf("rlp") > -1) { err = clone(errors.RLP_ENCODING_ERROR); err.bubble = res; err.packaged = packaged; return cb(err); } else if (res.message.indexOf("nonce") > -1) { ++packaged.nonce; return self.submitTx(packaged, cb); } else { err = clone(errors.RAW_TRANSACTION_ERROR); err.bubble = res; err.packaged = packaged; return cb(err); } } // res is the txhash if nothing failed immediately // (even if the tx is nulled, still index the hash) augur.rpc.rawTxs[res] = {tx: packaged}; // nonce ok, execute callback return cb(res); } cb(errors.TRANSACTION_FAILED); }); });
function createContractTx (fromAddress, txObject) { // txObject contains gasPrice, gasLimit, value, data, nonce var txObjectCopy = {}; txObjectCopy.to = add0x(txObject.to); txObjectCopy.gasPrice = add0x(txObject.gasPrice); txObjectCopy.gasLimit = add0x(txObject.gasLimit); txObjectCopy.nonce = add0x(txObject.nonce); txObjectCopy.data = add0x(txObject.data); txObjectCopy.value = add0x(txObject.value); var contractAddress = createdContractAddress(fromAddress, txObject.nonce); var tx = new Transaction(txObjectCopy); return {tx: tx.serialize().toString('hex'), addr: contractAddress}; }
return TrezorConnect.signEthereumTx(getTrezorHDPath(chainId), nonce, gasPrice, gasLimit, to, value, data, chainId, ({ error, success, r, s, v }: TrezorSignResultType) => { if (!success) { console.error('signTrezorTransaction', error); reject(new Error(error)); return; } const tx: EthereumTx = createRawTransaction(transaction); tx.r = Buffer.from(r, 'hex'); tx.s = Buffer.from(s, 'hex'); tx.v = Buffer.from([v]); resolve(`0x${tx.serialize().toString('hex')}`); });
]).then(function (results) { var transaction = new EthereumTx({ to: utils.ensureAddress(address), gasPrice: utils.hexlify(results[1]), gasLimit: utils.hexlify(3000000), nonce: utils.hexlify(results[0]), value: utils.hexlify(amountWei) }); transaction.sign(privateKey); var signedTransaction = utils.hexlify('0x' + transaction.serialize().toString('hex')); getWeb3Promise('sendRawTransaction', signedTransaction).then(function(txid) { resolve(txid); }, function(error) { reject(error); }); }, function(error) {
solc.loadRemoteVersion('latest', function (err, solcSnapshot) { console.log('Your current Solidity version is:\n\t', solcSnapshot.version()); var output = solcSnapshot.compile(source, 1); var browser_untitled_sol_ababContract = web3.eth.contract(JSON.parse(output.contracts[':Abab'].interface)); let nonce = web3.eth.getTransactionCount(account_address); let privateKey = new Buffer(account_private, 'hex'); let payloadData = '0x' + output.contracts[':Abab'].bytecode; let gasPriceHex = util.bufferToHex(21000000000); let gasLimitHex = util.bufferToHex(4000000); let nonceHex = util.bufferToHex(nonce); let tx = new Tx({ nonce: nonceHex, gasPrice: gasPriceHex, gasLimit: gasLimitHex, to: '', from: account_address, value: '0x00', data: payloadData, chainId: 3 // 3 == testnet ropsten ,1 == original }); tx.sign(privateKey); let serializedTx = tx.serialize(); web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function (err, hash) { console.log('Contract send tx:' + hash); console.log('Wait confirm transaction... (1 - 5 min)'); let checkTx = setInterval(function () { let txData = web3.eth.getTransactionReceipt(hash); if (!txData) { console.log('Tx check.'); return false; } cb && cb(txData, output.contracts[':Abab'].interface, output.contracts[':Abab'].bytecode, source, solcSnapshot.version()); clearInterval(checkTx); }, 10000); }); });
signTx = function (keystore, pwDerivedKey, rawTx, signingAddress, hdPathString) { if (hdPathString === undefined) { hdPathString = keystore.defaultHdPathString; } rawTx = util.stripHexPrefix(rawTx); signingAddress = util.stripHexPrefix(signingAddress); var txCopy = new Transaction(new Buffer(rawTx, 'hex')); var privKey = keystore.exportPrivateKey(signingAddress, pwDerivedKey, hdPathString); txCopy.sign(new Buffer(privKey, 'hex')); privKey = ''; return txCopy.serialize().toString('hex'); };
var signTx = function (keystore, pwDerivedKey, rawTx, signingAddress) { if(!keystore.isDerivedKeyCorrect(pwDerivedKey)) { throw new Error("Incorrect derived key!"); } rawTx = util.stripHexPrefix(rawTx); signingAddress = util.stripHexPrefix(signingAddress); var txCopy = new Transaction(new Buffer(rawTx, 'hex')); var privKey = keystore.exportPrivateKey(signingAddress, pwDerivedKey); txCopy.sign(new Buffer(privKey, 'hex')); privKey = ''; return txCopy.serialize().toString('hex'); };
it("should suceed with right nonce (1)", function(done) { var provider = web3.currentProvider; var transaction = new Transaction({ "value": "0x10000000", "gasLimit": "0x33450", "from": accounts[0], "to": accounts[1], "nonce": "0x01" }) var secretKeyBuffer = Buffer.from(secretKeys[0].substr(2), 'hex') transaction.sign(secretKeyBuffer) web3.eth.sendRawTransaction(transaction.serialize(), function(err, result) { done(err) }) })
function (err) { if (!err) { nonce = nonce + 1; options.nonce = nonce; options.to = address; options.data = '0x' + sha3(functionName+"()").slice(0, 8) + coder.encodeParams(inputTypes, args); var tx = new Tx(options); tx.sign(new Buffer(privateKey, 'hex')); var serializedTx = tx.serialize().toString('hex'); var result = undefined; var url = 'http://'+(config.eth_testnet ? 'testnet' : 'api')+'.etherscan.io/api?module=proxy&action=eth_sendRawTransaction&hex='+serializedTx; request.get(url, function(err, httpResponse, body){ if (!err) { result = JSON.parse(body); callback([result['result'], nonce]); } }); } }
it("should fail with bad nonce (too high)", function(done) { var provider = web3.currentProvider; var transaction = new Transaction({ "value": "0x10000000", "gasLimit": "0x33450", "from": accounts[0], "to": accounts[1], "nonce": "0xff", // too low nonce }) var secretKeyBuffer = Buffer.from(secretKeys[0].substr(2), 'hex') transaction.sign(secretKeyBuffer) web3.eth.sendRawTransaction(transaction.serialize(), function(err, result) { assert(err.message.indexOf("the tx doesn't have the correct nonce. account has nonce of: 1 tx has nonce of: 255") >= 0); done() }) })
HDWallet.prototype.signTransaction = function (txParams, callback) { var ethjsTxParams = {}; ethjsTxParams.from = util.addHexPrefix(txParams.from); ethjsTxParams.to = util.addHexPrefix(txParams.to); ethjsTxParams.gasLimit = util.addHexPrefix(txParams.gas); ethjsTxParams.gasPrice = util.addHexPrefix(txParams.gasPrice); ethjsTxParams.nonce = util.addHexPrefix(txParams.nonce); ethjsTxParams.value = util.addHexPrefix(txParams.value); ethjsTxParams.data = util.addHexPrefix(txParams.data); var senderAddress = ethjsTxParams.from; var txObj = new Transaction(ethjsTxParams); var rawTx = txObj.serialize().toString('hex'); this.signRawTx(rawTx, senderAddress, function(e,signedTx) { if (e) callback(e,null) else callback(null, '0x' + signedTx); }); };
handleQuestion: function(id, site, bounty, pkey) { var func = new SolidityFunction(this.app.web3, _.find(abi, { name: 'handleQuestion' }), ''); var data = func.toPayload([ id, site ]).data; var address = util.toAddress(pkey); var nonce = this.app.web3.eth.getTransactionCount(address); var gasPrice = this.app.web3.eth.gasPrice; var tx = new ethTx({ to: this.address, nonce: nonce, value: parseInt(this.app.web3.toWei(bounty, 'ether')), gasLimit: '0x100000', gasPrice: '0x' + gasPrice.toString(16), data: data }); tx.sign(new Buffer(pkey.substr(2), 'hex')); return this.app.web3.eth.sendRawTransaction('0x' + tx.serialize().toString('hex')); }
co(function* () { let gasPrice = yield web3.eth.getGasPrice(); let nonce = yield web3.eth.getTransactionCount(fromAccount); var rawTx = { nonce: nonce, gasPrice: web3.utils.toHex(gasPrice), gasLimit: web3.utils.toHex(90000), to: toAccount, value: web3.utils.toHex(amountToSend), data: '' } var tx = new Tx(rawTx); tx.sign(privateKey); var serializedTx = tx.serialize(); web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')) .on('receipt', console.log); })