Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

EXPERIMENTAL #10515

Merged
merged 4 commits into from
Aug 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 10 additions & 72 deletions packages/protocol/lib/signing-utils.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,12 @@
// Originally taken from https://github.com/ethereum/web3.js/blob/1.x/packages/web3-eth-accounts/src/index.js

import { inputCeloTxFormatter } from '@celo/connect/lib/utils/formatter'
import { parseSignature } from '@celo/utils/lib/signatureUtils'
import { account as Account, bytes, hash, nat, RLP } from 'eth-lib'
import _ from 'underscore'
import { LocalWallet } from '@celo/wallet-local'
import { account as Account } from 'eth-lib'
import Web3 from 'web3'
import { numberToHex } from 'web3-utils'

function isNot(value: any) {
return _.isUndefined(value) || _.isNull(value)
}

function trimLeadingZero(hex: string) {
while (hex && hex.startsWith('0x0')) {
hex = '0x' + hex.slice(3)
}
return hex
}

function makeEven(hex: string) {
if (hex.length % 2 === 1) {
hex = hex.replace('0x', '0x0')
}
return hex
return value === null || value === undefined
}

export const getParsedSignatureOfAddress = async (web3: Web3, address: string, signer: string) => {
Expand All @@ -32,13 +16,12 @@ export const getParsedSignatureOfAddress = async (web3: Web3, address: string, s
}

export async function signTransaction(web3: Web3, txn: any, privateKey: string) {
let result: any

if (!txn) {
throw new Error('No transaction object given!')
}

const signed = (tx: any) => {
const signed = async (tx: any) => {
if (!tx.gas && !tx.gasLimit) {
throw new Error('"gas" is missing')
}
Expand All @@ -47,61 +30,16 @@ export async function signTransaction(web3: Web3, txn: any, privateKey: string)
throw new Error('Gas, gasPrice, nonce or chainId is lower than 0')
}
try {
tx = inputCeloTxFormatter(tx)
console.info('protocol signing-util', tx)
const wallet = new LocalWallet()

const transaction = tx
transaction.to = tx.to || '0x'
transaction.data = tx.data || '0x'
transaction.value = tx.value || '0x'
transaction.chainId = numberToHex(tx.chainId)
transaction.feeCurrency = tx.feeCurrency || '0x'
transaction.gatewayFeeRecipient = tx.gatewayFeeRecipient || '0x'
transaction.gatewayFee = tx.gatewayFee || '0x'
wallet.addAccount(privateKey)

const rlpEncoded = RLP.encode([
bytes.fromNat(transaction.nonce),
bytes.fromNat(transaction.gasPrice),
bytes.fromNat(transaction.gas),
transaction.feeCurrency.toLowerCase(),
transaction.gatewayFeeRecipient.toLowerCase(),
bytes.fromNat(transaction.gatewayFee),
transaction.to.toLowerCase(),
bytes.fromNat(transaction.value),
transaction.data,
bytes.fromNat(transaction.chainId || '0x1'),
'0x',
'0x',
])
return wallet.signTransaction(tx)

const messageHash = hash.keccak256(rlpEncoded)

const signature = Account.makeSigner(nat.toNumber(transaction.chainId || '0x1') * 2 + 35)(
hash.keccak256(rlpEncoded),
privateKey
)

const rawTx = RLP.decode(rlpEncoded).slice(0, 9).concat(Account.decodeSignature(signature))

rawTx[9] = makeEven(trimLeadingZero(rawTx[9]))
rawTx[10] = makeEven(trimLeadingZero(rawTx[10]))
rawTx[11] = makeEven(trimLeadingZero(rawTx[11]))

const rawTransaction = RLP.encode(rawTx)

const values = RLP.decode(rawTransaction)
result = {
messageHash,
v: trimLeadingZero(values[9]),
r: trimLeadingZero(values[10]),
s: trimLeadingZero(values[11]),
rawTransaction,
}
} catch (e) {
console.info('Error signing transaction', e)
throw e
}

return result
}

// Resolve immediately if nonce, chainId and price are provided
Expand All @@ -110,7 +48,7 @@ export async function signTransaction(web3: Web3, txn: any, privateKey: string)
}

// Otherwise, get the missing info from the Ethereum Node
const chainId = isNot(txn.chainId) ? await web3.eth.net.getId() : txn.chainId
const chainId = isNot(txn.chainId) ? await web3.eth.getChainId() : txn.chainId
const gasPrice = isNot(txn.gasPrice) ? await web3.eth.getGasPrice() : txn.gasPrice
const nonce = isNot(txn.nonce)
? await web3.eth.getTransactionCount(Account.fromPrivate(privateKey).address)
Expand All @@ -122,5 +60,5 @@ export async function signTransaction(web3: Web3, txn: any, privateKey: string)
JSON.stringify({ chainId, gasPrice, nonce })
)
}
return signed(_.extend(txn, { chainId, gasPrice, nonce }))
return signed({...txn, chainId, gasPrice, nonce })
}
40 changes: 20 additions & 20 deletions packages/protocol/lib/web3-utils.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
/* tslint:disable:no-console */
// TODO(asa): Refactor and rename to 'deployment-utils.ts'
import { Address, CeloTxObject } from '@celo/connect';
import { setAndInitializeImplementation } from '@celo/protocol/lib/proxy-utils';
import { CeloContractName } from '@celo/protocol/lib/registry-utils';
import { signTransaction } from '@celo/protocol/lib/signing-utils';
import { privateKeyToAddress } from '@celo/utils/lib/address';
import { BuildArtifacts } from '@openzeppelin/upgrades';
import { BigNumber } from 'bignumber.js';

import { createInterfaceAdapter } from '@truffle/interface-adapter';
import path from 'path';
import prompts from 'prompts';
import { GoldTokenInstance, MultiSigInstance, OwnableInstance, ProxyContract, ProxyInstance, RegistryInstance } from 'types';
import { StableTokenInstance } from 'types/mento';
import Web3 from 'web3';
import { ContractPackage } from '../contractPackages';
import { ArtifactsSingleton } from './artifactsSingleton';
import { Address, CeloTxObject } from '@celo/connect'
import { setAndInitializeImplementation } from '@celo/protocol/lib/proxy-utils'
import { CeloContractName } from '@celo/protocol/lib/registry-utils'
import { signTransaction } from '@celo/protocol/lib/signing-utils'
import { privateKeyToAddress } from '@celo/utils/lib/address'
import { BuildArtifacts } from '@openzeppelin/upgrades'
import { BigNumber } from 'bignumber.js'

import { createInterfaceAdapter } from '@truffle/interface-adapter'
import path from 'path'
import prompts from 'prompts'
import { GoldTokenInstance, MultiSigInstance, OwnableInstance, ProxyContract, ProxyInstance, RegistryInstance } from 'types'
import { StableTokenInstance } from 'types/mento'
import Web3 from 'web3'
import { ContractPackage } from '../contractPackages'
import { ArtifactsSingleton } from './artifactsSingleton'

const truffleContract = require('@truffle/contract');

Expand All @@ -39,8 +39,8 @@ export async function sendTransactionWithPrivateKey<T>(
from: address,
})
}
console.info('signing tx with', address )
const signedTx: any = await signTransaction(
console.info('signing tx with', address)
const signedTx = await signTransaction(
web3,
{
...txArgs,
Expand All @@ -53,8 +53,8 @@ export async function sendTransactionWithPrivateKey<T>(
privateKey
)

const rawTransaction = signedTx.rawTransaction.toString('hex')
console.info('sending tx', rawTransaction)
const rawTransaction = signedTx.raw
console.info('sending tx',signedTx.tx, rawTransaction)
return web3.eth.sendSignedTransaction(rawTransaction)
}

Expand Down
1 change: 0 additions & 1 deletion packages/protocol/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@
"@types/mocha": "^7.0.2",
"@types/targz": "^1.0.0",
"@types/tmp": "^0.1.0",
"@types/underscore": "^1.8.8",
"@types/yargs": "^13.0.2",
"cross-env": "^5.1.6",
"eth-gas-reporter": "^0.2.16",
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk/wallets/wallet-base/src/signing-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export function stringNumberOrBNToHex(
if (typeof num === 'string' || typeof num === 'number' || num === undefined) {
return stringNumberToHex(num)
} else {
return makeEven(`0x` + num.toString('hex')) as `0x${string}`
return makeEven(`0x` + num.toString(16)) as `0x${string}`
}
}
function stringNumberToHex(num?: number | string): `0x${string}` {
Expand Down
5 changes: 0 additions & 5 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6868,11 +6868,6 @@
resolved "https://registry.yarnpkg.com/@types/triple-beam/-/triple-beam-1.3.2.tgz#38ecb64f01aa0d02b7c8f4222d7c38af6316fef8"
integrity sha512-txGIh+0eDFzKGC25zORnswy+br1Ha7hj5cMVwKIU7+s0U2AxxJru/jZSMU6OC9MJWP6+pc/hc6ZjyZShpsyY2g==

"@types/underscore@^1.8.8":
version "1.11.4"
resolved "https://registry.yarnpkg.com/@types/underscore/-/underscore-1.11.4.tgz#62e393f8bc4bd8a06154d110c7d042a93751def3"
integrity sha512-uO4CD2ELOjw8tasUrAhvnn2W4A0ZECOvMjCivJr4gA9pGgjv+qxKWY9GLTMVEK8ej85BxQOocUyE7hImmSQYcg==

"@types/utf8@^2.1.6":
version "2.1.6"
resolved "https://registry.yarnpkg.com/@types/utf8/-/utf8-2.1.6.tgz#430cabb71a42d0a3613cce5621324fe4f5a25753"
Expand Down